Merge "Various WikiPage code cleanups"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.11
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-07T20:48:15Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * @property {Number}
49 */
50 OO.ui.elementId = 0;
51
52 /**
53 * Generate a unique ID for element
54 *
55 * @return {String} [id]
56 */
57 OO.ui.generateElementId = function () {
58 OO.ui.elementId += 1;
59 return 'oojsui-' + OO.ui.elementId;
60 };
61
62 /**
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
65 *
66 * @param {jQuery} element Element to test
67 * @return {boolean}
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var nodeName,
71 element = $element[ 0 ];
72
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
75 return false;
76 }
77
78 // Check if the element is visible
79 if ( !(
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
85 } ).length
86 ) ) {
87 return false;
88 }
89
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
92 return true;
93 }
94
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
98 return true;
99 }
100
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
106 return true;
107 }
108
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
111 return true;
112 }
113
114 return false;
115 };
116
117 /**
118 * Find a focusable child
119 *
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
123 */
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
130
131 if ( backwards ) {
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
133 }
134
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
138 $focusable = $this;
139 return false;
140 }
141 } );
142 return $focusable;
143 };
144
145 /**
146 * Get the user's language and any fallback languages.
147 *
148 * These language codes are used to localize user interface elements in the user's language.
149 *
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
152 *
153 * @return {string[]} Language codes, in descending order of priority
154 */
155 OO.ui.getUserLanguages = function () {
156 return [ 'en' ];
157 };
158
159 /**
160 * Get a value in an object keyed by language code.
161 *
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
166 */
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
168 var i, len, langs;
169
170 // Requested language
171 if ( obj[ lang ] ) {
172 return obj[ lang ];
173 }
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
177 lang = langs[ i ];
178 if ( obj[ lang ] ) {
179 return obj[ lang ];
180 }
181 }
182 // Fallback language
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
185 }
186 // First existing language
187 for ( lang in obj ) {
188 return obj[ lang ];
189 }
190
191 return undefined;
192 };
193
194 /**
195 * Check if a node is contained within another node
196 *
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
199 *
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
204 */
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
206 var i;
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
209 }
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
212 return true;
213 }
214 }
215 return false;
216 };
217
218 /**
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
223 *
224 * Ported from: http://underscorejs.org/underscore.js
225 *
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
229 * @return {Function}
230 */
231 OO.ui.debounce = function ( func, wait, immediate ) {
232 var timeout;
233 return function () {
234 var context = this,
235 args = arguments,
236 later = function () {
237 timeout = null;
238 if ( !immediate ) {
239 func.apply( context, args );
240 }
241 };
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
244 }
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
247 };
248 };
249
250 /**
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
253 *
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
257 */
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
261 } else {
262 node.attachEvent( 'on' + eventName, handler );
263 }
264 };
265
266 /**
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
269 *
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
273 */
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
277 } else {
278 node.detachEvent( 'on' + eventName, handler );
279 }
280 };
281
282 /**
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
285 *
286 * This is an alias for `OO.ui.Element.static.infuse()`.
287 *
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
292 */
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
295 };
296
297 ( function () {
298 /**
299 * Message store for the default implementation of OO.ui.msg
300 *
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
303 *
304 * @private
305 */
306 var messages = {
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
339 };
340
341 /**
342 * Get a localized message.
343 *
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
346 * English messages.
347 *
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
352 *
353 * @abstract
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
357 */
358 OO.ui.msg = function ( key ) {
359 var message = messages[ key ],
360 params = Array.prototype.slice.call( arguments, 1 );
361 if ( typeof message === 'string' ) {
362 // Perform $1 substitution
363 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
364 var i = parseInt( n, 10 );
365 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
366 } );
367 } else {
368 // Return placeholder if message not found
369 message = '[' + key + ']';
370 }
371 return message;
372 };
373
374 /**
375 * Package a message and arguments for deferred resolution.
376 *
377 * Use this when you are statically specifying a message and the message may not yet be present.
378 *
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
382 */
383 OO.ui.deferMsg = function () {
384 var args = arguments;
385 return function () {
386 return OO.ui.msg.apply( OO.ui, args );
387 };
388 };
389
390 /**
391 * Resolve a message.
392 *
393 * If the message is a function it will be executed, otherwise it will pass through directly.
394 *
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
397 */
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
400 return msg();
401 }
402 return msg;
403 };
404
405 /**
406 * @param {string} url
407 * @return {boolean}
408 */
409 OO.ui.isSafeUrl = function ( url ) {
410 var protocol,
411 // Keep in sync with php/Tag.php
412 whitelist = [
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
416 ];
417
418 if ( url.indexOf( ':' ) === -1 ) {
419 // No protocol, safe
420 return true;
421 }
422
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
426 return true;
427 }
428
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
431 };
432
433 } )();
434
435 /*!
436 * Mixin namespace.
437 */
438
439 /**
440 * Namespace for OOjs UI mixins.
441 *
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
446 *
447 * @class
448 * @singleton
449 */
450 OO.ui.mixin = {};
451
452 /**
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
457 *
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
461 *
462 * @example
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
465 * }
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
467 *
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
471 * ];
472 *
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
477 * this.$body.append( this.content.$element );
478 * };
479 * MessageDialog.prototype.getBodyHeight = function () {
480 * return 100;
481 * }
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
483 * var dialog = this;
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
487 * .next( 1000 )
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
490 * } );
491 * }
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
493 * };
494 *
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
497 *
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
501 *
502 * @abstract
503 * @class
504 *
505 * @constructor
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
508 */
509 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
510 // Configuration initialization
511 config = config || {};
512
513 // Properties
514 this.pending = 0;
515 this.$pending = null;
516
517 // Initialisation
518 this.setPendingElement( config.$pending || this.$element );
519 };
520
521 /* Setup */
522
523 OO.initClass( OO.ui.mixin.PendingElement );
524
525 /* Methods */
526
527 /**
528 * Set the pending element (and clean up any existing one).
529 *
530 * @param {jQuery} $pending The element to set to pending.
531 */
532 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
533 if ( this.$pending ) {
534 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
535 }
536
537 this.$pending = $pending;
538 if ( this.pending > 0 ) {
539 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
540 }
541 };
542
543 /**
544 * Check if an element is pending.
545 *
546 * @return {boolean} Element is pending
547 */
548 OO.ui.mixin.PendingElement.prototype.isPending = function () {
549 return !!this.pending;
550 };
551
552 /**
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
555 *
556 * @chainable
557 */
558 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
559 if ( this.pending === 0 ) {
560 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
562 }
563 this.pending++;
564
565 return this;
566 };
567
568 /**
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
571 *
572 * @chainable
573 */
574 OO.ui.mixin.PendingElement.prototype.popPending = function () {
575 if ( this.pending === 1 ) {
576 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
578 }
579 this.pending = Math.max( 0, this.pending - 1 );
580
581 return this;
582 };
583
584 /**
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
588 *
589 * ActionSets contain two types of actions:
590 *
591 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
592 * - Other: Other actions include all non-special visible actions.
593 *
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
595 *
596 * @example
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
600 * }
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
609 * ];
610 *
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
619 * } );
620 * this.$body.append( this.stackLayout.$element );
621 * };
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
626 * }, this );
627 * };
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
636 * var dialog = this;
637 * return new OO.ui.Process( function () {
638 * dialog.close();
639 * } );
640 * }
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
642 * };
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
645 * };
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
649 * size: 'medium'
650 * } );
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
653 *
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
655 *
656 * @abstract
657 * @class
658 * @mixins OO.EventEmitter
659 *
660 * @constructor
661 * @param {Object} [config] Configuration options
662 */
663 OO.ui.ActionSet = function OoUiActionSet( config ) {
664 // Configuration initialization
665 config = config || {};
666
667 // Mixin constructors
668 OO.EventEmitter.call( this );
669
670 // Properties
671 this.list = [];
672 this.categories = {
673 actions: 'getAction',
674 flags: 'getFlags',
675 modes: 'getModes'
676 };
677 this.categorized = {};
678 this.special = {};
679 this.others = [];
680 this.organized = false;
681 this.changing = false;
682 this.changed = false;
683 };
684
685 /* Setup */
686
687 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
688
689 /* Static Properties */
690
691 /**
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
695 *
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
697 *
698 * @abstract
699 * @static
700 * @inheritable
701 * @property {string}
702 */
703 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
704
705 /* Events */
706
707 /**
708 * @event click
709 *
710 * A 'click' event is emitted when an action is clicked.
711 *
712 * @param {OO.ui.ActionWidget} action Action that was clicked
713 */
714
715 /**
716 * @event resize
717 *
718 * A 'resize' event is emitted when an action widget is resized.
719 *
720 * @param {OO.ui.ActionWidget} action Action that was resized
721 */
722
723 /**
724 * @event add
725 *
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
727 *
728 * @param {OO.ui.ActionWidget[]} added Actions added
729 */
730
731 /**
732 * @event remove
733 *
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
736 *
737 * @param {OO.ui.ActionWidget[]} added Actions removed
738 */
739
740 /**
741 * @event change
742 *
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
745 *
746 */
747
748 /* Methods */
749
750 /**
751 * Handle action change events.
752 *
753 * @private
754 * @fires change
755 */
756 OO.ui.ActionSet.prototype.onActionChange = function () {
757 this.organized = false;
758 if ( this.changing ) {
759 this.changed = true;
760 } else {
761 this.emit( 'change' );
762 }
763 };
764
765 /**
766 * Check if an action is one of the special actions.
767 *
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
770 */
771 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
772 var flag;
773
774 for ( flag in this.special ) {
775 if ( action === this.special[ flag ] ) {
776 return true;
777 }
778 }
779
780 return false;
781 };
782
783 /**
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
785 * or ‘disabled’.
786 *
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
794 */
795 OO.ui.ActionSet.prototype.get = function ( filters ) {
796 var i, len, list, category, actions, index, match, matches;
797
798 if ( filters ) {
799 this.organize();
800
801 // Collect category candidates
802 matches = [];
803 for ( category in this.categorized ) {
804 list = filters[ category ];
805 if ( list ) {
806 if ( !Array.isArray( list ) ) {
807 list = [ list ];
808 }
809 for ( i = 0, len = list.length; i < len; i++ ) {
810 actions = this.categorized[ category ][ list[ i ] ];
811 if ( Array.isArray( actions ) ) {
812 matches.push.apply( matches, actions );
813 }
814 }
815 }
816 }
817 // Remove by boolean filters
818 for ( i = 0, len = matches.length; i < len; i++ ) {
819 match = matches[ i ];
820 if (
821 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
822 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
823 ) {
824 matches.splice( i, 1 );
825 len--;
826 i--;
827 }
828 }
829 // Remove duplicates
830 for ( i = 0, len = matches.length; i < len; i++ ) {
831 match = matches[ i ];
832 index = matches.lastIndexOf( match );
833 while ( index !== i ) {
834 matches.splice( index, 1 );
835 len--;
836 index = matches.lastIndexOf( match );
837 }
838 }
839 return matches;
840 }
841 return this.list.slice();
842 };
843
844 /**
845 * Get 'special' actions.
846 *
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
849 *
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
851 */
852 OO.ui.ActionSet.prototype.getSpecial = function () {
853 this.organize();
854 return $.extend( {}, this.special );
855 };
856
857 /**
858 * Get 'other' actions.
859 *
860 * Other actions include all non-special visible action widgets.
861 *
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
863 */
864 OO.ui.ActionSet.prototype.getOthers = function () {
865 this.organize();
866 return this.others.slice();
867 };
868
869 /**
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
872 *
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
875 * @chainable
876 * @fires toggle
877 * @fires change
878 */
879 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
880 var i, len, action;
881
882 this.changing = true;
883 for ( i = 0, len = this.list.length; i < len; i++ ) {
884 action = this.list[ i ];
885 action.toggle( action.hasMode( mode ) );
886 }
887
888 this.organized = false;
889 this.changing = false;
890 this.emit( 'change' );
891
892 return this;
893 };
894
895 /**
896 * Set the abilities of the specified actions.
897 *
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
900 * parameter.
901 *
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
904 * @chainable
905 */
906 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
907 var i, len, action, item;
908
909 for ( i = 0, len = this.list.length; i < len; i++ ) {
910 item = this.list[ i ];
911 action = item.getAction();
912 if ( actions[ action ] !== undefined ) {
913 item.setDisabled( !actions[ action ] );
914 }
915 }
916
917 return this;
918 };
919
920 /**
921 * Executes a function once per action.
922 *
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
925 *
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
929 * @chainable
930 */
931 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
932 this.changed = false;
933 this.changing = true;
934 this.get( filter ).forEach( callback );
935 this.changing = false;
936 if ( this.changed ) {
937 this.emit( 'change' );
938 }
939
940 return this;
941 };
942
943 /**
944 * Add action widgets to the action set.
945 *
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
947 * @chainable
948 * @fires add
949 * @fires change
950 */
951 OO.ui.ActionSet.prototype.add = function ( actions ) {
952 var i, len, action;
953
954 this.changing = true;
955 for ( i = 0, len = actions.length; i < len; i++ ) {
956 action = actions[ i ];
957 action.connect( this, {
958 click: [ 'emit', 'click', action ],
959 resize: [ 'emit', 'resize', action ],
960 toggle: [ 'onActionChange' ]
961 } );
962 this.list.push( action );
963 }
964 this.organized = false;
965 this.emit( 'add', actions );
966 this.changing = false;
967 this.emit( 'change' );
968
969 return this;
970 };
971
972 /**
973 * Remove action widgets from the set.
974 *
975 * To remove all actions, you may wish to use the #clear method instead.
976 *
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
978 * @chainable
979 * @fires remove
980 * @fires change
981 */
982 OO.ui.ActionSet.prototype.remove = function ( actions ) {
983 var i, len, index, action;
984
985 this.changing = true;
986 for ( i = 0, len = actions.length; i < len; i++ ) {
987 action = actions[ i ];
988 index = this.list.indexOf( action );
989 if ( index !== -1 ) {
990 action.disconnect( this );
991 this.list.splice( index, 1 );
992 }
993 }
994 this.organized = false;
995 this.emit( 'remove', actions );
996 this.changing = false;
997 this.emit( 'change' );
998
999 return this;
1000 };
1001
1002 /**
1003 * Remove all action widets from the set.
1004 *
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1006 *
1007 * @chainable
1008 * @fires remove
1009 * @fires change
1010 */
1011 OO.ui.ActionSet.prototype.clear = function () {
1012 var i, len, action,
1013 removed = this.list.slice();
1014
1015 this.changing = true;
1016 for ( i = 0, len = this.list.length; i < len; i++ ) {
1017 action = this.list[ i ];
1018 action.disconnect( this );
1019 }
1020
1021 this.list = [];
1022
1023 this.organized = false;
1024 this.emit( 'remove', removed );
1025 this.changing = false;
1026 this.emit( 'change' );
1027
1028 return this;
1029 };
1030
1031 /**
1032 * Organize actions.
1033 *
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1036 *
1037 * @private
1038 * @chainable
1039 */
1040 OO.ui.ActionSet.prototype.organize = function () {
1041 var i, iLen, j, jLen, flag, action, category, list, item, special,
1042 specialFlags = this.constructor.static.specialFlags;
1043
1044 if ( !this.organized ) {
1045 this.categorized = {};
1046 this.special = {};
1047 this.others = [];
1048 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1049 action = this.list[ i ];
1050 if ( action.isVisible() ) {
1051 // Populate categories
1052 for ( category in this.categories ) {
1053 if ( !this.categorized[ category ] ) {
1054 this.categorized[ category ] = {};
1055 }
1056 list = action[ this.categories[ category ] ]();
1057 if ( !Array.isArray( list ) ) {
1058 list = [ list ];
1059 }
1060 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1061 item = list[ j ];
1062 if ( !this.categorized[ category ][ item ] ) {
1063 this.categorized[ category ][ item ] = [];
1064 }
1065 this.categorized[ category ][ item ].push( action );
1066 }
1067 }
1068 // Populate special/others
1069 special = false;
1070 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1071 flag = specialFlags[ j ];
1072 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1073 this.special[ flag ] = action;
1074 special = true;
1075 break;
1076 }
1077 }
1078 if ( !special ) {
1079 this.others.push( action );
1080 }
1081 }
1082 }
1083 this.organized = true;
1084 }
1085
1086 return this;
1087 };
1088
1089 /**
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1093 *
1094 * @abstract
1095 * @class
1096 *
1097 * @constructor
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1101 * for an example.
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text)
1109 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1110 * Data can also be specified with the #setData method.
1111 */
1112 OO.ui.Element = function OoUiElement( config ) {
1113 // Configuration initialization
1114 config = config || {};
1115
1116 // Properties
1117 this.$ = $;
1118 this.visible = true;
1119 this.data = config.data;
1120 this.$element = config.$element ||
1121 $( document.createElement( this.getTagName() ) );
1122 this.elementGroup = null;
1123 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1124
1125 // Initialization
1126 if ( Array.isArray( config.classes ) ) {
1127 this.$element.addClass( config.classes.join( ' ' ) );
1128 }
1129 if ( config.id ) {
1130 this.$element.attr( 'id', config.id );
1131 }
1132 if ( config.text ) {
1133 this.$element.text( config.text );
1134 }
1135 if ( config.content ) {
1136 // The `content` property treats plain strings as text; use an
1137 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1138 // appropriate $element appended.
1139 this.$element.append( config.content.map( function ( v ) {
1140 if ( typeof v === 'string' ) {
1141 // Escape string so it is properly represented in HTML.
1142 return document.createTextNode( v );
1143 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1144 // Bypass escaping.
1145 return v.toString();
1146 } else if ( v instanceof OO.ui.Element ) {
1147 return v.$element;
1148 }
1149 return v;
1150 } ) );
1151 }
1152 if ( config.$content ) {
1153 // The `$content` property treats plain strings as HTML.
1154 this.$element.append( config.$content );
1155 }
1156 };
1157
1158 /* Setup */
1159
1160 OO.initClass( OO.ui.Element );
1161
1162 /* Static Properties */
1163
1164 /**
1165 * The name of the HTML tag used by the element.
1166 *
1167 * The static value may be ignored if the #getTagName method is overridden.
1168 *
1169 * @static
1170 * @inheritable
1171 * @property {string}
1172 */
1173 OO.ui.Element.static.tagName = 'div';
1174
1175 /* Static Methods */
1176
1177 /**
1178 * Reconstitute a JavaScript object corresponding to a widget created
1179 * by the PHP implementation.
1180 *
1181 * @param {string|HTMLElement|jQuery} idOrNode
1182 * A DOM id (if a string) or node for the widget to infuse.
1183 * @return {OO.ui.Element}
1184 * The `OO.ui.Element` corresponding to this (infusable) document node.
1185 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1186 * the value returned is a newly-created Element wrapping around the existing
1187 * DOM node.
1188 */
1189 OO.ui.Element.static.infuse = function ( idOrNode ) {
1190 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1191 // Verify that the type matches up.
1192 // FIXME: uncomment after T89721 is fixed (see T90929)
1193 /*
1194 if ( !( obj instanceof this['class'] ) ) {
1195 throw new Error( 'Infusion type mismatch!' );
1196 }
1197 */
1198 return obj;
1199 };
1200
1201 /**
1202 * Implementation helper for `infuse`; skips the type check and has an
1203 * extra property so that only the top-level invocation touches the DOM.
1204 * @private
1205 * @param {string|HTMLElement|jQuery} idOrNode
1206 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1207 * when the top-level widget of this infusion is inserted into DOM,
1208 * replacing the original node; or false for top-level invocation.
1209 * @return {OO.ui.Element}
1210 */
1211 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1212 // look for a cached result of a previous infusion.
1213 var id, $elem, data, cls, parts, parent, obj, top, state;
1214 if ( typeof idOrNode === 'string' ) {
1215 id = idOrNode;
1216 $elem = $( document.getElementById( id ) );
1217 } else {
1218 $elem = $( idOrNode );
1219 id = $elem.attr( 'id' );
1220 }
1221 if ( !$elem.length ) {
1222 throw new Error( 'Widget not found: ' + id );
1223 }
1224 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1225 if ( data ) {
1226 // cached!
1227 if ( data === true ) {
1228 throw new Error( 'Circular dependency! ' + id );
1229 }
1230 return data;
1231 }
1232 data = $elem.attr( 'data-ooui' );
1233 if ( !data ) {
1234 throw new Error( 'No infusion data found: ' + id );
1235 }
1236 try {
1237 data = $.parseJSON( data );
1238 } catch ( _ ) {
1239 data = null;
1240 }
1241 if ( !( data && data._ ) ) {
1242 throw new Error( 'No valid infusion data found: ' + id );
1243 }
1244 if ( data._ === 'Tag' ) {
1245 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1246 return new OO.ui.Element( { $element: $elem } );
1247 }
1248 parts = data._.split( '.' );
1249 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1250 if ( cls === undefined ) {
1251 // The PHP output might be old and not including the "OO.ui" prefix
1252 // TODO: Remove this back-compat after next major release
1253 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1254 if ( cls === undefined ) {
1255 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1256 }
1257 }
1258
1259 // Verify that we're creating an OO.ui.Element instance
1260 parent = cls.parent;
1261
1262 while ( parent !== undefined ) {
1263 if ( parent === OO.ui.Element ) {
1264 // Safe
1265 break;
1266 }
1267
1268 parent = parent.parent;
1269 }
1270
1271 if ( parent !== OO.ui.Element ) {
1272 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1273 }
1274
1275 if ( domPromise === false ) {
1276 top = $.Deferred();
1277 domPromise = top.promise();
1278 }
1279 $elem.data( 'ooui-infused', true ); // prevent loops
1280 data.id = id; // implicit
1281 data = OO.copy( data, null, function deserialize( value ) {
1282 if ( OO.isPlainObject( value ) ) {
1283 if ( value.tag ) {
1284 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1285 }
1286 if ( value.html ) {
1287 return new OO.ui.HtmlSnippet( value.html );
1288 }
1289 }
1290 } );
1291 // jscs:disable requireCapitalizedConstructors
1292 obj = new cls( data ); // rebuild widget
1293 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1294 state = obj.gatherPreInfuseState( $elem );
1295 // now replace old DOM with this new DOM.
1296 if ( top ) {
1297 $elem.replaceWith( obj.$element );
1298 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1299 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1300 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1301 $elem[ 0 ].oouiInfused = obj;
1302 top.resolve();
1303 }
1304 obj.$element.data( 'ooui-infused', obj );
1305 // set the 'data-ooui' attribute so we can identify infused widgets
1306 obj.$element.attr( 'data-ooui', '' );
1307 // restore dynamic state after the new element is inserted into DOM
1308 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1309 return obj;
1310 };
1311
1312 /**
1313 * Get a jQuery function within a specific document.
1314 *
1315 * @static
1316 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1317 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1318 * not in an iframe
1319 * @return {Function} Bound jQuery function
1320 */
1321 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1322 function wrapper( selector ) {
1323 return $( selector, wrapper.context );
1324 }
1325
1326 wrapper.context = this.getDocument( context );
1327
1328 if ( $iframe ) {
1329 wrapper.$iframe = $iframe;
1330 }
1331
1332 return wrapper;
1333 };
1334
1335 /**
1336 * Get the document of an element.
1337 *
1338 * @static
1339 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1340 * @return {HTMLDocument|null} Document object
1341 */
1342 OO.ui.Element.static.getDocument = function ( obj ) {
1343 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1344 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1345 // Empty jQuery selections might have a context
1346 obj.context ||
1347 // HTMLElement
1348 obj.ownerDocument ||
1349 // Window
1350 obj.document ||
1351 // HTMLDocument
1352 ( obj.nodeType === 9 && obj ) ||
1353 null;
1354 };
1355
1356 /**
1357 * Get the window of an element or document.
1358 *
1359 * @static
1360 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1361 * @return {Window} Window object
1362 */
1363 OO.ui.Element.static.getWindow = function ( obj ) {
1364 var doc = this.getDocument( obj );
1365 // Support: IE 8
1366 // Standard Document.defaultView is IE9+
1367 return doc.parentWindow || doc.defaultView;
1368 };
1369
1370 /**
1371 * Get the direction of an element or document.
1372 *
1373 * @static
1374 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1375 * @return {string} Text direction, either 'ltr' or 'rtl'
1376 */
1377 OO.ui.Element.static.getDir = function ( obj ) {
1378 var isDoc, isWin;
1379
1380 if ( obj instanceof jQuery ) {
1381 obj = obj[ 0 ];
1382 }
1383 isDoc = obj.nodeType === 9;
1384 isWin = obj.document !== undefined;
1385 if ( isDoc || isWin ) {
1386 if ( isWin ) {
1387 obj = obj.document;
1388 }
1389 obj = obj.body;
1390 }
1391 return $( obj ).css( 'direction' );
1392 };
1393
1394 /**
1395 * Get the offset between two frames.
1396 *
1397 * TODO: Make this function not use recursion.
1398 *
1399 * @static
1400 * @param {Window} from Window of the child frame
1401 * @param {Window} [to=window] Window of the parent frame
1402 * @param {Object} [offset] Offset to start with, used internally
1403 * @return {Object} Offset object, containing left and top properties
1404 */
1405 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1406 var i, len, frames, frame, rect;
1407
1408 if ( !to ) {
1409 to = window;
1410 }
1411 if ( !offset ) {
1412 offset = { top: 0, left: 0 };
1413 }
1414 if ( from.parent === from ) {
1415 return offset;
1416 }
1417
1418 // Get iframe element
1419 frames = from.parent.document.getElementsByTagName( 'iframe' );
1420 for ( i = 0, len = frames.length; i < len; i++ ) {
1421 if ( frames[ i ].contentWindow === from ) {
1422 frame = frames[ i ];
1423 break;
1424 }
1425 }
1426
1427 // Recursively accumulate offset values
1428 if ( frame ) {
1429 rect = frame.getBoundingClientRect();
1430 offset.left += rect.left;
1431 offset.top += rect.top;
1432 if ( from !== to ) {
1433 this.getFrameOffset( from.parent, offset );
1434 }
1435 }
1436 return offset;
1437 };
1438
1439 /**
1440 * Get the offset between two elements.
1441 *
1442 * The two elements may be in a different frame, but in that case the frame $element is in must
1443 * be contained in the frame $anchor is in.
1444 *
1445 * @static
1446 * @param {jQuery} $element Element whose position to get
1447 * @param {jQuery} $anchor Element to get $element's position relative to
1448 * @return {Object} Translated position coordinates, containing top and left properties
1449 */
1450 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1451 var iframe, iframePos,
1452 pos = $element.offset(),
1453 anchorPos = $anchor.offset(),
1454 elementDocument = this.getDocument( $element ),
1455 anchorDocument = this.getDocument( $anchor );
1456
1457 // If $element isn't in the same document as $anchor, traverse up
1458 while ( elementDocument !== anchorDocument ) {
1459 iframe = elementDocument.defaultView.frameElement;
1460 if ( !iframe ) {
1461 throw new Error( '$element frame is not contained in $anchor frame' );
1462 }
1463 iframePos = $( iframe ).offset();
1464 pos.left += iframePos.left;
1465 pos.top += iframePos.top;
1466 elementDocument = iframe.ownerDocument;
1467 }
1468 pos.left -= anchorPos.left;
1469 pos.top -= anchorPos.top;
1470 return pos;
1471 };
1472
1473 /**
1474 * Get element border sizes.
1475 *
1476 * @static
1477 * @param {HTMLElement} el Element to measure
1478 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1479 */
1480 OO.ui.Element.static.getBorders = function ( el ) {
1481 var doc = el.ownerDocument,
1482 // Support: IE 8
1483 // Standard Document.defaultView is IE9+
1484 win = doc.parentWindow || doc.defaultView,
1485 style = win && win.getComputedStyle ?
1486 win.getComputedStyle( el, null ) :
1487 // Support: IE 8
1488 // Standard getComputedStyle() is IE9+
1489 el.currentStyle,
1490 $el = $( el ),
1491 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1492 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1493 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1494 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1495
1496 return {
1497 top: top,
1498 left: left,
1499 bottom: bottom,
1500 right: right
1501 };
1502 };
1503
1504 /**
1505 * Get dimensions of an element or window.
1506 *
1507 * @static
1508 * @param {HTMLElement|Window} el Element to measure
1509 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1510 */
1511 OO.ui.Element.static.getDimensions = function ( el ) {
1512 var $el, $win,
1513 doc = el.ownerDocument || el.document,
1514 // Support: IE 8
1515 // Standard Document.defaultView is IE9+
1516 win = doc.parentWindow || doc.defaultView;
1517
1518 if ( win === el || el === doc.documentElement ) {
1519 $win = $( win );
1520 return {
1521 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1522 scroll: {
1523 top: $win.scrollTop(),
1524 left: $win.scrollLeft()
1525 },
1526 scrollbar: { right: 0, bottom: 0 },
1527 rect: {
1528 top: 0,
1529 left: 0,
1530 bottom: $win.innerHeight(),
1531 right: $win.innerWidth()
1532 }
1533 };
1534 } else {
1535 $el = $( el );
1536 return {
1537 borders: this.getBorders( el ),
1538 scroll: {
1539 top: $el.scrollTop(),
1540 left: $el.scrollLeft()
1541 },
1542 scrollbar: {
1543 right: $el.innerWidth() - el.clientWidth,
1544 bottom: $el.innerHeight() - el.clientHeight
1545 },
1546 rect: el.getBoundingClientRect()
1547 };
1548 }
1549 };
1550
1551 /**
1552 * Get scrollable object parent
1553 *
1554 * documentElement can't be used to get or set the scrollTop
1555 * property on Blink. Changing and testing its value lets us
1556 * use 'body' or 'documentElement' based on what is working.
1557 *
1558 * https://code.google.com/p/chromium/issues/detail?id=303131
1559 *
1560 * @static
1561 * @param {HTMLElement} el Element to find scrollable parent for
1562 * @return {HTMLElement} Scrollable parent
1563 */
1564 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1565 var scrollTop, body;
1566
1567 if ( OO.ui.scrollableElement === undefined ) {
1568 body = el.ownerDocument.body;
1569 scrollTop = body.scrollTop;
1570 body.scrollTop = 1;
1571
1572 if ( body.scrollTop === 1 ) {
1573 body.scrollTop = scrollTop;
1574 OO.ui.scrollableElement = 'body';
1575 } else {
1576 OO.ui.scrollableElement = 'documentElement';
1577 }
1578 }
1579
1580 return el.ownerDocument[ OO.ui.scrollableElement ];
1581 };
1582
1583 /**
1584 * Get closest scrollable container.
1585 *
1586 * Traverses up until either a scrollable element or the root is reached, in which case the window
1587 * will be returned.
1588 *
1589 * @static
1590 * @param {HTMLElement} el Element to find scrollable container for
1591 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1592 * @return {HTMLElement} Closest scrollable container
1593 */
1594 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1595 var i, val,
1596 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1597 props = [ 'overflow-x', 'overflow-y' ],
1598 $parent = $( el ).parent();
1599
1600 if ( dimension === 'x' || dimension === 'y' ) {
1601 props = [ 'overflow-' + dimension ];
1602 }
1603
1604 while ( $parent.length ) {
1605 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1606 return $parent[ 0 ];
1607 }
1608 i = props.length;
1609 while ( i-- ) {
1610 val = $parent.css( props[ i ] );
1611 if ( val === 'auto' || val === 'scroll' ) {
1612 return $parent[ 0 ];
1613 }
1614 }
1615 $parent = $parent.parent();
1616 }
1617 return this.getDocument( el ).body;
1618 };
1619
1620 /**
1621 * Scroll element into view.
1622 *
1623 * @static
1624 * @param {HTMLElement} el Element to scroll into view
1625 * @param {Object} [config] Configuration options
1626 * @param {string} [config.duration] jQuery animation duration value
1627 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1628 * to scroll in both directions
1629 * @param {Function} [config.complete] Function to call when scrolling completes
1630 */
1631 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1632 var rel, anim, callback, sc, $sc, eld, scd, $win;
1633
1634 // Configuration initialization
1635 config = config || {};
1636
1637 anim = {};
1638 callback = typeof config.complete === 'function' && config.complete;
1639 sc = this.getClosestScrollableContainer( el, config.direction );
1640 $sc = $( sc );
1641 eld = this.getDimensions( el );
1642 scd = this.getDimensions( sc );
1643 $win = $( this.getWindow( el ) );
1644
1645 // Compute the distances between the edges of el and the edges of the scroll viewport
1646 if ( $sc.is( 'html, body' ) ) {
1647 // If the scrollable container is the root, this is easy
1648 rel = {
1649 top: eld.rect.top,
1650 bottom: $win.innerHeight() - eld.rect.bottom,
1651 left: eld.rect.left,
1652 right: $win.innerWidth() - eld.rect.right
1653 };
1654 } else {
1655 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1656 rel = {
1657 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1658 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1659 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1660 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1661 };
1662 }
1663
1664 if ( !config.direction || config.direction === 'y' ) {
1665 if ( rel.top < 0 ) {
1666 anim.scrollTop = scd.scroll.top + rel.top;
1667 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1668 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1669 }
1670 }
1671 if ( !config.direction || config.direction === 'x' ) {
1672 if ( rel.left < 0 ) {
1673 anim.scrollLeft = scd.scroll.left + rel.left;
1674 } else if ( rel.left > 0 && rel.right < 0 ) {
1675 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1676 }
1677 }
1678 if ( !$.isEmptyObject( anim ) ) {
1679 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1680 if ( callback ) {
1681 $sc.queue( function ( next ) {
1682 callback();
1683 next();
1684 } );
1685 }
1686 } else {
1687 if ( callback ) {
1688 callback();
1689 }
1690 }
1691 };
1692
1693 /**
1694 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1695 * and reserve space for them, because it probably doesn't.
1696 *
1697 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1698 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1699 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1700 * and then reattach (or show) them back.
1701 *
1702 * @static
1703 * @param {HTMLElement} el Element to reconsider the scrollbars on
1704 */
1705 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1706 var i, len, scrollLeft, scrollTop, nodes = [];
1707 // Save scroll position
1708 scrollLeft = el.scrollLeft;
1709 scrollTop = el.scrollTop;
1710 // Detach all children
1711 while ( el.firstChild ) {
1712 nodes.push( el.firstChild );
1713 el.removeChild( el.firstChild );
1714 }
1715 // Force reflow
1716 void el.offsetHeight;
1717 // Reattach all children
1718 for ( i = 0, len = nodes.length; i < len; i++ ) {
1719 el.appendChild( nodes[ i ] );
1720 }
1721 // Restore scroll position (no-op if scrollbars disappeared)
1722 el.scrollLeft = scrollLeft;
1723 el.scrollTop = scrollTop;
1724 };
1725
1726 /* Methods */
1727
1728 /**
1729 * Toggle visibility of an element.
1730 *
1731 * @param {boolean} [show] Make element visible, omit to toggle visibility
1732 * @fires visible
1733 * @chainable
1734 */
1735 OO.ui.Element.prototype.toggle = function ( show ) {
1736 show = show === undefined ? !this.visible : !!show;
1737
1738 if ( show !== this.isVisible() ) {
1739 this.visible = show;
1740 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1741 this.emit( 'toggle', show );
1742 }
1743
1744 return this;
1745 };
1746
1747 /**
1748 * Check if element is visible.
1749 *
1750 * @return {boolean} element is visible
1751 */
1752 OO.ui.Element.prototype.isVisible = function () {
1753 return this.visible;
1754 };
1755
1756 /**
1757 * Get element data.
1758 *
1759 * @return {Mixed} Element data
1760 */
1761 OO.ui.Element.prototype.getData = function () {
1762 return this.data;
1763 };
1764
1765 /**
1766 * Set element data.
1767 *
1768 * @param {Mixed} Element data
1769 * @chainable
1770 */
1771 OO.ui.Element.prototype.setData = function ( data ) {
1772 this.data = data;
1773 return this;
1774 };
1775
1776 /**
1777 * Check if element supports one or more methods.
1778 *
1779 * @param {string|string[]} methods Method or list of methods to check
1780 * @return {boolean} All methods are supported
1781 */
1782 OO.ui.Element.prototype.supports = function ( methods ) {
1783 var i, len,
1784 support = 0;
1785
1786 methods = Array.isArray( methods ) ? methods : [ methods ];
1787 for ( i = 0, len = methods.length; i < len; i++ ) {
1788 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1789 support++;
1790 }
1791 }
1792
1793 return methods.length === support;
1794 };
1795
1796 /**
1797 * Update the theme-provided classes.
1798 *
1799 * @localdoc This is called in element mixins and widget classes any time state changes.
1800 * Updating is debounced, minimizing overhead of changing multiple attributes and
1801 * guaranteeing that theme updates do not occur within an element's constructor
1802 */
1803 OO.ui.Element.prototype.updateThemeClasses = function () {
1804 this.debouncedUpdateThemeClassesHandler();
1805 };
1806
1807 /**
1808 * @private
1809 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1810 * make them synchronous.
1811 */
1812 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1813 OO.ui.theme.updateElementClasses( this );
1814 };
1815
1816 /**
1817 * Get the HTML tag name.
1818 *
1819 * Override this method to base the result on instance information.
1820 *
1821 * @return {string} HTML tag name
1822 */
1823 OO.ui.Element.prototype.getTagName = function () {
1824 return this.constructor.static.tagName;
1825 };
1826
1827 /**
1828 * Check if the element is attached to the DOM
1829 * @return {boolean} The element is attached to the DOM
1830 */
1831 OO.ui.Element.prototype.isElementAttached = function () {
1832 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1833 };
1834
1835 /**
1836 * Get the DOM document.
1837 *
1838 * @return {HTMLDocument} Document object
1839 */
1840 OO.ui.Element.prototype.getElementDocument = function () {
1841 // Don't cache this in other ways either because subclasses could can change this.$element
1842 return OO.ui.Element.static.getDocument( this.$element );
1843 };
1844
1845 /**
1846 * Get the DOM window.
1847 *
1848 * @return {Window} Window object
1849 */
1850 OO.ui.Element.prototype.getElementWindow = function () {
1851 return OO.ui.Element.static.getWindow( this.$element );
1852 };
1853
1854 /**
1855 * Get closest scrollable container.
1856 */
1857 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1858 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1859 };
1860
1861 /**
1862 * Get group element is in.
1863 *
1864 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1865 */
1866 OO.ui.Element.prototype.getElementGroup = function () {
1867 return this.elementGroup;
1868 };
1869
1870 /**
1871 * Set group element is in.
1872 *
1873 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1874 * @chainable
1875 */
1876 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1877 this.elementGroup = group;
1878 return this;
1879 };
1880
1881 /**
1882 * Scroll element into view.
1883 *
1884 * @param {Object} [config] Configuration options
1885 */
1886 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1887 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1888 };
1889
1890 /**
1891 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1892 * (and its children) that represent an Element of the same type and configuration as the current
1893 * one, generated by the PHP implementation.
1894 *
1895 * This method is called just before `node` is detached from the DOM. The return value of this
1896 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1897 * DOM to replace `node`.
1898 *
1899 * @protected
1900 * @param {HTMLElement} node
1901 * @return {Object}
1902 */
1903 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1904 return {};
1905 };
1906
1907 /**
1908 * Restore the pre-infusion dynamic state for this widget.
1909 *
1910 * This method is called after #$element has been inserted into DOM. The parameter is the return
1911 * value of #gatherPreInfuseState.
1912 *
1913 * @protected
1914 * @param {Object} state
1915 */
1916 OO.ui.Element.prototype.restorePreInfuseState = function () {
1917 };
1918
1919 /**
1920 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1921 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1922 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1923 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1924 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1925 *
1926 * @abstract
1927 * @class
1928 * @extends OO.ui.Element
1929 * @mixins OO.EventEmitter
1930 *
1931 * @constructor
1932 * @param {Object} [config] Configuration options
1933 */
1934 OO.ui.Layout = function OoUiLayout( config ) {
1935 // Configuration initialization
1936 config = config || {};
1937
1938 // Parent constructor
1939 OO.ui.Layout.parent.call( this, config );
1940
1941 // Mixin constructors
1942 OO.EventEmitter.call( this );
1943
1944 // Initialization
1945 this.$element.addClass( 'oo-ui-layout' );
1946 };
1947
1948 /* Setup */
1949
1950 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1951 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1952
1953 /**
1954 * Widgets are compositions of one or more OOjs UI elements that users can both view
1955 * and interact with. All widgets can be configured and modified via a standard API,
1956 * and their state can change dynamically according to a model.
1957 *
1958 * @abstract
1959 * @class
1960 * @extends OO.ui.Element
1961 * @mixins OO.EventEmitter
1962 *
1963 * @constructor
1964 * @param {Object} [config] Configuration options
1965 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1966 * appearance reflects this state.
1967 */
1968 OO.ui.Widget = function OoUiWidget( config ) {
1969 // Initialize config
1970 config = $.extend( { disabled: false }, config );
1971
1972 // Parent constructor
1973 OO.ui.Widget.parent.call( this, config );
1974
1975 // Mixin constructors
1976 OO.EventEmitter.call( this );
1977
1978 // Properties
1979 this.disabled = null;
1980 this.wasDisabled = null;
1981
1982 // Initialization
1983 this.$element.addClass( 'oo-ui-widget' );
1984 this.setDisabled( !!config.disabled );
1985 };
1986
1987 /* Setup */
1988
1989 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1990 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1991
1992 /* Static Properties */
1993
1994 /**
1995 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1996 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1997 * handling.
1998 *
1999 * @static
2000 * @inheritable
2001 * @property {boolean}
2002 */
2003 OO.ui.Widget.static.supportsSimpleLabel = false;
2004
2005 /* Events */
2006
2007 /**
2008 * @event disable
2009 *
2010 * A 'disable' event is emitted when the disabled state of the widget changes
2011 * (i.e. on disable **and** enable).
2012 *
2013 * @param {boolean} disabled Widget is disabled
2014 */
2015
2016 /**
2017 * @event toggle
2018 *
2019 * A 'toggle' event is emitted when the visibility of the widget changes.
2020 *
2021 * @param {boolean} visible Widget is visible
2022 */
2023
2024 /* Methods */
2025
2026 /**
2027 * Check if the widget is disabled.
2028 *
2029 * @return {boolean} Widget is disabled
2030 */
2031 OO.ui.Widget.prototype.isDisabled = function () {
2032 return this.disabled;
2033 };
2034
2035 /**
2036 * Set the 'disabled' state of the widget.
2037 *
2038 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2039 *
2040 * @param {boolean} disabled Disable widget
2041 * @chainable
2042 */
2043 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2044 var isDisabled;
2045
2046 this.disabled = !!disabled;
2047 isDisabled = this.isDisabled();
2048 if ( isDisabled !== this.wasDisabled ) {
2049 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2050 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2051 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2052 this.emit( 'disable', isDisabled );
2053 this.updateThemeClasses();
2054 }
2055 this.wasDisabled = isDisabled;
2056
2057 return this;
2058 };
2059
2060 /**
2061 * Update the disabled state, in case of changes in parent widget.
2062 *
2063 * @chainable
2064 */
2065 OO.ui.Widget.prototype.updateDisabled = function () {
2066 this.setDisabled( this.disabled );
2067 return this;
2068 };
2069
2070 /**
2071 * A window is a container for elements that are in a child frame. They are used with
2072 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2073 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2074 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2075 * the window manager will choose a sensible fallback.
2076 *
2077 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2078 * different processes are executed:
2079 *
2080 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2081 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2082 * the window.
2083 *
2084 * - {@link #getSetupProcess} method is called and its result executed
2085 * - {@link #getReadyProcess} method is called and its result executed
2086 *
2087 * **opened**: The window is now open
2088 *
2089 * **closing**: The closing stage begins when the window manager's
2090 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2091 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2092 *
2093 * - {@link #getHoldProcess} method is called and its result executed
2094 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2095 *
2096 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2097 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2098 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2099 * processing can complete. Always assume window processes are executed asynchronously.
2100 *
2101 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2102 *
2103 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2104 *
2105 * @abstract
2106 * @class
2107 * @extends OO.ui.Element
2108 * @mixins OO.EventEmitter
2109 *
2110 * @constructor
2111 * @param {Object} [config] Configuration options
2112 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2113 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2114 */
2115 OO.ui.Window = function OoUiWindow( config ) {
2116 // Configuration initialization
2117 config = config || {};
2118
2119 // Parent constructor
2120 OO.ui.Window.parent.call( this, config );
2121
2122 // Mixin constructors
2123 OO.EventEmitter.call( this );
2124
2125 // Properties
2126 this.manager = null;
2127 this.size = config.size || this.constructor.static.size;
2128 this.$frame = $( '<div>' );
2129 this.$overlay = $( '<div>' );
2130 this.$content = $( '<div>' );
2131
2132 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2133 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2134 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2135
2136 // Initialization
2137 this.$overlay.addClass( 'oo-ui-window-overlay' );
2138 this.$content
2139 .addClass( 'oo-ui-window-content' )
2140 .attr( 'tabindex', 0 );
2141 this.$frame
2142 .addClass( 'oo-ui-window-frame' )
2143 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2144
2145 this.$element
2146 .addClass( 'oo-ui-window' )
2147 .append( this.$frame, this.$overlay );
2148
2149 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2150 // that reference properties not initialized at that time of parent class construction
2151 // TODO: Find a better way to handle post-constructor setup
2152 this.visible = false;
2153 this.$element.addClass( 'oo-ui-element-hidden' );
2154 };
2155
2156 /* Setup */
2157
2158 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2159 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2160
2161 /* Static Properties */
2162
2163 /**
2164 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2165 *
2166 * The static size is used if no #size is configured during construction.
2167 *
2168 * @static
2169 * @inheritable
2170 * @property {string}
2171 */
2172 OO.ui.Window.static.size = 'medium';
2173
2174 /* Methods */
2175
2176 /**
2177 * Handle mouse down events.
2178 *
2179 * @private
2180 * @param {jQuery.Event} e Mouse down event
2181 */
2182 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2183 // Prevent clicking on the click-block from stealing focus
2184 if ( e.target === this.$element[ 0 ] ) {
2185 return false;
2186 }
2187 };
2188
2189 /**
2190 * Check if the window has been initialized.
2191 *
2192 * Initialization occurs when a window is added to a manager.
2193 *
2194 * @return {boolean} Window has been initialized
2195 */
2196 OO.ui.Window.prototype.isInitialized = function () {
2197 return !!this.manager;
2198 };
2199
2200 /**
2201 * Check if the window is visible.
2202 *
2203 * @return {boolean} Window is visible
2204 */
2205 OO.ui.Window.prototype.isVisible = function () {
2206 return this.visible;
2207 };
2208
2209 /**
2210 * Check if the window is opening.
2211 *
2212 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2213 * method.
2214 *
2215 * @return {boolean} Window is opening
2216 */
2217 OO.ui.Window.prototype.isOpening = function () {
2218 return this.manager.isOpening( this );
2219 };
2220
2221 /**
2222 * Check if the window is closing.
2223 *
2224 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2225 *
2226 * @return {boolean} Window is closing
2227 */
2228 OO.ui.Window.prototype.isClosing = function () {
2229 return this.manager.isClosing( this );
2230 };
2231
2232 /**
2233 * Check if the window is opened.
2234 *
2235 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2236 *
2237 * @return {boolean} Window is opened
2238 */
2239 OO.ui.Window.prototype.isOpened = function () {
2240 return this.manager.isOpened( this );
2241 };
2242
2243 /**
2244 * Get the window manager.
2245 *
2246 * All windows must be attached to a window manager, which is used to open
2247 * and close the window and control its presentation.
2248 *
2249 * @return {OO.ui.WindowManager} Manager of window
2250 */
2251 OO.ui.Window.prototype.getManager = function () {
2252 return this.manager;
2253 };
2254
2255 /**
2256 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2257 *
2258 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2259 */
2260 OO.ui.Window.prototype.getSize = function () {
2261 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2262 sizes = this.manager.constructor.static.sizes,
2263 size = this.size;
2264
2265 if ( !sizes[ size ] ) {
2266 size = this.manager.constructor.static.defaultSize;
2267 }
2268 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2269 size = 'full';
2270 }
2271
2272 return size;
2273 };
2274
2275 /**
2276 * Get the size properties associated with the current window size
2277 *
2278 * @return {Object} Size properties
2279 */
2280 OO.ui.Window.prototype.getSizeProperties = function () {
2281 return this.manager.constructor.static.sizes[ this.getSize() ];
2282 };
2283
2284 /**
2285 * Disable transitions on window's frame for the duration of the callback function, then enable them
2286 * back.
2287 *
2288 * @private
2289 * @param {Function} callback Function to call while transitions are disabled
2290 */
2291 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2292 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2293 // Disable transitions first, otherwise we'll get values from when the window was animating.
2294 var oldTransition,
2295 styleObj = this.$frame[ 0 ].style;
2296 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2297 styleObj.MozTransition || styleObj.WebkitTransition;
2298 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2299 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2300 callback();
2301 // Force reflow to make sure the style changes done inside callback really are not transitioned
2302 this.$frame.height();
2303 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2304 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2305 };
2306
2307 /**
2308 * Get the height of the full window contents (i.e., the window head, body and foot together).
2309 *
2310 * What consistitutes the head, body, and foot varies depending on the window type.
2311 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2312 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2313 * and special actions in the head, and dialog content in the body.
2314 *
2315 * To get just the height of the dialog body, use the #getBodyHeight method.
2316 *
2317 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2318 */
2319 OO.ui.Window.prototype.getContentHeight = function () {
2320 var bodyHeight,
2321 win = this,
2322 bodyStyleObj = this.$body[ 0 ].style,
2323 frameStyleObj = this.$frame[ 0 ].style;
2324
2325 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2326 // Disable transitions first, otherwise we'll get values from when the window was animating.
2327 this.withoutSizeTransitions( function () {
2328 var oldHeight = frameStyleObj.height,
2329 oldPosition = bodyStyleObj.position;
2330 frameStyleObj.height = '1px';
2331 // Force body to resize to new width
2332 bodyStyleObj.position = 'relative';
2333 bodyHeight = win.getBodyHeight();
2334 frameStyleObj.height = oldHeight;
2335 bodyStyleObj.position = oldPosition;
2336 } );
2337
2338 return (
2339 // Add buffer for border
2340 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2341 // Use combined heights of children
2342 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2343 );
2344 };
2345
2346 /**
2347 * Get the height of the window body.
2348 *
2349 * To get the height of the full window contents (the window body, head, and foot together),
2350 * use #getContentHeight.
2351 *
2352 * When this function is called, the window will temporarily have been resized
2353 * to height=1px, so .scrollHeight measurements can be taken accurately.
2354 *
2355 * @return {number} Height of the window body in pixels
2356 */
2357 OO.ui.Window.prototype.getBodyHeight = function () {
2358 return this.$body[ 0 ].scrollHeight;
2359 };
2360
2361 /**
2362 * Get the directionality of the frame (right-to-left or left-to-right).
2363 *
2364 * @return {string} Directionality: `'ltr'` or `'rtl'`
2365 */
2366 OO.ui.Window.prototype.getDir = function () {
2367 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2368 };
2369
2370 /**
2371 * Get the 'setup' process.
2372 *
2373 * The setup process is used to set up a window for use in a particular context,
2374 * based on the `data` argument. This method is called during the opening phase of the window’s
2375 * lifecycle.
2376 *
2377 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2378 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2379 * of OO.ui.Process.
2380 *
2381 * To add window content that persists between openings, you may wish to use the #initialize method
2382 * instead.
2383 *
2384 * @abstract
2385 * @param {Object} [data] Window opening data
2386 * @return {OO.ui.Process} Setup process
2387 */
2388 OO.ui.Window.prototype.getSetupProcess = function () {
2389 return new OO.ui.Process();
2390 };
2391
2392 /**
2393 * Get the ‘ready’ process.
2394 *
2395 * The ready process is used to ready a window for use in a particular
2396 * context, based on the `data` argument. This method is called during the opening phase of
2397 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2398 *
2399 * Override this method to add additional steps to the ‘ready’ process the parent method
2400 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2401 * methods of OO.ui.Process.
2402 *
2403 * @abstract
2404 * @param {Object} [data] Window opening data
2405 * @return {OO.ui.Process} Ready process
2406 */
2407 OO.ui.Window.prototype.getReadyProcess = function () {
2408 return new OO.ui.Process();
2409 };
2410
2411 /**
2412 * Get the 'hold' process.
2413 *
2414 * The hold proccess is used to keep a window from being used in a particular context,
2415 * based on the `data` argument. This method is called during the closing phase of the window’s
2416 * lifecycle.
2417 *
2418 * Override this method to add additional steps to the 'hold' process the parent method provides
2419 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2420 * of OO.ui.Process.
2421 *
2422 * @abstract
2423 * @param {Object} [data] Window closing data
2424 * @return {OO.ui.Process} Hold process
2425 */
2426 OO.ui.Window.prototype.getHoldProcess = function () {
2427 return new OO.ui.Process();
2428 };
2429
2430 /**
2431 * Get the ‘teardown’ process.
2432 *
2433 * The teardown process is used to teardown a window after use. During teardown,
2434 * user interactions within the window are conveyed and the window is closed, based on the `data`
2435 * argument. This method is called during the closing phase of the window’s lifecycle.
2436 *
2437 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2438 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2439 * of OO.ui.Process.
2440 *
2441 * @abstract
2442 * @param {Object} [data] Window closing data
2443 * @return {OO.ui.Process} Teardown process
2444 */
2445 OO.ui.Window.prototype.getTeardownProcess = function () {
2446 return new OO.ui.Process();
2447 };
2448
2449 /**
2450 * Set the window manager.
2451 *
2452 * This will cause the window to initialize. Calling it more than once will cause an error.
2453 *
2454 * @param {OO.ui.WindowManager} manager Manager for this window
2455 * @throws {Error} An error is thrown if the method is called more than once
2456 * @chainable
2457 */
2458 OO.ui.Window.prototype.setManager = function ( manager ) {
2459 if ( this.manager ) {
2460 throw new Error( 'Cannot set window manager, window already has a manager' );
2461 }
2462
2463 this.manager = manager;
2464 this.initialize();
2465
2466 return this;
2467 };
2468
2469 /**
2470 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2471 *
2472 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2473 * `full`
2474 * @chainable
2475 */
2476 OO.ui.Window.prototype.setSize = function ( size ) {
2477 this.size = size;
2478 this.updateSize();
2479 return this;
2480 };
2481
2482 /**
2483 * Update the window size.
2484 *
2485 * @throws {Error} An error is thrown if the window is not attached to a window manager
2486 * @chainable
2487 */
2488 OO.ui.Window.prototype.updateSize = function () {
2489 if ( !this.manager ) {
2490 throw new Error( 'Cannot update window size, must be attached to a manager' );
2491 }
2492
2493 this.manager.updateWindowSize( this );
2494
2495 return this;
2496 };
2497
2498 /**
2499 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2500 * when the window is opening. In general, setDimensions should not be called directly.
2501 *
2502 * To set the size of the window, use the #setSize method.
2503 *
2504 * @param {Object} dim CSS dimension properties
2505 * @param {string|number} [dim.width] Width
2506 * @param {string|number} [dim.minWidth] Minimum width
2507 * @param {string|number} [dim.maxWidth] Maximum width
2508 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2509 * @param {string|number} [dim.minWidth] Minimum height
2510 * @param {string|number} [dim.maxWidth] Maximum height
2511 * @chainable
2512 */
2513 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2514 var height,
2515 win = this,
2516 styleObj = this.$frame[ 0 ].style;
2517
2518 // Calculate the height we need to set using the correct width
2519 if ( dim.height === undefined ) {
2520 this.withoutSizeTransitions( function () {
2521 var oldWidth = styleObj.width;
2522 win.$frame.css( 'width', dim.width || '' );
2523 height = win.getContentHeight();
2524 styleObj.width = oldWidth;
2525 } );
2526 } else {
2527 height = dim.height;
2528 }
2529
2530 this.$frame.css( {
2531 width: dim.width || '',
2532 minWidth: dim.minWidth || '',
2533 maxWidth: dim.maxWidth || '',
2534 height: height || '',
2535 minHeight: dim.minHeight || '',
2536 maxHeight: dim.maxHeight || ''
2537 } );
2538
2539 return this;
2540 };
2541
2542 /**
2543 * Initialize window contents.
2544 *
2545 * Before the window is opened for the first time, #initialize is called so that content that
2546 * persists between openings can be added to the window.
2547 *
2548 * To set up a window with new content each time the window opens, use #getSetupProcess.
2549 *
2550 * @throws {Error} An error is thrown if the window is not attached to a window manager
2551 * @chainable
2552 */
2553 OO.ui.Window.prototype.initialize = function () {
2554 if ( !this.manager ) {
2555 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2556 }
2557
2558 // Properties
2559 this.$head = $( '<div>' );
2560 this.$body = $( '<div>' );
2561 this.$foot = $( '<div>' );
2562 this.$document = $( this.getElementDocument() );
2563
2564 // Events
2565 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2566
2567 // Initialization
2568 this.$head.addClass( 'oo-ui-window-head' );
2569 this.$body.addClass( 'oo-ui-window-body' );
2570 this.$foot.addClass( 'oo-ui-window-foot' );
2571 this.$content.append( this.$head, this.$body, this.$foot );
2572
2573 return this;
2574 };
2575
2576 /**
2577 * Called when someone tries to focus the hidden element at the end of the dialog.
2578 * Sends focus back to the start of the dialog.
2579 *
2580 * @param {jQuery.Event} event Focus event
2581 */
2582 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2583 if ( this.$focusTrapBefore.is( event.target ) ) {
2584 OO.ui.findFocusable( this.$content, true ).focus();
2585 } else {
2586 // this.$content is the part of the focus cycle, and is the first focusable element
2587 this.$content.focus();
2588 }
2589 };
2590
2591 /**
2592 * Open the window.
2593 *
2594 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2595 * method, which returns a promise resolved when the window is done opening.
2596 *
2597 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2598 *
2599 * @param {Object} [data] Window opening data
2600 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2601 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2602 * value is a new promise, which is resolved when the window begins closing.
2603 * @throws {Error} An error is thrown if the window is not attached to a window manager
2604 */
2605 OO.ui.Window.prototype.open = function ( data ) {
2606 if ( !this.manager ) {
2607 throw new Error( 'Cannot open window, must be attached to a manager' );
2608 }
2609
2610 return this.manager.openWindow( this, data );
2611 };
2612
2613 /**
2614 * Close the window.
2615 *
2616 * This method is a wrapper around a call to the window
2617 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2618 * which returns a closing promise resolved when the window is done closing.
2619 *
2620 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2621 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2622 * the window closes.
2623 *
2624 * @param {Object} [data] Window closing data
2625 * @return {jQuery.Promise} Promise resolved when window is closed
2626 * @throws {Error} An error is thrown if the window is not attached to a window manager
2627 */
2628 OO.ui.Window.prototype.close = function ( data ) {
2629 if ( !this.manager ) {
2630 throw new Error( 'Cannot close window, must be attached to a manager' );
2631 }
2632
2633 return this.manager.closeWindow( this, data );
2634 };
2635
2636 /**
2637 * Setup window.
2638 *
2639 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2640 * by other systems.
2641 *
2642 * @param {Object} [data] Window opening data
2643 * @return {jQuery.Promise} Promise resolved when window is setup
2644 */
2645 OO.ui.Window.prototype.setup = function ( data ) {
2646 var win = this,
2647 deferred = $.Deferred();
2648
2649 this.toggle( true );
2650
2651 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2652 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2653
2654 this.getSetupProcess( data ).execute().done( function () {
2655 // Force redraw by asking the browser to measure the elements' widths
2656 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2657 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2658 deferred.resolve();
2659 } );
2660
2661 return deferred.promise();
2662 };
2663
2664 /**
2665 * Ready window.
2666 *
2667 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2668 * by other systems.
2669 *
2670 * @param {Object} [data] Window opening data
2671 * @return {jQuery.Promise} Promise resolved when window is ready
2672 */
2673 OO.ui.Window.prototype.ready = function ( data ) {
2674 var win = this,
2675 deferred = $.Deferred();
2676
2677 this.$content.focus();
2678 this.getReadyProcess( data ).execute().done( function () {
2679 // Force redraw by asking the browser to measure the elements' widths
2680 win.$element.addClass( 'oo-ui-window-ready' ).width();
2681 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2682 deferred.resolve();
2683 } );
2684
2685 return deferred.promise();
2686 };
2687
2688 /**
2689 * Hold window.
2690 *
2691 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2692 * by other systems.
2693 *
2694 * @param {Object} [data] Window closing data
2695 * @return {jQuery.Promise} Promise resolved when window is held
2696 */
2697 OO.ui.Window.prototype.hold = function ( data ) {
2698 var win = this,
2699 deferred = $.Deferred();
2700
2701 this.getHoldProcess( data ).execute().done( function () {
2702 // Get the focused element within the window's content
2703 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2704
2705 // Blur the focused element
2706 if ( $focus.length ) {
2707 $focus[ 0 ].blur();
2708 }
2709
2710 // Force redraw by asking the browser to measure the elements' widths
2711 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2712 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2713 deferred.resolve();
2714 } );
2715
2716 return deferred.promise();
2717 };
2718
2719 /**
2720 * Teardown window.
2721 *
2722 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2723 * by other systems.
2724 *
2725 * @param {Object} [data] Window closing data
2726 * @return {jQuery.Promise} Promise resolved when window is torn down
2727 */
2728 OO.ui.Window.prototype.teardown = function ( data ) {
2729 var win = this;
2730
2731 return this.getTeardownProcess( data ).execute()
2732 .done( function () {
2733 // Force redraw by asking the browser to measure the elements' widths
2734 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2735 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2736 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2737 win.toggle( false );
2738 } );
2739 };
2740
2741 /**
2742 * The Dialog class serves as the base class for the other types of dialogs.
2743 * Unless extended to include controls, the rendered dialog box is a simple window
2744 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2745 * which opens, closes, and controls the presentation of the window. See the
2746 * [OOjs UI documentation on MediaWiki] [1] for more information.
2747 *
2748 * @example
2749 * // A simple dialog window.
2750 * function MyDialog( config ) {
2751 * MyDialog.parent.call( this, config );
2752 * }
2753 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2754 * MyDialog.prototype.initialize = function () {
2755 * MyDialog.parent.prototype.initialize.call( this );
2756 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2757 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2758 * this.$body.append( this.content.$element );
2759 * };
2760 * MyDialog.prototype.getBodyHeight = function () {
2761 * return this.content.$element.outerHeight( true );
2762 * };
2763 * var myDialog = new MyDialog( {
2764 * size: 'medium'
2765 * } );
2766 * // Create and append a window manager, which opens and closes the window.
2767 * var windowManager = new OO.ui.WindowManager();
2768 * $( 'body' ).append( windowManager.$element );
2769 * windowManager.addWindows( [ myDialog ] );
2770 * // Open the window!
2771 * windowManager.openWindow( myDialog );
2772 *
2773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2774 *
2775 * @abstract
2776 * @class
2777 * @extends OO.ui.Window
2778 * @mixins OO.ui.mixin.PendingElement
2779 *
2780 * @constructor
2781 * @param {Object} [config] Configuration options
2782 */
2783 OO.ui.Dialog = function OoUiDialog( config ) {
2784 // Parent constructor
2785 OO.ui.Dialog.parent.call( this, config );
2786
2787 // Mixin constructors
2788 OO.ui.mixin.PendingElement.call( this );
2789
2790 // Properties
2791 this.actions = new OO.ui.ActionSet();
2792 this.attachedActions = [];
2793 this.currentAction = null;
2794 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2795
2796 // Events
2797 this.actions.connect( this, {
2798 click: 'onActionClick',
2799 resize: 'onActionResize',
2800 change: 'onActionsChange'
2801 } );
2802
2803 // Initialization
2804 this.$element
2805 .addClass( 'oo-ui-dialog' )
2806 .attr( 'role', 'dialog' );
2807 };
2808
2809 /* Setup */
2810
2811 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2812 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2813
2814 /* Static Properties */
2815
2816 /**
2817 * Symbolic name of dialog.
2818 *
2819 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2820 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2821 *
2822 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2823 *
2824 * @abstract
2825 * @static
2826 * @inheritable
2827 * @property {string}
2828 */
2829 OO.ui.Dialog.static.name = '';
2830
2831 /**
2832 * The dialog title.
2833 *
2834 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2835 * that will produce a Label node or string. The title can also be specified with data passed to the
2836 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2837 *
2838 * @abstract
2839 * @static
2840 * @inheritable
2841 * @property {jQuery|string|Function}
2842 */
2843 OO.ui.Dialog.static.title = '';
2844
2845 /**
2846 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2847 *
2848 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2849 * value will be overriden.
2850 *
2851 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2852 *
2853 * @static
2854 * @inheritable
2855 * @property {Object[]}
2856 */
2857 OO.ui.Dialog.static.actions = [];
2858
2859 /**
2860 * Close the dialog when the 'Esc' key is pressed.
2861 *
2862 * @static
2863 * @abstract
2864 * @inheritable
2865 * @property {boolean}
2866 */
2867 OO.ui.Dialog.static.escapable = true;
2868
2869 /* Methods */
2870
2871 /**
2872 * Handle frame document key down events.
2873 *
2874 * @private
2875 * @param {jQuery.Event} e Key down event
2876 */
2877 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2878 if ( e.which === OO.ui.Keys.ESCAPE ) {
2879 this.close();
2880 e.preventDefault();
2881 e.stopPropagation();
2882 }
2883 };
2884
2885 /**
2886 * Handle action resized events.
2887 *
2888 * @private
2889 * @param {OO.ui.ActionWidget} action Action that was resized
2890 */
2891 OO.ui.Dialog.prototype.onActionResize = function () {
2892 // Override in subclass
2893 };
2894
2895 /**
2896 * Handle action click events.
2897 *
2898 * @private
2899 * @param {OO.ui.ActionWidget} action Action that was clicked
2900 */
2901 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2902 if ( !this.isPending() ) {
2903 this.executeAction( action.getAction() );
2904 }
2905 };
2906
2907 /**
2908 * Handle actions change event.
2909 *
2910 * @private
2911 */
2912 OO.ui.Dialog.prototype.onActionsChange = function () {
2913 this.detachActions();
2914 if ( !this.isClosing() ) {
2915 this.attachActions();
2916 }
2917 };
2918
2919 /**
2920 * Get the set of actions used by the dialog.
2921 *
2922 * @return {OO.ui.ActionSet}
2923 */
2924 OO.ui.Dialog.prototype.getActions = function () {
2925 return this.actions;
2926 };
2927
2928 /**
2929 * Get a process for taking action.
2930 *
2931 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2932 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2933 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2934 *
2935 * @abstract
2936 * @param {string} [action] Symbolic name of action
2937 * @return {OO.ui.Process} Action process
2938 */
2939 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2940 return new OO.ui.Process()
2941 .next( function () {
2942 if ( !action ) {
2943 // An empty action always closes the dialog without data, which should always be
2944 // safe and make no changes
2945 this.close();
2946 }
2947 }, this );
2948 };
2949
2950 /**
2951 * @inheritdoc
2952 *
2953 * @param {Object} [data] Dialog opening data
2954 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2955 * the {@link #static-title static title}
2956 * @param {Object[]} [data.actions] List of configuration options for each
2957 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2958 */
2959 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2960 data = data || {};
2961
2962 // Parent method
2963 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2964 .next( function () {
2965 var config = this.constructor.static,
2966 actions = data.actions !== undefined ? data.actions : config.actions;
2967
2968 this.title.setLabel(
2969 data.title !== undefined ? data.title : this.constructor.static.title
2970 );
2971 this.actions.add( this.getActionWidgets( actions ) );
2972
2973 if ( this.constructor.static.escapable ) {
2974 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2975 }
2976 }, this );
2977 };
2978
2979 /**
2980 * @inheritdoc
2981 */
2982 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2983 // Parent method
2984 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2985 .first( function () {
2986 if ( this.constructor.static.escapable ) {
2987 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2988 }
2989
2990 this.actions.clear();
2991 this.currentAction = null;
2992 }, this );
2993 };
2994
2995 /**
2996 * @inheritdoc
2997 */
2998 OO.ui.Dialog.prototype.initialize = function () {
2999 var titleId;
3000
3001 // Parent method
3002 OO.ui.Dialog.parent.prototype.initialize.call( this );
3003
3004 titleId = OO.ui.generateElementId();
3005
3006 // Properties
3007 this.title = new OO.ui.LabelWidget( {
3008 id: titleId
3009 } );
3010
3011 // Initialization
3012 this.$content.addClass( 'oo-ui-dialog-content' );
3013 this.$element.attr( 'aria-labelledby', titleId );
3014 this.setPendingElement( this.$head );
3015 };
3016
3017 /**
3018 * Get action widgets from a list of configs
3019 *
3020 * @param {Object[]} actions Action widget configs
3021 * @return {OO.ui.ActionWidget[]} Action widgets
3022 */
3023 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3024 var i, len, widgets = [];
3025 for ( i = 0, len = actions.length; i < len; i++ ) {
3026 widgets.push(
3027 new OO.ui.ActionWidget( actions[ i ] )
3028 );
3029 }
3030 return widgets;
3031 };
3032
3033 /**
3034 * Attach action actions.
3035 *
3036 * @protected
3037 */
3038 OO.ui.Dialog.prototype.attachActions = function () {
3039 // Remember the list of potentially attached actions
3040 this.attachedActions = this.actions.get();
3041 };
3042
3043 /**
3044 * Detach action actions.
3045 *
3046 * @protected
3047 * @chainable
3048 */
3049 OO.ui.Dialog.prototype.detachActions = function () {
3050 var i, len;
3051
3052 // Detach all actions that may have been previously attached
3053 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3054 this.attachedActions[ i ].$element.detach();
3055 }
3056 this.attachedActions = [];
3057 };
3058
3059 /**
3060 * Execute an action.
3061 *
3062 * @param {string} action Symbolic name of action to execute
3063 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3064 */
3065 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3066 this.pushPending();
3067 this.currentAction = action;
3068 return this.getActionProcess( action ).execute()
3069 .always( this.popPending.bind( this ) );
3070 };
3071
3072 /**
3073 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3074 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3075 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3076 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3077 * pertinent data and reused.
3078 *
3079 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3080 * `opened`, and `closing`, which represent the primary stages of the cycle:
3081 *
3082 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3083 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3084 *
3085 * - an `opening` event is emitted with an `opening` promise
3086 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3087 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3088 * window and its result executed
3089 * - a `setup` progress notification is emitted from the `opening` promise
3090 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3091 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3092 * window and its result executed
3093 * - a `ready` progress notification is emitted from the `opening` promise
3094 * - the `opening` promise is resolved with an `opened` promise
3095 *
3096 * **Opened**: the window is now open.
3097 *
3098 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3099 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3100 * to close the window.
3101 *
3102 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3103 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3104 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3105 * window and its result executed
3106 * - a `hold` progress notification is emitted from the `closing` promise
3107 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3108 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3109 * window and its result executed
3110 * - a `teardown` progress notification is emitted from the `closing` promise
3111 * - the `closing` promise is resolved. The window is now closed
3112 *
3113 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3114 *
3115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3116 *
3117 * @class
3118 * @extends OO.ui.Element
3119 * @mixins OO.EventEmitter
3120 *
3121 * @constructor
3122 * @param {Object} [config] Configuration options
3123 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3124 * Note that window classes that are instantiated with a factory must have
3125 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3126 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3127 */
3128 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3129 // Configuration initialization
3130 config = config || {};
3131
3132 // Parent constructor
3133 OO.ui.WindowManager.parent.call( this, config );
3134
3135 // Mixin constructors
3136 OO.EventEmitter.call( this );
3137
3138 // Properties
3139 this.factory = config.factory;
3140 this.modal = config.modal === undefined || !!config.modal;
3141 this.windows = {};
3142 this.opening = null;
3143 this.opened = null;
3144 this.closing = null;
3145 this.preparingToOpen = null;
3146 this.preparingToClose = null;
3147 this.currentWindow = null;
3148 this.globalEvents = false;
3149 this.$ariaHidden = null;
3150 this.onWindowResizeTimeout = null;
3151 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3152 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3153
3154 // Initialization
3155 this.$element
3156 .addClass( 'oo-ui-windowManager' )
3157 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3158 };
3159
3160 /* Setup */
3161
3162 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3163 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3164
3165 /* Events */
3166
3167 /**
3168 * An 'opening' event is emitted when the window begins to be opened.
3169 *
3170 * @event opening
3171 * @param {OO.ui.Window} win Window that's being opened
3172 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3173 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3174 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3175 * @param {Object} data Window opening data
3176 */
3177
3178 /**
3179 * A 'closing' event is emitted when the window begins to be closed.
3180 *
3181 * @event closing
3182 * @param {OO.ui.Window} win Window that's being closed
3183 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3184 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3185 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3186 * is the closing data.
3187 * @param {Object} data Window closing data
3188 */
3189
3190 /**
3191 * A 'resize' event is emitted when a window is resized.
3192 *
3193 * @event resize
3194 * @param {OO.ui.Window} win Window that was resized
3195 */
3196
3197 /* Static Properties */
3198
3199 /**
3200 * Map of the symbolic name of each window size and its CSS properties.
3201 *
3202 * @static
3203 * @inheritable
3204 * @property {Object}
3205 */
3206 OO.ui.WindowManager.static.sizes = {
3207 small: {
3208 width: 300
3209 },
3210 medium: {
3211 width: 500
3212 },
3213 large: {
3214 width: 700
3215 },
3216 larger: {
3217 width: 900
3218 },
3219 full: {
3220 // These can be non-numeric because they are never used in calculations
3221 width: '100%',
3222 height: '100%'
3223 }
3224 };
3225
3226 /**
3227 * Symbolic name of the default window size.
3228 *
3229 * The default size is used if the window's requested size is not recognized.
3230 *
3231 * @static
3232 * @inheritable
3233 * @property {string}
3234 */
3235 OO.ui.WindowManager.static.defaultSize = 'medium';
3236
3237 /* Methods */
3238
3239 /**
3240 * Handle window resize events.
3241 *
3242 * @private
3243 * @param {jQuery.Event} e Window resize event
3244 */
3245 OO.ui.WindowManager.prototype.onWindowResize = function () {
3246 clearTimeout( this.onWindowResizeTimeout );
3247 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3248 };
3249
3250 /**
3251 * Handle window resize events.
3252 *
3253 * @private
3254 * @param {jQuery.Event} e Window resize event
3255 */
3256 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3257 if ( this.currentWindow ) {
3258 this.updateWindowSize( this.currentWindow );
3259 }
3260 };
3261
3262 /**
3263 * Check if window is opening.
3264 *
3265 * @return {boolean} Window is opening
3266 */
3267 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3268 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3269 };
3270
3271 /**
3272 * Check if window is closing.
3273 *
3274 * @return {boolean} Window is closing
3275 */
3276 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3277 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3278 };
3279
3280 /**
3281 * Check if window is opened.
3282 *
3283 * @return {boolean} Window is opened
3284 */
3285 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3286 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3287 };
3288
3289 /**
3290 * Check if a window is being managed.
3291 *
3292 * @param {OO.ui.Window} win Window to check
3293 * @return {boolean} Window is being managed
3294 */
3295 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3296 var name;
3297
3298 for ( name in this.windows ) {
3299 if ( this.windows[ name ] === win ) {
3300 return true;
3301 }
3302 }
3303
3304 return false;
3305 };
3306
3307 /**
3308 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3309 *
3310 * @param {OO.ui.Window} win Window being opened
3311 * @param {Object} [data] Window opening data
3312 * @return {number} Milliseconds to wait
3313 */
3314 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3315 return 0;
3316 };
3317
3318 /**
3319 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3320 *
3321 * @param {OO.ui.Window} win Window being opened
3322 * @param {Object} [data] Window opening data
3323 * @return {number} Milliseconds to wait
3324 */
3325 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3326 return 0;
3327 };
3328
3329 /**
3330 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3331 *
3332 * @param {OO.ui.Window} win Window being closed
3333 * @param {Object} [data] Window closing data
3334 * @return {number} Milliseconds to wait
3335 */
3336 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3337 return 0;
3338 };
3339
3340 /**
3341 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3342 * executing the ‘teardown’ process.
3343 *
3344 * @param {OO.ui.Window} win Window being closed
3345 * @param {Object} [data] Window closing data
3346 * @return {number} Milliseconds to wait
3347 */
3348 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3349 return this.modal ? 250 : 0;
3350 };
3351
3352 /**
3353 * Get a window by its symbolic name.
3354 *
3355 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3356 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3357 * for more information about using factories.
3358 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3359 *
3360 * @param {string} name Symbolic name of the window
3361 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3362 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3363 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3364 */
3365 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3366 var deferred = $.Deferred(),
3367 win = this.windows[ name ];
3368
3369 if ( !( win instanceof OO.ui.Window ) ) {
3370 if ( this.factory ) {
3371 if ( !this.factory.lookup( name ) ) {
3372 deferred.reject( new OO.ui.Error(
3373 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3374 ) );
3375 } else {
3376 win = this.factory.create( name );
3377 this.addWindows( [ win ] );
3378 deferred.resolve( win );
3379 }
3380 } else {
3381 deferred.reject( new OO.ui.Error(
3382 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3383 ) );
3384 }
3385 } else {
3386 deferred.resolve( win );
3387 }
3388
3389 return deferred.promise();
3390 };
3391
3392 /**
3393 * Get current window.
3394 *
3395 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3396 */
3397 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3398 return this.currentWindow;
3399 };
3400
3401 /**
3402 * Open a window.
3403 *
3404 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3405 * @param {Object} [data] Window opening data
3406 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3407 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3408 * @fires opening
3409 */
3410 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3411 var manager = this,
3412 opening = $.Deferred();
3413
3414 // Argument handling
3415 if ( typeof win === 'string' ) {
3416 return this.getWindow( win ).then( function ( win ) {
3417 return manager.openWindow( win, data );
3418 } );
3419 }
3420
3421 // Error handling
3422 if ( !this.hasWindow( win ) ) {
3423 opening.reject( new OO.ui.Error(
3424 'Cannot open window: window is not attached to manager'
3425 ) );
3426 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3427 opening.reject( new OO.ui.Error(
3428 'Cannot open window: another window is opening or open'
3429 ) );
3430 }
3431
3432 // Window opening
3433 if ( opening.state() !== 'rejected' ) {
3434 // If a window is currently closing, wait for it to complete
3435 this.preparingToOpen = $.when( this.closing );
3436 // Ensure handlers get called after preparingToOpen is set
3437 this.preparingToOpen.done( function () {
3438 if ( manager.modal ) {
3439 manager.toggleGlobalEvents( true );
3440 manager.toggleAriaIsolation( true );
3441 }
3442 manager.currentWindow = win;
3443 manager.opening = opening;
3444 manager.preparingToOpen = null;
3445 manager.emit( 'opening', win, opening, data );
3446 setTimeout( function () {
3447 win.setup( data ).then( function () {
3448 manager.updateWindowSize( win );
3449 manager.opening.notify( { state: 'setup' } );
3450 setTimeout( function () {
3451 win.ready( data ).then( function () {
3452 manager.opening.notify( { state: 'ready' } );
3453 manager.opening = null;
3454 manager.opened = $.Deferred();
3455 opening.resolve( manager.opened.promise(), data );
3456 } );
3457 }, manager.getReadyDelay() );
3458 } );
3459 }, manager.getSetupDelay() );
3460 } );
3461 }
3462
3463 return opening.promise();
3464 };
3465
3466 /**
3467 * Close a window.
3468 *
3469 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3470 * @param {Object} [data] Window closing data
3471 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3472 * See {@link #event-closing 'closing' event} for more information about closing promises.
3473 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3474 * @fires closing
3475 */
3476 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3477 var manager = this,
3478 closing = $.Deferred(),
3479 opened;
3480
3481 // Argument handling
3482 if ( typeof win === 'string' ) {
3483 win = this.windows[ win ];
3484 } else if ( !this.hasWindow( win ) ) {
3485 win = null;
3486 }
3487
3488 // Error handling
3489 if ( !win ) {
3490 closing.reject( new OO.ui.Error(
3491 'Cannot close window: window is not attached to manager'
3492 ) );
3493 } else if ( win !== this.currentWindow ) {
3494 closing.reject( new OO.ui.Error(
3495 'Cannot close window: window already closed with different data'
3496 ) );
3497 } else if ( this.preparingToClose || this.closing ) {
3498 closing.reject( new OO.ui.Error(
3499 'Cannot close window: window already closing with different data'
3500 ) );
3501 }
3502
3503 // Window closing
3504 if ( closing.state() !== 'rejected' ) {
3505 // If the window is currently opening, close it when it's done
3506 this.preparingToClose = $.when( this.opening );
3507 // Ensure handlers get called after preparingToClose is set
3508 this.preparingToClose.done( function () {
3509 manager.closing = closing;
3510 manager.preparingToClose = null;
3511 manager.emit( 'closing', win, closing, data );
3512 opened = manager.opened;
3513 manager.opened = null;
3514 opened.resolve( closing.promise(), data );
3515 setTimeout( function () {
3516 win.hold( data ).then( function () {
3517 closing.notify( { state: 'hold' } );
3518 setTimeout( function () {
3519 win.teardown( data ).then( function () {
3520 closing.notify( { state: 'teardown' } );
3521 if ( manager.modal ) {
3522 manager.toggleGlobalEvents( false );
3523 manager.toggleAriaIsolation( false );
3524 }
3525 manager.closing = null;
3526 manager.currentWindow = null;
3527 closing.resolve( data );
3528 } );
3529 }, manager.getTeardownDelay() );
3530 } );
3531 }, manager.getHoldDelay() );
3532 } );
3533 }
3534
3535 return closing.promise();
3536 };
3537
3538 /**
3539 * Add windows to the window manager.
3540 *
3541 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3542 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3543 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3544 *
3545 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3546 * by reference, symbolic name, or explicitly defined symbolic names.
3547 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3548 * explicit nor a statically configured symbolic name.
3549 */
3550 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3551 var i, len, win, name, list;
3552
3553 if ( Array.isArray( windows ) ) {
3554 // Convert to map of windows by looking up symbolic names from static configuration
3555 list = {};
3556 for ( i = 0, len = windows.length; i < len; i++ ) {
3557 name = windows[ i ].constructor.static.name;
3558 if ( typeof name !== 'string' ) {
3559 throw new Error( 'Cannot add window' );
3560 }
3561 list[ name ] = windows[ i ];
3562 }
3563 } else if ( OO.isPlainObject( windows ) ) {
3564 list = windows;
3565 }
3566
3567 // Add windows
3568 for ( name in list ) {
3569 win = list[ name ];
3570 this.windows[ name ] = win.toggle( false );
3571 this.$element.append( win.$element );
3572 win.setManager( this );
3573 }
3574 };
3575
3576 /**
3577 * Remove the specified windows from the windows manager.
3578 *
3579 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3580 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3581 * longer listens to events, use the #destroy method.
3582 *
3583 * @param {string[]} names Symbolic names of windows to remove
3584 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3585 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3586 */
3587 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3588 var i, len, win, name, cleanupWindow,
3589 manager = this,
3590 promises = [],
3591 cleanup = function ( name, win ) {
3592 delete manager.windows[ name ];
3593 win.$element.detach();
3594 };
3595
3596 for ( i = 0, len = names.length; i < len; i++ ) {
3597 name = names[ i ];
3598 win = this.windows[ name ];
3599 if ( !win ) {
3600 throw new Error( 'Cannot remove window' );
3601 }
3602 cleanupWindow = cleanup.bind( null, name, win );
3603 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3604 }
3605
3606 return $.when.apply( $, promises );
3607 };
3608
3609 /**
3610 * Remove all windows from the window manager.
3611 *
3612 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3613 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3614 * To remove just a subset of windows, use the #removeWindows method.
3615 *
3616 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3617 */
3618 OO.ui.WindowManager.prototype.clearWindows = function () {
3619 return this.removeWindows( Object.keys( this.windows ) );
3620 };
3621
3622 /**
3623 * Set dialog size. In general, this method should not be called directly.
3624 *
3625 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3626 *
3627 * @chainable
3628 */
3629 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3630 var isFullscreen;
3631
3632 // Bypass for non-current, and thus invisible, windows
3633 if ( win !== this.currentWindow ) {
3634 return;
3635 }
3636
3637 isFullscreen = win.getSize() === 'full';
3638
3639 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3640 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3641 win.setDimensions( win.getSizeProperties() );
3642
3643 this.emit( 'resize', win );
3644
3645 return this;
3646 };
3647
3648 /**
3649 * Bind or unbind global events for scrolling.
3650 *
3651 * @private
3652 * @param {boolean} [on] Bind global events
3653 * @chainable
3654 */
3655 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3656 var scrollWidth, bodyMargin,
3657 $body = $( this.getElementDocument().body ),
3658 // We could have multiple window managers open so only modify
3659 // the body css at the bottom of the stack
3660 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3661
3662 on = on === undefined ? !!this.globalEvents : !!on;
3663
3664 if ( on ) {
3665 if ( !this.globalEvents ) {
3666 $( this.getElementWindow() ).on( {
3667 // Start listening for top-level window dimension changes
3668 'orientationchange resize': this.onWindowResizeHandler
3669 } );
3670 if ( stackDepth === 0 ) {
3671 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3672 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3673 $body.css( {
3674 overflow: 'hidden',
3675 'margin-right': bodyMargin + scrollWidth
3676 } );
3677 }
3678 stackDepth++;
3679 this.globalEvents = true;
3680 }
3681 } else if ( this.globalEvents ) {
3682 $( this.getElementWindow() ).off( {
3683 // Stop listening for top-level window dimension changes
3684 'orientationchange resize': this.onWindowResizeHandler
3685 } );
3686 stackDepth--;
3687 if ( stackDepth === 0 ) {
3688 $body.css( {
3689 overflow: '',
3690 'margin-right': ''
3691 } );
3692 }
3693 this.globalEvents = false;
3694 }
3695 $body.data( 'windowManagerGlobalEvents', stackDepth );
3696
3697 return this;
3698 };
3699
3700 /**
3701 * Toggle screen reader visibility of content other than the window manager.
3702 *
3703 * @private
3704 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3705 * @chainable
3706 */
3707 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3708 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3709
3710 if ( isolate ) {
3711 if ( !this.$ariaHidden ) {
3712 // Hide everything other than the window manager from screen readers
3713 this.$ariaHidden = $( 'body' )
3714 .children()
3715 .not( this.$element.parentsUntil( 'body' ).last() )
3716 .attr( 'aria-hidden', '' );
3717 }
3718 } else if ( this.$ariaHidden ) {
3719 // Restore screen reader visibility
3720 this.$ariaHidden.removeAttr( 'aria-hidden' );
3721 this.$ariaHidden = null;
3722 }
3723
3724 return this;
3725 };
3726
3727 /**
3728 * Destroy the window manager.
3729 *
3730 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3731 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3732 * instead.
3733 */
3734 OO.ui.WindowManager.prototype.destroy = function () {
3735 this.toggleGlobalEvents( false );
3736 this.toggleAriaIsolation( false );
3737 this.clearWindows();
3738 this.$element.remove();
3739 };
3740
3741 /**
3742 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3743 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3744 * appearance and functionality of the error interface.
3745 *
3746 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3747 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3748 * that initiated the failed process will be disabled.
3749 *
3750 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3751 * process again.
3752 *
3753 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3754 *
3755 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3756 *
3757 * @class
3758 *
3759 * @constructor
3760 * @param {string|jQuery} message Description of error
3761 * @param {Object} [config] Configuration options
3762 * @cfg {boolean} [recoverable=true] Error is recoverable.
3763 * By default, errors are recoverable, and users can try the process again.
3764 * @cfg {boolean} [warning=false] Error is a warning.
3765 * If the error is a warning, the error interface will include a
3766 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3767 * is not triggered a second time if the user chooses to continue.
3768 */
3769 OO.ui.Error = function OoUiError( message, config ) {
3770 // Allow passing positional parameters inside the config object
3771 if ( OO.isPlainObject( message ) && config === undefined ) {
3772 config = message;
3773 message = config.message;
3774 }
3775
3776 // Configuration initialization
3777 config = config || {};
3778
3779 // Properties
3780 this.message = message instanceof jQuery ? message : String( message );
3781 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3782 this.warning = !!config.warning;
3783 };
3784
3785 /* Setup */
3786
3787 OO.initClass( OO.ui.Error );
3788
3789 /* Methods */
3790
3791 /**
3792 * Check if the error is recoverable.
3793 *
3794 * If the error is recoverable, users are able to try the process again.
3795 *
3796 * @return {boolean} Error is recoverable
3797 */
3798 OO.ui.Error.prototype.isRecoverable = function () {
3799 return this.recoverable;
3800 };
3801
3802 /**
3803 * Check if the error is a warning.
3804 *
3805 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3806 *
3807 * @return {boolean} Error is warning
3808 */
3809 OO.ui.Error.prototype.isWarning = function () {
3810 return this.warning;
3811 };
3812
3813 /**
3814 * Get error message as DOM nodes.
3815 *
3816 * @return {jQuery} Error message in DOM nodes
3817 */
3818 OO.ui.Error.prototype.getMessage = function () {
3819 return this.message instanceof jQuery ?
3820 this.message.clone() :
3821 $( '<div>' ).text( this.message ).contents();
3822 };
3823
3824 /**
3825 * Get the error message text.
3826 *
3827 * @return {string} Error message
3828 */
3829 OO.ui.Error.prototype.getMessageText = function () {
3830 return this.message instanceof jQuery ? this.message.text() : this.message;
3831 };
3832
3833 /**
3834 * Wraps an HTML snippet for use with configuration values which default
3835 * to strings. This bypasses the default html-escaping done to string
3836 * values.
3837 *
3838 * @class
3839 *
3840 * @constructor
3841 * @param {string} [content] HTML content
3842 */
3843 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3844 // Properties
3845 this.content = content;
3846 };
3847
3848 /* Setup */
3849
3850 OO.initClass( OO.ui.HtmlSnippet );
3851
3852 /* Methods */
3853
3854 /**
3855 * Render into HTML.
3856 *
3857 * @return {string} Unchanged HTML snippet.
3858 */
3859 OO.ui.HtmlSnippet.prototype.toString = function () {
3860 return this.content;
3861 };
3862
3863 /**
3864 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3865 * or a function:
3866 *
3867 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3868 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3869 * or stop if the promise is rejected.
3870 * - **function**: the process will execute the function. The process will stop if the function returns
3871 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3872 * will wait for that number of milliseconds before proceeding.
3873 *
3874 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3875 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3876 * its remaining steps will not be performed.
3877 *
3878 * @class
3879 *
3880 * @constructor
3881 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3882 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3883 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3884 * a number or promise.
3885 * @return {Object} Step object, with `callback` and `context` properties
3886 */
3887 OO.ui.Process = function ( step, context ) {
3888 // Properties
3889 this.steps = [];
3890
3891 // Initialization
3892 if ( step !== undefined ) {
3893 this.next( step, context );
3894 }
3895 };
3896
3897 /* Setup */
3898
3899 OO.initClass( OO.ui.Process );
3900
3901 /* Methods */
3902
3903 /**
3904 * Start the process.
3905 *
3906 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3907 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3908 * and any remaining steps are not performed.
3909 */
3910 OO.ui.Process.prototype.execute = function () {
3911 var i, len, promise;
3912
3913 /**
3914 * Continue execution.
3915 *
3916 * @ignore
3917 * @param {Array} step A function and the context it should be called in
3918 * @return {Function} Function that continues the process
3919 */
3920 function proceed( step ) {
3921 return function () {
3922 // Execute step in the correct context
3923 var deferred,
3924 result = step.callback.call( step.context );
3925
3926 if ( result === false ) {
3927 // Use rejected promise for boolean false results
3928 return $.Deferred().reject( [] ).promise();
3929 }
3930 if ( typeof result === 'number' ) {
3931 if ( result < 0 ) {
3932 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3933 }
3934 // Use a delayed promise for numbers, expecting them to be in milliseconds
3935 deferred = $.Deferred();
3936 setTimeout( deferred.resolve, result );
3937 return deferred.promise();
3938 }
3939 if ( result instanceof OO.ui.Error ) {
3940 // Use rejected promise for error
3941 return $.Deferred().reject( [ result ] ).promise();
3942 }
3943 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3944 // Use rejected promise for list of errors
3945 return $.Deferred().reject( result ).promise();
3946 }
3947 // Duck-type the object to see if it can produce a promise
3948 if ( result && $.isFunction( result.promise ) ) {
3949 // Use a promise generated from the result
3950 return result.promise();
3951 }
3952 // Use resolved promise for other results
3953 return $.Deferred().resolve().promise();
3954 };
3955 }
3956
3957 if ( this.steps.length ) {
3958 // Generate a chain reaction of promises
3959 promise = proceed( this.steps[ 0 ] )();
3960 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3961 promise = promise.then( proceed( this.steps[ i ] ) );
3962 }
3963 } else {
3964 promise = $.Deferred().resolve().promise();
3965 }
3966
3967 return promise;
3968 };
3969
3970 /**
3971 * Create a process step.
3972 *
3973 * @private
3974 * @param {number|jQuery.Promise|Function} step
3975 *
3976 * - Number of milliseconds to wait before proceeding
3977 * - Promise that must be resolved before proceeding
3978 * - Function to execute
3979 * - If the function returns a boolean false the process will stop
3980 * - If the function returns a promise, the process will continue to the next
3981 * step when the promise is resolved or stop if the promise is rejected
3982 * - If the function returns a number, the process will wait for that number of
3983 * milliseconds before proceeding
3984 * @param {Object} [context=null] Execution context of the function. The context is
3985 * ignored if the step is a number or promise.
3986 * @return {Object} Step object, with `callback` and `context` properties
3987 */
3988 OO.ui.Process.prototype.createStep = function ( step, context ) {
3989 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3990 return {
3991 callback: function () {
3992 return step;
3993 },
3994 context: null
3995 };
3996 }
3997 if ( $.isFunction( step ) ) {
3998 return {
3999 callback: step,
4000 context: context
4001 };
4002 }
4003 throw new Error( 'Cannot create process step: number, promise or function expected' );
4004 };
4005
4006 /**
4007 * Add step to the beginning of the process.
4008 *
4009 * @inheritdoc #createStep
4010 * @return {OO.ui.Process} this
4011 * @chainable
4012 */
4013 OO.ui.Process.prototype.first = function ( step, context ) {
4014 this.steps.unshift( this.createStep( step, context ) );
4015 return this;
4016 };
4017
4018 /**
4019 * Add step to the end of the process.
4020 *
4021 * @inheritdoc #createStep
4022 * @return {OO.ui.Process} this
4023 * @chainable
4024 */
4025 OO.ui.Process.prototype.next = function ( step, context ) {
4026 this.steps.push( this.createStep( step, context ) );
4027 return this;
4028 };
4029
4030 /**
4031 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4032 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4033 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4034 *
4035 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4036 *
4037 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4038 *
4039 * @class
4040 * @extends OO.Factory
4041 * @constructor
4042 */
4043 OO.ui.ToolFactory = function OoUiToolFactory() {
4044 // Parent constructor
4045 OO.ui.ToolFactory.parent.call( this );
4046 };
4047
4048 /* Setup */
4049
4050 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4051
4052 /* Methods */
4053
4054 /**
4055 * Get tools from the factory
4056 *
4057 * @param {Array} include Included tools
4058 * @param {Array} exclude Excluded tools
4059 * @param {Array} promote Promoted tools
4060 * @param {Array} demote Demoted tools
4061 * @return {string[]} List of tools
4062 */
4063 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4064 var i, len, included, promoted, demoted,
4065 auto = [],
4066 used = {};
4067
4068 // Collect included and not excluded tools
4069 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4070
4071 // Promotion
4072 promoted = this.extract( promote, used );
4073 demoted = this.extract( demote, used );
4074
4075 // Auto
4076 for ( i = 0, len = included.length; i < len; i++ ) {
4077 if ( !used[ included[ i ] ] ) {
4078 auto.push( included[ i ] );
4079 }
4080 }
4081
4082 return promoted.concat( auto ).concat( demoted );
4083 };
4084
4085 /**
4086 * Get a flat list of names from a list of names or groups.
4087 *
4088 * Tools can be specified in the following ways:
4089 *
4090 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4091 * - All tools in a group: `{ group: 'group-name' }`
4092 * - All tools: `'*'`
4093 *
4094 * @private
4095 * @param {Array|string} collection List of tools
4096 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4097 * names will be added as properties
4098 * @return {string[]} List of extracted names
4099 */
4100 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4101 var i, len, item, name, tool,
4102 names = [];
4103
4104 if ( collection === '*' ) {
4105 for ( name in this.registry ) {
4106 tool = this.registry[ name ];
4107 if (
4108 // Only add tools by group name when auto-add is enabled
4109 tool.static.autoAddToCatchall &&
4110 // Exclude already used tools
4111 ( !used || !used[ name ] )
4112 ) {
4113 names.push( name );
4114 if ( used ) {
4115 used[ name ] = true;
4116 }
4117 }
4118 }
4119 } else if ( Array.isArray( collection ) ) {
4120 for ( i = 0, len = collection.length; i < len; i++ ) {
4121 item = collection[ i ];
4122 // Allow plain strings as shorthand for named tools
4123 if ( typeof item === 'string' ) {
4124 item = { name: item };
4125 }
4126 if ( OO.isPlainObject( item ) ) {
4127 if ( item.group ) {
4128 for ( name in this.registry ) {
4129 tool = this.registry[ name ];
4130 if (
4131 // Include tools with matching group
4132 tool.static.group === item.group &&
4133 // Only add tools by group name when auto-add is enabled
4134 tool.static.autoAddToGroup &&
4135 // Exclude already used tools
4136 ( !used || !used[ name ] )
4137 ) {
4138 names.push( name );
4139 if ( used ) {
4140 used[ name ] = true;
4141 }
4142 }
4143 }
4144 // Include tools with matching name and exclude already used tools
4145 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4146 names.push( item.name );
4147 if ( used ) {
4148 used[ item.name ] = true;
4149 }
4150 }
4151 }
4152 }
4153 }
4154 return names;
4155 };
4156
4157 /**
4158 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4159 * specify a symbolic name and be registered with the factory. The following classes are registered by
4160 * default:
4161 *
4162 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4163 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4164 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4165 *
4166 * See {@link OO.ui.Toolbar toolbars} for an example.
4167 *
4168 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4169 *
4170 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4171 * @class
4172 * @extends OO.Factory
4173 * @constructor
4174 */
4175 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4176 var i, l, defaultClasses;
4177 // Parent constructor
4178 OO.Factory.call( this );
4179
4180 defaultClasses = this.constructor.static.getDefaultClasses();
4181
4182 // Register default toolgroups
4183 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4184 this.register( defaultClasses[ i ] );
4185 }
4186 };
4187
4188 /* Setup */
4189
4190 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4191
4192 /* Static Methods */
4193
4194 /**
4195 * Get a default set of classes to be registered on construction.
4196 *
4197 * @return {Function[]} Default classes
4198 */
4199 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4200 return [
4201 OO.ui.BarToolGroup,
4202 OO.ui.ListToolGroup,
4203 OO.ui.MenuToolGroup
4204 ];
4205 };
4206
4207 /**
4208 * Theme logic.
4209 *
4210 * @abstract
4211 * @class
4212 *
4213 * @constructor
4214 * @param {Object} [config] Configuration options
4215 */
4216 OO.ui.Theme = function OoUiTheme( config ) {
4217 // Configuration initialization
4218 config = config || {};
4219 };
4220
4221 /* Setup */
4222
4223 OO.initClass( OO.ui.Theme );
4224
4225 /* Methods */
4226
4227 /**
4228 * Get a list of classes to be applied to a widget.
4229 *
4230 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4231 * otherwise state transitions will not work properly.
4232 *
4233 * @param {OO.ui.Element} element Element for which to get classes
4234 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4235 */
4236 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4237 return { on: [], off: [] };
4238 };
4239
4240 /**
4241 * Update CSS classes provided by the theme.
4242 *
4243 * For elements with theme logic hooks, this should be called any time there's a state change.
4244 *
4245 * @param {OO.ui.Element} element Element for which to update classes
4246 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4247 */
4248 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4249 var $elements = $( [] ),
4250 classes = this.getElementClasses( element );
4251
4252 if ( element.$icon ) {
4253 $elements = $elements.add( element.$icon );
4254 }
4255 if ( element.$indicator ) {
4256 $elements = $elements.add( element.$indicator );
4257 }
4258
4259 $elements
4260 .removeClass( classes.off.join( ' ' ) )
4261 .addClass( classes.on.join( ' ' ) );
4262 };
4263
4264 /**
4265 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4266 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4267 * order in which users will navigate through the focusable elements via the "tab" key.
4268 *
4269 * @example
4270 * // TabIndexedElement is mixed into the ButtonWidget class
4271 * // to provide a tabIndex property.
4272 * var button1 = new OO.ui.ButtonWidget( {
4273 * label: 'fourth',
4274 * tabIndex: 4
4275 * } );
4276 * var button2 = new OO.ui.ButtonWidget( {
4277 * label: 'second',
4278 * tabIndex: 2
4279 * } );
4280 * var button3 = new OO.ui.ButtonWidget( {
4281 * label: 'third',
4282 * tabIndex: 3
4283 * } );
4284 * var button4 = new OO.ui.ButtonWidget( {
4285 * label: 'first',
4286 * tabIndex: 1
4287 * } );
4288 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4289 *
4290 * @abstract
4291 * @class
4292 *
4293 * @constructor
4294 * @param {Object} [config] Configuration options
4295 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4296 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4297 * functionality will be applied to it instead.
4298 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4299 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4300 * to remove the element from the tab-navigation flow.
4301 */
4302 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4303 // Configuration initialization
4304 config = $.extend( { tabIndex: 0 }, config );
4305
4306 // Properties
4307 this.$tabIndexed = null;
4308 this.tabIndex = null;
4309
4310 // Events
4311 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4312
4313 // Initialization
4314 this.setTabIndex( config.tabIndex );
4315 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4316 };
4317
4318 /* Setup */
4319
4320 OO.initClass( OO.ui.mixin.TabIndexedElement );
4321
4322 /* Methods */
4323
4324 /**
4325 * Set the element that should use the tabindex functionality.
4326 *
4327 * This method is used to retarget a tabindex mixin so that its functionality applies
4328 * to the specified element. If an element is currently using the functionality, the mixin’s
4329 * effect on that element is removed before the new element is set up.
4330 *
4331 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4332 * @chainable
4333 */
4334 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4335 var tabIndex = this.tabIndex;
4336 // Remove attributes from old $tabIndexed
4337 this.setTabIndex( null );
4338 // Force update of new $tabIndexed
4339 this.$tabIndexed = $tabIndexed;
4340 this.tabIndex = tabIndex;
4341 return this.updateTabIndex();
4342 };
4343
4344 /**
4345 * Set the value of the tabindex.
4346 *
4347 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4348 * @chainable
4349 */
4350 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4351 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4352
4353 if ( this.tabIndex !== tabIndex ) {
4354 this.tabIndex = tabIndex;
4355 this.updateTabIndex();
4356 }
4357
4358 return this;
4359 };
4360
4361 /**
4362 * Update the `tabindex` attribute, in case of changes to tab index or
4363 * disabled state.
4364 *
4365 * @private
4366 * @chainable
4367 */
4368 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4369 if ( this.$tabIndexed ) {
4370 if ( this.tabIndex !== null ) {
4371 // Do not index over disabled elements
4372 this.$tabIndexed.attr( {
4373 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4374 // Support: ChromeVox and NVDA
4375 // These do not seem to inherit aria-disabled from parent elements
4376 'aria-disabled': this.isDisabled().toString()
4377 } );
4378 } else {
4379 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4380 }
4381 }
4382 return this;
4383 };
4384
4385 /**
4386 * Handle disable events.
4387 *
4388 * @private
4389 * @param {boolean} disabled Element is disabled
4390 */
4391 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4392 this.updateTabIndex();
4393 };
4394
4395 /**
4396 * Get the value of the tabindex.
4397 *
4398 * @return {number|null} Tabindex value
4399 */
4400 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4401 return this.tabIndex;
4402 };
4403
4404 /**
4405 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4406 * interface element that can be configured with access keys for accessibility.
4407 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4408 *
4409 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4410 * @abstract
4411 * @class
4412 *
4413 * @constructor
4414 * @param {Object} [config] Configuration options
4415 * @cfg {jQuery} [$button] The button element created by the class.
4416 * If this configuration is omitted, the button element will use a generated `<a>`.
4417 * @cfg {boolean} [framed=true] Render the button with a frame
4418 */
4419 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4420 // Configuration initialization
4421 config = config || {};
4422
4423 // Properties
4424 this.$button = null;
4425 this.framed = null;
4426 this.active = false;
4427 this.onMouseUpHandler = this.onMouseUp.bind( this );
4428 this.onMouseDownHandler = this.onMouseDown.bind( this );
4429 this.onKeyDownHandler = this.onKeyDown.bind( this );
4430 this.onKeyUpHandler = this.onKeyUp.bind( this );
4431 this.onClickHandler = this.onClick.bind( this );
4432 this.onKeyPressHandler = this.onKeyPress.bind( this );
4433
4434 // Initialization
4435 this.$element.addClass( 'oo-ui-buttonElement' );
4436 this.toggleFramed( config.framed === undefined || config.framed );
4437 this.setButtonElement( config.$button || $( '<a>' ) );
4438 };
4439
4440 /* Setup */
4441
4442 OO.initClass( OO.ui.mixin.ButtonElement );
4443
4444 /* Static Properties */
4445
4446 /**
4447 * Cancel mouse down events.
4448 *
4449 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4450 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4451 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4452 * parent widget.
4453 *
4454 * @static
4455 * @inheritable
4456 * @property {boolean}
4457 */
4458 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4459
4460 /* Events */
4461
4462 /**
4463 * A 'click' event is emitted when the button element is clicked.
4464 *
4465 * @event click
4466 */
4467
4468 /* Methods */
4469
4470 /**
4471 * Set the button element.
4472 *
4473 * This method is used to retarget a button mixin so that its functionality applies to
4474 * the specified button element instead of the one created by the class. If a button element
4475 * is already set, the method will remove the mixin’s effect on that element.
4476 *
4477 * @param {jQuery} $button Element to use as button
4478 */
4479 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4480 if ( this.$button ) {
4481 this.$button
4482 .removeClass( 'oo-ui-buttonElement-button' )
4483 .removeAttr( 'role accesskey' )
4484 .off( {
4485 mousedown: this.onMouseDownHandler,
4486 keydown: this.onKeyDownHandler,
4487 click: this.onClickHandler,
4488 keypress: this.onKeyPressHandler
4489 } );
4490 }
4491
4492 this.$button = $button
4493 .addClass( 'oo-ui-buttonElement-button' )
4494 .attr( { role: 'button' } )
4495 .on( {
4496 mousedown: this.onMouseDownHandler,
4497 keydown: this.onKeyDownHandler,
4498 click: this.onClickHandler,
4499 keypress: this.onKeyPressHandler
4500 } );
4501 };
4502
4503 /**
4504 * Handles mouse down events.
4505 *
4506 * @protected
4507 * @param {jQuery.Event} e Mouse down event
4508 */
4509 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4510 if ( this.isDisabled() || e.which !== 1 ) {
4511 return;
4512 }
4513 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4514 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4515 // reliably remove the pressed class
4516 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4517 // Prevent change of focus unless specifically configured otherwise
4518 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4519 return false;
4520 }
4521 };
4522
4523 /**
4524 * Handles mouse up events.
4525 *
4526 * @protected
4527 * @param {jQuery.Event} e Mouse up event
4528 */
4529 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4530 if ( this.isDisabled() || e.which !== 1 ) {
4531 return;
4532 }
4533 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4534 // Stop listening for mouseup, since we only needed this once
4535 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4536 };
4537
4538 /**
4539 * Handles mouse click events.
4540 *
4541 * @protected
4542 * @param {jQuery.Event} e Mouse click event
4543 * @fires click
4544 */
4545 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4546 if ( !this.isDisabled() && e.which === 1 ) {
4547 if ( this.emit( 'click' ) ) {
4548 return false;
4549 }
4550 }
4551 };
4552
4553 /**
4554 * Handles key down events.
4555 *
4556 * @protected
4557 * @param {jQuery.Event} e Key down event
4558 */
4559 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4560 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4561 return;
4562 }
4563 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4564 // Run the keyup handler no matter where the key is when the button is let go, so we can
4565 // reliably remove the pressed class
4566 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4567 };
4568
4569 /**
4570 * Handles key up events.
4571 *
4572 * @protected
4573 * @param {jQuery.Event} e Key up event
4574 */
4575 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4576 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4577 return;
4578 }
4579 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4580 // Stop listening for keyup, since we only needed this once
4581 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4582 };
4583
4584 /**
4585 * Handles key press events.
4586 *
4587 * @protected
4588 * @param {jQuery.Event} e Key press event
4589 * @fires click
4590 */
4591 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4592 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4593 if ( this.emit( 'click' ) ) {
4594 return false;
4595 }
4596 }
4597 };
4598
4599 /**
4600 * Check if button has a frame.
4601 *
4602 * @return {boolean} Button is framed
4603 */
4604 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4605 return this.framed;
4606 };
4607
4608 /**
4609 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4610 *
4611 * @param {boolean} [framed] Make button framed, omit to toggle
4612 * @chainable
4613 */
4614 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4615 framed = framed === undefined ? !this.framed : !!framed;
4616 if ( framed !== this.framed ) {
4617 this.framed = framed;
4618 this.$element
4619 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4620 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4621 this.updateThemeClasses();
4622 }
4623
4624 return this;
4625 };
4626
4627 /**
4628 * Set the button to its 'active' state.
4629 *
4630 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4631 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4632 * for other button types.
4633 *
4634 * @param {boolean} [value] Make button active
4635 * @chainable
4636 */
4637 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4638 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4639 return this;
4640 };
4641
4642 /**
4643 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4644 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4645 * items from the group is done through the interface the class provides.
4646 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4647 *
4648 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4649 *
4650 * @abstract
4651 * @class
4652 *
4653 * @constructor
4654 * @param {Object} [config] Configuration options
4655 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4656 * is omitted, the group element will use a generated `<div>`.
4657 */
4658 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4659 // Configuration initialization
4660 config = config || {};
4661
4662 // Properties
4663 this.$group = null;
4664 this.items = [];
4665 this.aggregateItemEvents = {};
4666
4667 // Initialization
4668 this.setGroupElement( config.$group || $( '<div>' ) );
4669 };
4670
4671 /* Methods */
4672
4673 /**
4674 * Set the group element.
4675 *
4676 * If an element is already set, items will be moved to the new element.
4677 *
4678 * @param {jQuery} $group Element to use as group
4679 */
4680 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4681 var i, len;
4682
4683 this.$group = $group;
4684 for ( i = 0, len = this.items.length; i < len; i++ ) {
4685 this.$group.append( this.items[ i ].$element );
4686 }
4687 };
4688
4689 /**
4690 * Check if a group contains no items.
4691 *
4692 * @return {boolean} Group is empty
4693 */
4694 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4695 return !this.items.length;
4696 };
4697
4698 /**
4699 * Get all items in the group.
4700 *
4701 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4702 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4703 * from a group).
4704 *
4705 * @return {OO.ui.Element[]} An array of items.
4706 */
4707 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4708 return this.items.slice( 0 );
4709 };
4710
4711 /**
4712 * Get an item by its data.
4713 *
4714 * Only the first item with matching data will be returned. To return all matching items,
4715 * use the #getItemsFromData method.
4716 *
4717 * @param {Object} data Item data to search for
4718 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4719 */
4720 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4721 var i, len, item,
4722 hash = OO.getHash( data );
4723
4724 for ( i = 0, len = this.items.length; i < len; i++ ) {
4725 item = this.items[ i ];
4726 if ( hash === OO.getHash( item.getData() ) ) {
4727 return item;
4728 }
4729 }
4730
4731 return null;
4732 };
4733
4734 /**
4735 * Get items by their data.
4736 *
4737 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4738 *
4739 * @param {Object} data Item data to search for
4740 * @return {OO.ui.Element[]} Items with equivalent data
4741 */
4742 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4743 var i, len, item,
4744 hash = OO.getHash( data ),
4745 items = [];
4746
4747 for ( i = 0, len = this.items.length; i < len; i++ ) {
4748 item = this.items[ i ];
4749 if ( hash === OO.getHash( item.getData() ) ) {
4750 items.push( item );
4751 }
4752 }
4753
4754 return items;
4755 };
4756
4757 /**
4758 * Aggregate the events emitted by the group.
4759 *
4760 * When events are aggregated, the group will listen to all contained items for the event,
4761 * and then emit the event under a new name. The new event will contain an additional leading
4762 * parameter containing the item that emitted the original event. Other arguments emitted from
4763 * the original event are passed through.
4764 *
4765 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4766 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4767 * A `null` value will remove aggregated events.
4768
4769 * @throws {Error} An error is thrown if aggregation already exists.
4770 */
4771 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4772 var i, len, item, add, remove, itemEvent, groupEvent;
4773
4774 for ( itemEvent in events ) {
4775 groupEvent = events[ itemEvent ];
4776
4777 // Remove existing aggregated event
4778 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4779 // Don't allow duplicate aggregations
4780 if ( groupEvent ) {
4781 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4782 }
4783 // Remove event aggregation from existing items
4784 for ( i = 0, len = this.items.length; i < len; i++ ) {
4785 item = this.items[ i ];
4786 if ( item.connect && item.disconnect ) {
4787 remove = {};
4788 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4789 item.disconnect( this, remove );
4790 }
4791 }
4792 // Prevent future items from aggregating event
4793 delete this.aggregateItemEvents[ itemEvent ];
4794 }
4795
4796 // Add new aggregate event
4797 if ( groupEvent ) {
4798 // Make future items aggregate event
4799 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4800 // Add event aggregation to existing items
4801 for ( i = 0, len = this.items.length; i < len; i++ ) {
4802 item = this.items[ i ];
4803 if ( item.connect && item.disconnect ) {
4804 add = {};
4805 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4806 item.connect( this, add );
4807 }
4808 }
4809 }
4810 }
4811 };
4812
4813 /**
4814 * Add items to the group.
4815 *
4816 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4817 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4818 *
4819 * @param {OO.ui.Element[]} items An array of items to add to the group
4820 * @param {number} [index] Index of the insertion point
4821 * @chainable
4822 */
4823 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4824 var i, len, item, event, events, currentIndex,
4825 itemElements = [];
4826
4827 for ( i = 0, len = items.length; i < len; i++ ) {
4828 item = items[ i ];
4829
4830 // Check if item exists then remove it first, effectively "moving" it
4831 currentIndex = this.items.indexOf( item );
4832 if ( currentIndex >= 0 ) {
4833 this.removeItems( [ item ] );
4834 // Adjust index to compensate for removal
4835 if ( currentIndex < index ) {
4836 index--;
4837 }
4838 }
4839 // Add the item
4840 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4841 events = {};
4842 for ( event in this.aggregateItemEvents ) {
4843 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4844 }
4845 item.connect( this, events );
4846 }
4847 item.setElementGroup( this );
4848 itemElements.push( item.$element.get( 0 ) );
4849 }
4850
4851 if ( index === undefined || index < 0 || index >= this.items.length ) {
4852 this.$group.append( itemElements );
4853 this.items.push.apply( this.items, items );
4854 } else if ( index === 0 ) {
4855 this.$group.prepend( itemElements );
4856 this.items.unshift.apply( this.items, items );
4857 } else {
4858 this.items[ index ].$element.before( itemElements );
4859 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4860 }
4861
4862 return this;
4863 };
4864
4865 /**
4866 * Remove the specified items from a group.
4867 *
4868 * Removed items are detached (not removed) from the DOM so that they may be reused.
4869 * To remove all items from a group, you may wish to use the #clearItems method instead.
4870 *
4871 * @param {OO.ui.Element[]} items An array of items to remove
4872 * @chainable
4873 */
4874 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4875 var i, len, item, index, remove, itemEvent;
4876
4877 // Remove specific items
4878 for ( i = 0, len = items.length; i < len; i++ ) {
4879 item = items[ i ];
4880 index = this.items.indexOf( item );
4881 if ( index !== -1 ) {
4882 if (
4883 item.connect && item.disconnect &&
4884 !$.isEmptyObject( this.aggregateItemEvents )
4885 ) {
4886 remove = {};
4887 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4888 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4889 }
4890 item.disconnect( this, remove );
4891 }
4892 item.setElementGroup( null );
4893 this.items.splice( index, 1 );
4894 item.$element.detach();
4895 }
4896 }
4897
4898 return this;
4899 };
4900
4901 /**
4902 * Clear all items from the group.
4903 *
4904 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4905 * To remove only a subset of items from a group, use the #removeItems method.
4906 *
4907 * @chainable
4908 */
4909 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4910 var i, len, item, remove, itemEvent;
4911
4912 // Remove all items
4913 for ( i = 0, len = this.items.length; i < len; i++ ) {
4914 item = this.items[ i ];
4915 if (
4916 item.connect && item.disconnect &&
4917 !$.isEmptyObject( this.aggregateItemEvents )
4918 ) {
4919 remove = {};
4920 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4921 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4922 }
4923 item.disconnect( this, remove );
4924 }
4925 item.setElementGroup( null );
4926 item.$element.detach();
4927 }
4928
4929 this.items = [];
4930 return this;
4931 };
4932
4933 /**
4934 * DraggableElement is a mixin class used to create elements that can be clicked
4935 * and dragged by a mouse to a new position within a group. This class must be used
4936 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4937 * the draggable elements.
4938 *
4939 * @abstract
4940 * @class
4941 *
4942 * @constructor
4943 */
4944 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4945 // Properties
4946 this.index = null;
4947
4948 // Initialize and events
4949 this.$element
4950 .attr( 'draggable', true )
4951 .addClass( 'oo-ui-draggableElement' )
4952 .on( {
4953 dragstart: this.onDragStart.bind( this ),
4954 dragover: this.onDragOver.bind( this ),
4955 dragend: this.onDragEnd.bind( this ),
4956 drop: this.onDrop.bind( this )
4957 } );
4958 };
4959
4960 OO.initClass( OO.ui.mixin.DraggableElement );
4961
4962 /* Events */
4963
4964 /**
4965 * @event dragstart
4966 *
4967 * A dragstart event is emitted when the user clicks and begins dragging an item.
4968 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4969 */
4970
4971 /**
4972 * @event dragend
4973 * A dragend event is emitted when the user drags an item and releases the mouse,
4974 * thus terminating the drag operation.
4975 */
4976
4977 /**
4978 * @event drop
4979 * A drop event is emitted when the user drags an item and then releases the mouse button
4980 * over a valid target.
4981 */
4982
4983 /* Static Properties */
4984
4985 /**
4986 * @inheritdoc OO.ui.mixin.ButtonElement
4987 */
4988 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4989
4990 /* Methods */
4991
4992 /**
4993 * Respond to dragstart event.
4994 *
4995 * @private
4996 * @param {jQuery.Event} event jQuery event
4997 * @fires dragstart
4998 */
4999 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5000 var dataTransfer = e.originalEvent.dataTransfer;
5001 // Define drop effect
5002 dataTransfer.dropEffect = 'none';
5003 dataTransfer.effectAllowed = 'move';
5004 // Support: Firefox
5005 // We must set up a dataTransfer data property or Firefox seems to
5006 // ignore the fact the element is draggable.
5007 try {
5008 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5009 } catch ( err ) {
5010 // The above is only for Firefox. Move on if it fails.
5011 }
5012 // Add dragging class
5013 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5014 // Emit event
5015 this.emit( 'dragstart', this );
5016 return true;
5017 };
5018
5019 /**
5020 * Respond to dragend event.
5021 *
5022 * @private
5023 * @fires dragend
5024 */
5025 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5026 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5027 this.emit( 'dragend' );
5028 };
5029
5030 /**
5031 * Handle drop event.
5032 *
5033 * @private
5034 * @param {jQuery.Event} event jQuery event
5035 * @fires drop
5036 */
5037 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5038 e.preventDefault();
5039 this.emit( 'drop', e );
5040 };
5041
5042 /**
5043 * In order for drag/drop to work, the dragover event must
5044 * return false and stop propogation.
5045 *
5046 * @private
5047 */
5048 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5049 e.preventDefault();
5050 };
5051
5052 /**
5053 * Set item index.
5054 * Store it in the DOM so we can access from the widget drag event
5055 *
5056 * @private
5057 * @param {number} Item index
5058 */
5059 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5060 if ( this.index !== index ) {
5061 this.index = index;
5062 this.$element.data( 'index', index );
5063 }
5064 };
5065
5066 /**
5067 * Get item index
5068 *
5069 * @private
5070 * @return {number} Item index
5071 */
5072 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5073 return this.index;
5074 };
5075
5076 /**
5077 * DraggableGroupElement is a mixin class used to create a group element to
5078 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5079 * The class is used with OO.ui.mixin.DraggableElement.
5080 *
5081 * @abstract
5082 * @class
5083 * @mixins OO.ui.mixin.GroupElement
5084 *
5085 * @constructor
5086 * @param {Object} [config] Configuration options
5087 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5088 * should match the layout of the items. Items displayed in a single row
5089 * or in several rows should use horizontal orientation. The vertical orientation should only be
5090 * used when the items are displayed in a single column. Defaults to 'vertical'
5091 */
5092 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5093 // Configuration initialization
5094 config = config || {};
5095
5096 // Parent constructor
5097 OO.ui.mixin.GroupElement.call( this, config );
5098
5099 // Properties
5100 this.orientation = config.orientation || 'vertical';
5101 this.dragItem = null;
5102 this.itemDragOver = null;
5103 this.itemKeys = {};
5104 this.sideInsertion = '';
5105
5106 // Events
5107 this.aggregate( {
5108 dragstart: 'itemDragStart',
5109 dragend: 'itemDragEnd',
5110 drop: 'itemDrop'
5111 } );
5112 this.connect( this, {
5113 itemDragStart: 'onItemDragStart',
5114 itemDrop: 'onItemDrop',
5115 itemDragEnd: 'onItemDragEnd'
5116 } );
5117 this.$element.on( {
5118 dragover: this.onDragOver.bind( this ),
5119 dragleave: this.onDragLeave.bind( this )
5120 } );
5121
5122 // Initialize
5123 if ( Array.isArray( config.items ) ) {
5124 this.addItems( config.items );
5125 }
5126 this.$placeholder = $( '<div>' )
5127 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5128 this.$element
5129 .addClass( 'oo-ui-draggableGroupElement' )
5130 .append( this.$status )
5131 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5132 .prepend( this.$placeholder );
5133 };
5134
5135 /* Setup */
5136 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5137
5138 /* Events */
5139
5140 /**
5141 * A 'reorder' event is emitted when the order of items in the group changes.
5142 *
5143 * @event reorder
5144 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5145 * @param {number} [newIndex] New index for the item
5146 */
5147
5148 /* Methods */
5149
5150 /**
5151 * Respond to item drag start event
5152 *
5153 * @private
5154 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5155 */
5156 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5157 var i, len;
5158
5159 // Map the index of each object
5160 for ( i = 0, len = this.items.length; i < len; i++ ) {
5161 this.items[ i ].setIndex( i );
5162 }
5163
5164 if ( this.orientation === 'horizontal' ) {
5165 // Set the height of the indicator
5166 this.$placeholder.css( {
5167 height: item.$element.outerHeight(),
5168 width: 2
5169 } );
5170 } else {
5171 // Set the width of the indicator
5172 this.$placeholder.css( {
5173 height: 2,
5174 width: item.$element.outerWidth()
5175 } );
5176 }
5177 this.setDragItem( item );
5178 };
5179
5180 /**
5181 * Respond to item drag end event
5182 *
5183 * @private
5184 */
5185 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5186 this.unsetDragItem();
5187 return false;
5188 };
5189
5190 /**
5191 * Handle drop event and switch the order of the items accordingly
5192 *
5193 * @private
5194 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5195 * @fires reorder
5196 */
5197 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5198 var toIndex = item.getIndex();
5199 // Check if the dropped item is from the current group
5200 // TODO: Figure out a way to configure a list of legally droppable
5201 // elements even if they are not yet in the list
5202 if ( this.getDragItem() ) {
5203 // If the insertion point is 'after', the insertion index
5204 // is shifted to the right (or to the left in RTL, hence 'after')
5205 if ( this.sideInsertion === 'after' ) {
5206 toIndex++;
5207 }
5208 // Emit change event
5209 this.emit( 'reorder', this.getDragItem(), toIndex );
5210 }
5211 this.unsetDragItem();
5212 // Return false to prevent propogation
5213 return false;
5214 };
5215
5216 /**
5217 * Handle dragleave event.
5218 *
5219 * @private
5220 */
5221 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5222 // This means the item was dragged outside the widget
5223 this.$placeholder
5224 .css( 'left', 0 )
5225 .addClass( 'oo-ui-element-hidden' );
5226 };
5227
5228 /**
5229 * Respond to dragover event
5230 *
5231 * @private
5232 * @param {jQuery.Event} event Event details
5233 */
5234 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5235 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5236 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5237 clientX = e.originalEvent.clientX,
5238 clientY = e.originalEvent.clientY;
5239
5240 // Get the OptionWidget item we are dragging over
5241 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5242 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5243 if ( $optionWidget[ 0 ] ) {
5244 itemOffset = $optionWidget.offset();
5245 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5246 itemPosition = $optionWidget.position();
5247 itemIndex = $optionWidget.data( 'index' );
5248 }
5249
5250 if (
5251 itemOffset &&
5252 this.isDragging() &&
5253 itemIndex !== this.getDragItem().getIndex()
5254 ) {
5255 if ( this.orientation === 'horizontal' ) {
5256 // Calculate where the mouse is relative to the item width
5257 itemSize = itemBoundingRect.width;
5258 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5259 dragPosition = clientX;
5260 // Which side of the item we hover over will dictate
5261 // where the placeholder will appear, on the left or
5262 // on the right
5263 cssOutput = {
5264 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5265 top: itemPosition.top
5266 };
5267 } else {
5268 // Calculate where the mouse is relative to the item height
5269 itemSize = itemBoundingRect.height;
5270 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5271 dragPosition = clientY;
5272 // Which side of the item we hover over will dictate
5273 // where the placeholder will appear, on the top or
5274 // on the bottom
5275 cssOutput = {
5276 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5277 left: itemPosition.left
5278 };
5279 }
5280 // Store whether we are before or after an item to rearrange
5281 // For horizontal layout, we need to account for RTL, as this is flipped
5282 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5283 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5284 } else {
5285 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5286 }
5287 // Add drop indicator between objects
5288 this.$placeholder
5289 .css( cssOutput )
5290 .removeClass( 'oo-ui-element-hidden' );
5291 } else {
5292 // This means the item was dragged outside the widget
5293 this.$placeholder
5294 .css( 'left', 0 )
5295 .addClass( 'oo-ui-element-hidden' );
5296 }
5297 // Prevent default
5298 e.preventDefault();
5299 };
5300
5301 /**
5302 * Set a dragged item
5303 *
5304 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5305 */
5306 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5307 this.dragItem = item;
5308 };
5309
5310 /**
5311 * Unset the current dragged item
5312 */
5313 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5314 this.dragItem = null;
5315 this.itemDragOver = null;
5316 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5317 this.sideInsertion = '';
5318 };
5319
5320 /**
5321 * Get the item that is currently being dragged.
5322 *
5323 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5324 */
5325 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5326 return this.dragItem;
5327 };
5328
5329 /**
5330 * Check if an item in the group is currently being dragged.
5331 *
5332 * @return {Boolean} Item is being dragged
5333 */
5334 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5335 return this.getDragItem() !== null;
5336 };
5337
5338 /**
5339 * IconElement is often mixed into other classes to generate an icon.
5340 * Icons are graphics, about the size of normal text. They are used to aid the user
5341 * in locating a control or to convey information in a space-efficient way. See the
5342 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5343 * included in the library.
5344 *
5345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5346 *
5347 * @abstract
5348 * @class
5349 *
5350 * @constructor
5351 * @param {Object} [config] Configuration options
5352 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5353 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5354 * the icon element be set to an existing icon instead of the one generated by this class, set a
5355 * value using a jQuery selection. For example:
5356 *
5357 * // Use a <div> tag instead of a <span>
5358 * $icon: $("<div>")
5359 * // Use an existing icon element instead of the one generated by the class
5360 * $icon: this.$element
5361 * // Use an icon element from a child widget
5362 * $icon: this.childwidget.$element
5363 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5364 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5365 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5366 * by the user's language.
5367 *
5368 * Example of an i18n map:
5369 *
5370 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5371 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5372 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5373 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5374 * text. The icon title is displayed when users move the mouse over the icon.
5375 */
5376 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5377 // Configuration initialization
5378 config = config || {};
5379
5380 // Properties
5381 this.$icon = null;
5382 this.icon = null;
5383 this.iconTitle = null;
5384
5385 // Initialization
5386 this.setIcon( config.icon || this.constructor.static.icon );
5387 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5388 this.setIconElement( config.$icon || $( '<span>' ) );
5389 };
5390
5391 /* Setup */
5392
5393 OO.initClass( OO.ui.mixin.IconElement );
5394
5395 /* Static Properties */
5396
5397 /**
5398 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5399 * for i18n purposes and contains a `default` icon name and additional names keyed by
5400 * language code. The `default` name is used when no icon is keyed by the user's language.
5401 *
5402 * Example of an i18n map:
5403 *
5404 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5405 *
5406 * Note: the static property will be overridden if the #icon configuration is used.
5407 *
5408 * @static
5409 * @inheritable
5410 * @property {Object|string}
5411 */
5412 OO.ui.mixin.IconElement.static.icon = null;
5413
5414 /**
5415 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5416 * function that returns title text, or `null` for no title.
5417 *
5418 * The static property will be overridden if the #iconTitle configuration is used.
5419 *
5420 * @static
5421 * @inheritable
5422 * @property {string|Function|null}
5423 */
5424 OO.ui.mixin.IconElement.static.iconTitle = null;
5425
5426 /* Methods */
5427
5428 /**
5429 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5430 * applies to the specified icon element instead of the one created by the class. If an icon
5431 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5432 * and mixin methods will no longer affect the element.
5433 *
5434 * @param {jQuery} $icon Element to use as icon
5435 */
5436 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5437 if ( this.$icon ) {
5438 this.$icon
5439 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5440 .removeAttr( 'title' );
5441 }
5442
5443 this.$icon = $icon
5444 .addClass( 'oo-ui-iconElement-icon' )
5445 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5446 if ( this.iconTitle !== null ) {
5447 this.$icon.attr( 'title', this.iconTitle );
5448 }
5449
5450 this.updateThemeClasses();
5451 };
5452
5453 /**
5454 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5455 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5456 * for an example.
5457 *
5458 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5459 * by language code, or `null` to remove the icon.
5460 * @chainable
5461 */
5462 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5463 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5464 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5465
5466 if ( this.icon !== icon ) {
5467 if ( this.$icon ) {
5468 if ( this.icon !== null ) {
5469 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5470 }
5471 if ( icon !== null ) {
5472 this.$icon.addClass( 'oo-ui-icon-' + icon );
5473 }
5474 }
5475 this.icon = icon;
5476 }
5477
5478 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5479 this.updateThemeClasses();
5480
5481 return this;
5482 };
5483
5484 /**
5485 * Set the icon title. Use `null` to remove the title.
5486 *
5487 * @param {string|Function|null} iconTitle A text string used as the icon title,
5488 * a function that returns title text, or `null` for no title.
5489 * @chainable
5490 */
5491 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5492 iconTitle = typeof iconTitle === 'function' ||
5493 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5494 OO.ui.resolveMsg( iconTitle ) : null;
5495
5496 if ( this.iconTitle !== iconTitle ) {
5497 this.iconTitle = iconTitle;
5498 if ( this.$icon ) {
5499 if ( this.iconTitle !== null ) {
5500 this.$icon.attr( 'title', iconTitle );
5501 } else {
5502 this.$icon.removeAttr( 'title' );
5503 }
5504 }
5505 }
5506
5507 return this;
5508 };
5509
5510 /**
5511 * Get the symbolic name of the icon.
5512 *
5513 * @return {string} Icon name
5514 */
5515 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5516 return this.icon;
5517 };
5518
5519 /**
5520 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5521 *
5522 * @return {string} Icon title text
5523 */
5524 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5525 return this.iconTitle;
5526 };
5527
5528 /**
5529 * IndicatorElement is often mixed into other classes to generate an indicator.
5530 * Indicators are small graphics that are generally used in two ways:
5531 *
5532 * - To draw attention to the status of an item. For example, an indicator might be
5533 * used to show that an item in a list has errors that need to be resolved.
5534 * - To clarify the function of a control that acts in an exceptional way (a button
5535 * that opens a menu instead of performing an action directly, for example).
5536 *
5537 * For a list of indicators included in the library, please see the
5538 * [OOjs UI documentation on MediaWiki] [1].
5539 *
5540 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5541 *
5542 * @abstract
5543 * @class
5544 *
5545 * @constructor
5546 * @param {Object} [config] Configuration options
5547 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5548 * configuration is omitted, the indicator element will use a generated `<span>`.
5549 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5550 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5551 * in the library.
5552 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5553 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5554 * or a function that returns title text. The indicator title is displayed when users move
5555 * the mouse over the indicator.
5556 */
5557 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5558 // Configuration initialization
5559 config = config || {};
5560
5561 // Properties
5562 this.$indicator = null;
5563 this.indicator = null;
5564 this.indicatorTitle = null;
5565
5566 // Initialization
5567 this.setIndicator( config.indicator || this.constructor.static.indicator );
5568 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5569 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5570 };
5571
5572 /* Setup */
5573
5574 OO.initClass( OO.ui.mixin.IndicatorElement );
5575
5576 /* Static Properties */
5577
5578 /**
5579 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5580 * The static property will be overridden if the #indicator configuration is used.
5581 *
5582 * @static
5583 * @inheritable
5584 * @property {string|null}
5585 */
5586 OO.ui.mixin.IndicatorElement.static.indicator = null;
5587
5588 /**
5589 * A text string used as the indicator title, a function that returns title text, or `null`
5590 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5591 *
5592 * @static
5593 * @inheritable
5594 * @property {string|Function|null}
5595 */
5596 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5597
5598 /* Methods */
5599
5600 /**
5601 * Set the indicator element.
5602 *
5603 * If an element is already set, it will be cleaned up before setting up the new element.
5604 *
5605 * @param {jQuery} $indicator Element to use as indicator
5606 */
5607 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5608 if ( this.$indicator ) {
5609 this.$indicator
5610 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5611 .removeAttr( 'title' );
5612 }
5613
5614 this.$indicator = $indicator
5615 .addClass( 'oo-ui-indicatorElement-indicator' )
5616 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5617 if ( this.indicatorTitle !== null ) {
5618 this.$indicator.attr( 'title', this.indicatorTitle );
5619 }
5620
5621 this.updateThemeClasses();
5622 };
5623
5624 /**
5625 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5626 *
5627 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5628 * @chainable
5629 */
5630 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5631 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5632
5633 if ( this.indicator !== indicator ) {
5634 if ( this.$indicator ) {
5635 if ( this.indicator !== null ) {
5636 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5637 }
5638 if ( indicator !== null ) {
5639 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5640 }
5641 }
5642 this.indicator = indicator;
5643 }
5644
5645 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5646 this.updateThemeClasses();
5647
5648 return this;
5649 };
5650
5651 /**
5652 * Set the indicator title.
5653 *
5654 * The title is displayed when a user moves the mouse over the indicator.
5655 *
5656 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5657 * `null` for no indicator title
5658 * @chainable
5659 */
5660 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5661 indicatorTitle = typeof indicatorTitle === 'function' ||
5662 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5663 OO.ui.resolveMsg( indicatorTitle ) : null;
5664
5665 if ( this.indicatorTitle !== indicatorTitle ) {
5666 this.indicatorTitle = indicatorTitle;
5667 if ( this.$indicator ) {
5668 if ( this.indicatorTitle !== null ) {
5669 this.$indicator.attr( 'title', indicatorTitle );
5670 } else {
5671 this.$indicator.removeAttr( 'title' );
5672 }
5673 }
5674 }
5675
5676 return this;
5677 };
5678
5679 /**
5680 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5681 *
5682 * @return {string} Symbolic name of indicator
5683 */
5684 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5685 return this.indicator;
5686 };
5687
5688 /**
5689 * Get the indicator title.
5690 *
5691 * The title is displayed when a user moves the mouse over the indicator.
5692 *
5693 * @return {string} Indicator title text
5694 */
5695 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5696 return this.indicatorTitle;
5697 };
5698
5699 /**
5700 * LabelElement is often mixed into other classes to generate a label, which
5701 * helps identify the function of an interface element.
5702 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5703 *
5704 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5705 *
5706 * @abstract
5707 * @class
5708 *
5709 * @constructor
5710 * @param {Object} [config] Configuration options
5711 * @cfg {jQuery} [$label] The label element created by the class. If this
5712 * configuration is omitted, the label element will use a generated `<span>`.
5713 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5714 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5715 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5716 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5717 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5718 * The label will be truncated to fit if necessary.
5719 */
5720 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5721 // Configuration initialization
5722 config = config || {};
5723
5724 // Properties
5725 this.$label = null;
5726 this.label = null;
5727 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5728
5729 // Initialization
5730 this.setLabel( config.label || this.constructor.static.label );
5731 this.setLabelElement( config.$label || $( '<span>' ) );
5732 };
5733
5734 /* Setup */
5735
5736 OO.initClass( OO.ui.mixin.LabelElement );
5737
5738 /* Events */
5739
5740 /**
5741 * @event labelChange
5742 * @param {string} value
5743 */
5744
5745 /* Static Properties */
5746
5747 /**
5748 * The label text. The label can be specified as a plaintext string, a function that will
5749 * produce a string in the future, or `null` for no label. The static value will
5750 * be overridden if a label is specified with the #label config option.
5751 *
5752 * @static
5753 * @inheritable
5754 * @property {string|Function|null}
5755 */
5756 OO.ui.mixin.LabelElement.static.label = null;
5757
5758 /* Methods */
5759
5760 /**
5761 * Set the label element.
5762 *
5763 * If an element is already set, it will be cleaned up before setting up the new element.
5764 *
5765 * @param {jQuery} $label Element to use as label
5766 */
5767 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5768 if ( this.$label ) {
5769 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5770 }
5771
5772 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5773 this.setLabelContent( this.label );
5774 };
5775
5776 /**
5777 * Set the label.
5778 *
5779 * An empty string will result in the label being hidden. A string containing only whitespace will
5780 * be converted to a single `&nbsp;`.
5781 *
5782 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5783 * text; or null for no label
5784 * @chainable
5785 */
5786 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5787 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5788 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5789
5790 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5791
5792 if ( this.label !== label ) {
5793 if ( this.$label ) {
5794 this.setLabelContent( label );
5795 }
5796 this.label = label;
5797 this.emit( 'labelChange' );
5798 }
5799
5800 return this;
5801 };
5802
5803 /**
5804 * Get the label.
5805 *
5806 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5807 * text; or null for no label
5808 */
5809 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5810 return this.label;
5811 };
5812
5813 /**
5814 * Fit the label.
5815 *
5816 * @chainable
5817 */
5818 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5819 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5820 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5821 }
5822
5823 return this;
5824 };
5825
5826 /**
5827 * Set the content of the label.
5828 *
5829 * Do not call this method until after the label element has been set by #setLabelElement.
5830 *
5831 * @private
5832 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5833 * text; or null for no label
5834 */
5835 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5836 if ( typeof label === 'string' ) {
5837 if ( label.match( /^\s*$/ ) ) {
5838 // Convert whitespace only string to a single non-breaking space
5839 this.$label.html( '&nbsp;' );
5840 } else {
5841 this.$label.text( label );
5842 }
5843 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5844 this.$label.html( label.toString() );
5845 } else if ( label instanceof jQuery ) {
5846 this.$label.empty().append( label );
5847 } else {
5848 this.$label.empty();
5849 }
5850 };
5851
5852 /**
5853 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5854 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5855 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5856 * from the lookup menu, that value becomes the value of the input field.
5857 *
5858 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5859 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5860 * re-enable lookups.
5861 *
5862 * See the [OOjs UI demos][1] for an example.
5863 *
5864 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5865 *
5866 * @class
5867 * @abstract
5868 *
5869 * @constructor
5870 * @param {Object} [config] Configuration options
5871 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5872 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5873 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5874 * By default, the lookup menu is not generated and displayed until the user begins to type.
5875 */
5876 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5877 // Configuration initialization
5878 config = config || {};
5879
5880 // Properties
5881 this.$overlay = config.$overlay || this.$element;
5882 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5883 widget: this,
5884 input: this,
5885 $container: config.$container || this.$element
5886 } );
5887
5888 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5889
5890 this.lookupCache = {};
5891 this.lookupQuery = null;
5892 this.lookupRequest = null;
5893 this.lookupsDisabled = false;
5894 this.lookupInputFocused = false;
5895
5896 // Events
5897 this.$input.on( {
5898 focus: this.onLookupInputFocus.bind( this ),
5899 blur: this.onLookupInputBlur.bind( this ),
5900 mousedown: this.onLookupInputMouseDown.bind( this )
5901 } );
5902 this.connect( this, { change: 'onLookupInputChange' } );
5903 this.lookupMenu.connect( this, {
5904 toggle: 'onLookupMenuToggle',
5905 choose: 'onLookupMenuItemChoose'
5906 } );
5907
5908 // Initialization
5909 this.$element.addClass( 'oo-ui-lookupElement' );
5910 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5911 this.$overlay.append( this.lookupMenu.$element );
5912 };
5913
5914 /* Methods */
5915
5916 /**
5917 * Handle input focus event.
5918 *
5919 * @protected
5920 * @param {jQuery.Event} e Input focus event
5921 */
5922 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5923 this.lookupInputFocused = true;
5924 this.populateLookupMenu();
5925 };
5926
5927 /**
5928 * Handle input blur event.
5929 *
5930 * @protected
5931 * @param {jQuery.Event} e Input blur event
5932 */
5933 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5934 this.closeLookupMenu();
5935 this.lookupInputFocused = false;
5936 };
5937
5938 /**
5939 * Handle input mouse down event.
5940 *
5941 * @protected
5942 * @param {jQuery.Event} e Input mouse down event
5943 */
5944 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5945 // Only open the menu if the input was already focused.
5946 // This way we allow the user to open the menu again after closing it with Esc
5947 // by clicking in the input. Opening (and populating) the menu when initially
5948 // clicking into the input is handled by the focus handler.
5949 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5950 this.populateLookupMenu();
5951 }
5952 };
5953
5954 /**
5955 * Handle input change event.
5956 *
5957 * @protected
5958 * @param {string} value New input value
5959 */
5960 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5961 if ( this.lookupInputFocused ) {
5962 this.populateLookupMenu();
5963 }
5964 };
5965
5966 /**
5967 * Handle the lookup menu being shown/hidden.
5968 *
5969 * @protected
5970 * @param {boolean} visible Whether the lookup menu is now visible.
5971 */
5972 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5973 if ( !visible ) {
5974 // When the menu is hidden, abort any active request and clear the menu.
5975 // This has to be done here in addition to closeLookupMenu(), because
5976 // MenuSelectWidget will close itself when the user presses Esc.
5977 this.abortLookupRequest();
5978 this.lookupMenu.clearItems();
5979 }
5980 };
5981
5982 /**
5983 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5984 *
5985 * @protected
5986 * @param {OO.ui.MenuOptionWidget} item Selected item
5987 */
5988 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5989 this.setValue( item.getData() );
5990 };
5991
5992 /**
5993 * Get lookup menu.
5994 *
5995 * @private
5996 * @return {OO.ui.FloatingMenuSelectWidget}
5997 */
5998 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
5999 return this.lookupMenu;
6000 };
6001
6002 /**
6003 * Disable or re-enable lookups.
6004 *
6005 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6006 *
6007 * @param {boolean} disabled Disable lookups
6008 */
6009 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6010 this.lookupsDisabled = !!disabled;
6011 };
6012
6013 /**
6014 * Open the menu. If there are no entries in the menu, this does nothing.
6015 *
6016 * @private
6017 * @chainable
6018 */
6019 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6020 if ( !this.lookupMenu.isEmpty() ) {
6021 this.lookupMenu.toggle( true );
6022 }
6023 return this;
6024 };
6025
6026 /**
6027 * Close the menu, empty it, and abort any pending request.
6028 *
6029 * @private
6030 * @chainable
6031 */
6032 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6033 this.lookupMenu.toggle( false );
6034 this.abortLookupRequest();
6035 this.lookupMenu.clearItems();
6036 return this;
6037 };
6038
6039 /**
6040 * Request menu items based on the input's current value, and when they arrive,
6041 * populate the menu with these items and show the menu.
6042 *
6043 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6044 *
6045 * @private
6046 * @chainable
6047 */
6048 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6049 var widget = this,
6050 value = this.getValue();
6051
6052 if ( this.lookupsDisabled || this.isReadOnly() ) {
6053 return;
6054 }
6055
6056 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6057 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6058 this.closeLookupMenu();
6059 // Skip population if there is already a request pending for the current value
6060 } else if ( value !== this.lookupQuery ) {
6061 this.getLookupMenuItems()
6062 .done( function ( items ) {
6063 widget.lookupMenu.clearItems();
6064 if ( items.length ) {
6065 widget.lookupMenu
6066 .addItems( items )
6067 .toggle( true );
6068 widget.initializeLookupMenuSelection();
6069 } else {
6070 widget.lookupMenu.toggle( false );
6071 }
6072 } )
6073 .fail( function () {
6074 widget.lookupMenu.clearItems();
6075 } );
6076 }
6077
6078 return this;
6079 };
6080
6081 /**
6082 * Highlight the first selectable item in the menu.
6083 *
6084 * @private
6085 * @chainable
6086 */
6087 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6088 if ( !this.lookupMenu.getSelectedItem() ) {
6089 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6090 }
6091 };
6092
6093 /**
6094 * Get lookup menu items for the current query.
6095 *
6096 * @private
6097 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6098 * the done event. If the request was aborted to make way for a subsequent request, this promise
6099 * will not be rejected: it will remain pending forever.
6100 */
6101 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6102 var widget = this,
6103 value = this.getValue(),
6104 deferred = $.Deferred(),
6105 ourRequest;
6106
6107 this.abortLookupRequest();
6108 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6109 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6110 } else {
6111 this.pushPending();
6112 this.lookupQuery = value;
6113 ourRequest = this.lookupRequest = this.getLookupRequest();
6114 ourRequest
6115 .always( function () {
6116 // We need to pop pending even if this is an old request, otherwise
6117 // the widget will remain pending forever.
6118 // TODO: this assumes that an aborted request will fail or succeed soon after
6119 // being aborted, or at least eventually. It would be nice if we could popPending()
6120 // at abort time, but only if we knew that we hadn't already called popPending()
6121 // for that request.
6122 widget.popPending();
6123 } )
6124 .done( function ( response ) {
6125 // If this is an old request (and aborting it somehow caused it to still succeed),
6126 // ignore its success completely
6127 if ( ourRequest === widget.lookupRequest ) {
6128 widget.lookupQuery = null;
6129 widget.lookupRequest = null;
6130 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6131 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6132 }
6133 } )
6134 .fail( function () {
6135 // If this is an old request (or a request failing because it's being aborted),
6136 // ignore its failure completely
6137 if ( ourRequest === widget.lookupRequest ) {
6138 widget.lookupQuery = null;
6139 widget.lookupRequest = null;
6140 deferred.reject();
6141 }
6142 } );
6143 }
6144 return deferred.promise();
6145 };
6146
6147 /**
6148 * Abort the currently pending lookup request, if any.
6149 *
6150 * @private
6151 */
6152 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6153 var oldRequest = this.lookupRequest;
6154 if ( oldRequest ) {
6155 // First unset this.lookupRequest to the fail handler will notice
6156 // that the request is no longer current
6157 this.lookupRequest = null;
6158 this.lookupQuery = null;
6159 oldRequest.abort();
6160 }
6161 };
6162
6163 /**
6164 * Get a new request object of the current lookup query value.
6165 *
6166 * @protected
6167 * @abstract
6168 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6169 */
6170 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6171 // Stub, implemented in subclass
6172 return null;
6173 };
6174
6175 /**
6176 * Pre-process data returned by the request from #getLookupRequest.
6177 *
6178 * The return value of this function will be cached, and any further queries for the given value
6179 * will use the cache rather than doing API requests.
6180 *
6181 * @protected
6182 * @abstract
6183 * @param {Mixed} response Response from server
6184 * @return {Mixed} Cached result data
6185 */
6186 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6187 // Stub, implemented in subclass
6188 return [];
6189 };
6190
6191 /**
6192 * Get a list of menu option widgets from the (possibly cached) data returned by
6193 * #getLookupCacheDataFromResponse.
6194 *
6195 * @protected
6196 * @abstract
6197 * @param {Mixed} data Cached result data, usually an array
6198 * @return {OO.ui.MenuOptionWidget[]} Menu items
6199 */
6200 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6201 // Stub, implemented in subclass
6202 return [];
6203 };
6204
6205 /**
6206 * Set the read-only state of the widget.
6207 *
6208 * This will also disable/enable the lookups functionality.
6209 *
6210 * @param {boolean} readOnly Make input read-only
6211 * @chainable
6212 */
6213 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6214 // Parent method
6215 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6216 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6217
6218 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6219 if ( this.isReadOnly() && this.lookupMenu ) {
6220 this.closeLookupMenu();
6221 }
6222
6223 return this;
6224 };
6225
6226 /**
6227 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6228 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6229 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6230 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6231 *
6232 * @abstract
6233 * @class
6234 *
6235 * @constructor
6236 * @param {Object} [config] Configuration options
6237 * @cfg {Object} [popup] Configuration to pass to popup
6238 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6239 */
6240 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6241 // Configuration initialization
6242 config = config || {};
6243
6244 // Properties
6245 this.popup = new OO.ui.PopupWidget( $.extend(
6246 { autoClose: true },
6247 config.popup,
6248 { $autoCloseIgnore: this.$element }
6249 ) );
6250 };
6251
6252 /* Methods */
6253
6254 /**
6255 * Get popup.
6256 *
6257 * @return {OO.ui.PopupWidget} Popup widget
6258 */
6259 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6260 return this.popup;
6261 };
6262
6263 /**
6264 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6265 * additional functionality to an element created by another class. The class provides
6266 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6267 * which are used to customize the look and feel of a widget to better describe its
6268 * importance and functionality.
6269 *
6270 * The library currently contains the following styling flags for general use:
6271 *
6272 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6273 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6274 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6275 *
6276 * The flags affect the appearance of the buttons:
6277 *
6278 * @example
6279 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6280 * var button1 = new OO.ui.ButtonWidget( {
6281 * label: 'Constructive',
6282 * flags: 'constructive'
6283 * } );
6284 * var button2 = new OO.ui.ButtonWidget( {
6285 * label: 'Destructive',
6286 * flags: 'destructive'
6287 * } );
6288 * var button3 = new OO.ui.ButtonWidget( {
6289 * label: 'Progressive',
6290 * flags: 'progressive'
6291 * } );
6292 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6293 *
6294 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6295 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6296 *
6297 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6298 *
6299 * @abstract
6300 * @class
6301 *
6302 * @constructor
6303 * @param {Object} [config] Configuration options
6304 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6305 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6306 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6307 * @cfg {jQuery} [$flagged] The flagged element. By default,
6308 * the flagged functionality is applied to the element created by the class ($element).
6309 * If a different element is specified, the flagged functionality will be applied to it instead.
6310 */
6311 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6312 // Configuration initialization
6313 config = config || {};
6314
6315 // Properties
6316 this.flags = {};
6317 this.$flagged = null;
6318
6319 // Initialization
6320 this.setFlags( config.flags );
6321 this.setFlaggedElement( config.$flagged || this.$element );
6322 };
6323
6324 /* Events */
6325
6326 /**
6327 * @event flag
6328 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6329 * parameter contains the name of each modified flag and indicates whether it was
6330 * added or removed.
6331 *
6332 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6333 * that the flag was added, `false` that the flag was removed.
6334 */
6335
6336 /* Methods */
6337
6338 /**
6339 * Set the flagged element.
6340 *
6341 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6342 * If an element is already set, the method will remove the mixin’s effect on that element.
6343 *
6344 * @param {jQuery} $flagged Element that should be flagged
6345 */
6346 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6347 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6348 return 'oo-ui-flaggedElement-' + flag;
6349 } ).join( ' ' );
6350
6351 if ( this.$flagged ) {
6352 this.$flagged.removeClass( classNames );
6353 }
6354
6355 this.$flagged = $flagged.addClass( classNames );
6356 };
6357
6358 /**
6359 * Check if the specified flag is set.
6360 *
6361 * @param {string} flag Name of flag
6362 * @return {boolean} The flag is set
6363 */
6364 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6365 // This may be called before the constructor, thus before this.flags is set
6366 return this.flags && ( flag in this.flags );
6367 };
6368
6369 /**
6370 * Get the names of all flags set.
6371 *
6372 * @return {string[]} Flag names
6373 */
6374 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6375 // This may be called before the constructor, thus before this.flags is set
6376 return Object.keys( this.flags || {} );
6377 };
6378
6379 /**
6380 * Clear all flags.
6381 *
6382 * @chainable
6383 * @fires flag
6384 */
6385 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6386 var flag, className,
6387 changes = {},
6388 remove = [],
6389 classPrefix = 'oo-ui-flaggedElement-';
6390
6391 for ( flag in this.flags ) {
6392 className = classPrefix + flag;
6393 changes[ flag ] = false;
6394 delete this.flags[ flag ];
6395 remove.push( className );
6396 }
6397
6398 if ( this.$flagged ) {
6399 this.$flagged.removeClass( remove.join( ' ' ) );
6400 }
6401
6402 this.updateThemeClasses();
6403 this.emit( 'flag', changes );
6404
6405 return this;
6406 };
6407
6408 /**
6409 * Add one or more flags.
6410 *
6411 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6412 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6413 * be added (`true`) or removed (`false`).
6414 * @chainable
6415 * @fires flag
6416 */
6417 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6418 var i, len, flag, className,
6419 changes = {},
6420 add = [],
6421 remove = [],
6422 classPrefix = 'oo-ui-flaggedElement-';
6423
6424 if ( typeof flags === 'string' ) {
6425 className = classPrefix + flags;
6426 // Set
6427 if ( !this.flags[ flags ] ) {
6428 this.flags[ flags ] = true;
6429 add.push( className );
6430 }
6431 } else if ( Array.isArray( flags ) ) {
6432 for ( i = 0, len = flags.length; i < len; i++ ) {
6433 flag = flags[ i ];
6434 className = classPrefix + flag;
6435 // Set
6436 if ( !this.flags[ flag ] ) {
6437 changes[ flag ] = true;
6438 this.flags[ flag ] = true;
6439 add.push( className );
6440 }
6441 }
6442 } else if ( OO.isPlainObject( flags ) ) {
6443 for ( flag in flags ) {
6444 className = classPrefix + flag;
6445 if ( flags[ flag ] ) {
6446 // Set
6447 if ( !this.flags[ flag ] ) {
6448 changes[ flag ] = true;
6449 this.flags[ flag ] = true;
6450 add.push( className );
6451 }
6452 } else {
6453 // Remove
6454 if ( this.flags[ flag ] ) {
6455 changes[ flag ] = false;
6456 delete this.flags[ flag ];
6457 remove.push( className );
6458 }
6459 }
6460 }
6461 }
6462
6463 if ( this.$flagged ) {
6464 this.$flagged
6465 .addClass( add.join( ' ' ) )
6466 .removeClass( remove.join( ' ' ) );
6467 }
6468
6469 this.updateThemeClasses();
6470 this.emit( 'flag', changes );
6471
6472 return this;
6473 };
6474
6475 /**
6476 * TitledElement is mixed into other classes to provide a `title` attribute.
6477 * Titles are rendered by the browser and are made visible when the user moves
6478 * the mouse over the element. Titles are not visible on touch devices.
6479 *
6480 * @example
6481 * // TitledElement provides a 'title' attribute to the
6482 * // ButtonWidget class
6483 * var button = new OO.ui.ButtonWidget( {
6484 * label: 'Button with Title',
6485 * title: 'I am a button'
6486 * } );
6487 * $( 'body' ).append( button.$element );
6488 *
6489 * @abstract
6490 * @class
6491 *
6492 * @constructor
6493 * @param {Object} [config] Configuration options
6494 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6495 * If this config is omitted, the title functionality is applied to $element, the
6496 * element created by the class.
6497 * @cfg {string|Function} [title] The title text or a function that returns text. If
6498 * this config is omitted, the value of the {@link #static-title static title} property is used.
6499 */
6500 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6501 // Configuration initialization
6502 config = config || {};
6503
6504 // Properties
6505 this.$titled = null;
6506 this.title = null;
6507
6508 // Initialization
6509 this.setTitle( config.title || this.constructor.static.title );
6510 this.setTitledElement( config.$titled || this.$element );
6511 };
6512
6513 /* Setup */
6514
6515 OO.initClass( OO.ui.mixin.TitledElement );
6516
6517 /* Static Properties */
6518
6519 /**
6520 * The title text, a function that returns text, or `null` for no title. The value of the static property
6521 * is overridden if the #title config option is used.
6522 *
6523 * @static
6524 * @inheritable
6525 * @property {string|Function|null}
6526 */
6527 OO.ui.mixin.TitledElement.static.title = null;
6528
6529 /* Methods */
6530
6531 /**
6532 * Set the titled element.
6533 *
6534 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6535 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6536 *
6537 * @param {jQuery} $titled Element that should use the 'titled' functionality
6538 */
6539 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6540 if ( this.$titled ) {
6541 this.$titled.removeAttr( 'title' );
6542 }
6543
6544 this.$titled = $titled;
6545 if ( this.title ) {
6546 this.$titled.attr( 'title', this.title );
6547 }
6548 };
6549
6550 /**
6551 * Set title.
6552 *
6553 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6554 * @chainable
6555 */
6556 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6557 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6558
6559 if ( this.title !== title ) {
6560 if ( this.$titled ) {
6561 if ( title !== null ) {
6562 this.$titled.attr( 'title', title );
6563 } else {
6564 this.$titled.removeAttr( 'title' );
6565 }
6566 }
6567 this.title = title;
6568 }
6569
6570 return this;
6571 };
6572
6573 /**
6574 * Get title.
6575 *
6576 * @return {string} Title string
6577 */
6578 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6579 return this.title;
6580 };
6581
6582 /**
6583 * Element that can be automatically clipped to visible boundaries.
6584 *
6585 * Whenever the element's natural height changes, you have to call
6586 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6587 * clipping correctly.
6588 *
6589 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6590 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6591 * then #$clippable will be given a fixed reduced height and/or width and will be made
6592 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6593 * but you can build a static footer by setting #$clippableContainer to an element that contains
6594 * #$clippable and the footer.
6595 *
6596 * @abstract
6597 * @class
6598 *
6599 * @constructor
6600 * @param {Object} [config] Configuration options
6601 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6602 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6603 * omit to use #$clippable
6604 */
6605 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6606 // Configuration initialization
6607 config = config || {};
6608
6609 // Properties
6610 this.$clippable = null;
6611 this.$clippableContainer = null;
6612 this.clipping = false;
6613 this.clippedHorizontally = false;
6614 this.clippedVertically = false;
6615 this.$clippableScrollableContainer = null;
6616 this.$clippableScroller = null;
6617 this.$clippableWindow = null;
6618 this.idealWidth = null;
6619 this.idealHeight = null;
6620 this.onClippableScrollHandler = this.clip.bind( this );
6621 this.onClippableWindowResizeHandler = this.clip.bind( this );
6622
6623 // Initialization
6624 if ( config.$clippableContainer ) {
6625 this.setClippableContainer( config.$clippableContainer );
6626 }
6627 this.setClippableElement( config.$clippable || this.$element );
6628 };
6629
6630 /* Methods */
6631
6632 /**
6633 * Set clippable element.
6634 *
6635 * If an element is already set, it will be cleaned up before setting up the new element.
6636 *
6637 * @param {jQuery} $clippable Element to make clippable
6638 */
6639 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6640 if ( this.$clippable ) {
6641 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6642 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6643 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6644 }
6645
6646 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6647 this.clip();
6648 };
6649
6650 /**
6651 * Set clippable container.
6652 *
6653 * This is the container that will be measured when deciding whether to clip. When clipping,
6654 * #$clippable will be resized in order to keep the clippable container fully visible.
6655 *
6656 * If the clippable container is unset, #$clippable will be used.
6657 *
6658 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6659 */
6660 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6661 this.$clippableContainer = $clippableContainer;
6662 if ( this.$clippable ) {
6663 this.clip();
6664 }
6665 };
6666
6667 /**
6668 * Toggle clipping.
6669 *
6670 * Do not turn clipping on until after the element is attached to the DOM and visible.
6671 *
6672 * @param {boolean} [clipping] Enable clipping, omit to toggle
6673 * @chainable
6674 */
6675 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6676 clipping = clipping === undefined ? !this.clipping : !!clipping;
6677
6678 if ( this.clipping !== clipping ) {
6679 this.clipping = clipping;
6680 if ( clipping ) {
6681 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6682 // If the clippable container is the root, we have to listen to scroll events and check
6683 // jQuery.scrollTop on the window because of browser inconsistencies
6684 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6685 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6686 this.$clippableScrollableContainer;
6687 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6688 this.$clippableWindow = $( this.getElementWindow() )
6689 .on( 'resize', this.onClippableWindowResizeHandler );
6690 // Initial clip after visible
6691 this.clip();
6692 } else {
6693 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6694 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6695
6696 this.$clippableScrollableContainer = null;
6697 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6698 this.$clippableScroller = null;
6699 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6700 this.$clippableWindow = null;
6701 }
6702 }
6703
6704 return this;
6705 };
6706
6707 /**
6708 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6709 *
6710 * @return {boolean} Element will be clipped to the visible area
6711 */
6712 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6713 return this.clipping;
6714 };
6715
6716 /**
6717 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6718 *
6719 * @return {boolean} Part of the element is being clipped
6720 */
6721 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6722 return this.clippedHorizontally || this.clippedVertically;
6723 };
6724
6725 /**
6726 * Check if the right of the element is being clipped by the nearest scrollable container.
6727 *
6728 * @return {boolean} Part of the element is being clipped
6729 */
6730 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6731 return this.clippedHorizontally;
6732 };
6733
6734 /**
6735 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6736 *
6737 * @return {boolean} Part of the element is being clipped
6738 */
6739 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6740 return this.clippedVertically;
6741 };
6742
6743 /**
6744 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6745 *
6746 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6747 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6748 */
6749 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6750 this.idealWidth = width;
6751 this.idealHeight = height;
6752
6753 if ( !this.clipping ) {
6754 // Update dimensions
6755 this.$clippable.css( { width: width, height: height } );
6756 }
6757 // While clipping, idealWidth and idealHeight are not considered
6758 };
6759
6760 /**
6761 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6762 * the element's natural height changes.
6763 *
6764 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6765 * overlapped by, the visible area of the nearest scrollable container.
6766 *
6767 * @chainable
6768 */
6769 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6770 var $container, extraHeight, extraWidth, ccOffset,
6771 $scrollableContainer, scOffset, scHeight, scWidth,
6772 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6773 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6774 naturalWidth, naturalHeight, clipWidth, clipHeight,
6775 buffer = 7; // Chosen by fair dice roll
6776
6777 if ( !this.clipping ) {
6778 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6779 return this;
6780 }
6781
6782 $container = this.$clippableContainer || this.$clippable;
6783 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6784 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6785 ccOffset = $container.offset();
6786 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6787 this.$clippableWindow : this.$clippableScrollableContainer;
6788 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6789 scHeight = $scrollableContainer.innerHeight() - buffer;
6790 scWidth = $scrollableContainer.innerWidth() - buffer;
6791 ccWidth = $container.outerWidth() + buffer;
6792 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6793 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6794 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6795 desiredWidth = ccOffset.left < 0 ?
6796 ccWidth + ccOffset.left :
6797 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6798 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6799 allotedWidth = desiredWidth - extraWidth;
6800 allotedHeight = desiredHeight - extraHeight;
6801 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6802 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6803 clipWidth = allotedWidth < naturalWidth;
6804 clipHeight = allotedHeight < naturalHeight;
6805
6806 if ( clipWidth ) {
6807 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6808 } else {
6809 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6810 }
6811 if ( clipHeight ) {
6812 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6813 } else {
6814 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6815 }
6816
6817 // If we stopped clipping in at least one of the dimensions
6818 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6819 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6820 }
6821
6822 this.clippedHorizontally = clipWidth;
6823 this.clippedVertically = clipHeight;
6824
6825 return this;
6826 };
6827
6828 /**
6829 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6830 * document (for example, in a OO.ui.Window's $overlay).
6831 *
6832 * The elements's position is automatically calculated and maintained when window is resized or the
6833 * page is scrolled. If you reposition the container manually, you have to call #position to make
6834 * sure the element is still placed correctly.
6835 *
6836 * As positioning is only possible when both the element and the container are attached to the DOM
6837 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6838 * the #toggle method to display a floating popup, for example.
6839 *
6840 * @abstract
6841 * @class
6842 *
6843 * @constructor
6844 * @param {Object} [config] Configuration options
6845 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6846 * @cfg {jQuery} [$floatableContainer] Node to position below
6847 */
6848 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6849 // Configuration initialization
6850 config = config || {};
6851
6852 // Properties
6853 this.$floatable = null;
6854 this.$floatableContainer = null;
6855 this.$floatableWindow = null;
6856 this.$floatableClosestScrollable = null;
6857 this.onFloatableScrollHandler = this.position.bind( this );
6858 this.onFloatableWindowResizeHandler = this.position.bind( this );
6859
6860 // Initialization
6861 this.setFloatableContainer( config.$floatableContainer );
6862 this.setFloatableElement( config.$floatable || this.$element );
6863 };
6864
6865 /* Methods */
6866
6867 /**
6868 * Set floatable element.
6869 *
6870 * If an element is already set, it will be cleaned up before setting up the new element.
6871 *
6872 * @param {jQuery} $floatable Element to make floatable
6873 */
6874 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6875 if ( this.$floatable ) {
6876 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6877 this.$floatable.css( { left: '', top: '' } );
6878 }
6879
6880 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6881 this.position();
6882 };
6883
6884 /**
6885 * Set floatable container.
6886 *
6887 * The element will be always positioned under the specified container.
6888 *
6889 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6890 */
6891 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6892 this.$floatableContainer = $floatableContainer;
6893 if ( this.$floatable ) {
6894 this.position();
6895 }
6896 };
6897
6898 /**
6899 * Toggle positioning.
6900 *
6901 * Do not turn positioning on until after the element is attached to the DOM and visible.
6902 *
6903 * @param {boolean} [positioning] Enable positioning, omit to toggle
6904 * @chainable
6905 */
6906 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6907 var closestScrollableOfContainer, closestScrollableOfFloatable;
6908
6909 positioning = positioning === undefined ? !this.positioning : !!positioning;
6910
6911 if ( this.positioning !== positioning ) {
6912 this.positioning = positioning;
6913
6914 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6915 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6916 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6917 // If the scrollable is the root, we have to listen to scroll events
6918 // on the window because of browser inconsistencies (or do we? someone should verify this)
6919 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6920 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6921 }
6922 }
6923
6924 if ( positioning ) {
6925 this.$floatableWindow = $( this.getElementWindow() );
6926 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6927
6928 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6929 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6930 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6931 }
6932
6933 // Initial position after visible
6934 this.position();
6935 } else {
6936 if ( this.$floatableWindow ) {
6937 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6938 this.$floatableWindow = null;
6939 }
6940
6941 if ( this.$floatableClosestScrollable ) {
6942 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6943 this.$floatableClosestScrollable = null;
6944 }
6945
6946 this.$floatable.css( { left: '', top: '' } );
6947 }
6948 }
6949
6950 return this;
6951 };
6952
6953 /**
6954 * Position the floatable below its container.
6955 *
6956 * This should only be done when both of them are attached to the DOM and visible.
6957 *
6958 * @chainable
6959 */
6960 OO.ui.mixin.FloatableElement.prototype.position = function () {
6961 var pos;
6962
6963 if ( !this.positioning ) {
6964 return this;
6965 }
6966
6967 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
6968
6969 // Position under container
6970 pos.top += this.$floatableContainer.height();
6971 this.$floatable.css( pos );
6972
6973 // We updated the position, so re-evaluate the clipping state.
6974 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6975 // will not notice the need to update itself.)
6976 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6977 // it not listen to the right events in the right places?
6978 if ( this.clip ) {
6979 this.clip();
6980 }
6981
6982 return this;
6983 };
6984
6985 /**
6986 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6987 * Accesskeys allow an user to go to a specific element by using
6988 * a shortcut combination of a browser specific keys + the key
6989 * set to the field.
6990 *
6991 * @example
6992 * // AccessKeyedElement provides an 'accesskey' attribute to the
6993 * // ButtonWidget class
6994 * var button = new OO.ui.ButtonWidget( {
6995 * label: 'Button with Accesskey',
6996 * accessKey: 'k'
6997 * } );
6998 * $( 'body' ).append( button.$element );
6999 *
7000 * @abstract
7001 * @class
7002 *
7003 * @constructor
7004 * @param {Object} [config] Configuration options
7005 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7006 * If this config is omitted, the accesskey functionality is applied to $element, the
7007 * element created by the class.
7008 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7009 * this config is omitted, no accesskey will be added.
7010 */
7011 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7012 // Configuration initialization
7013 config = config || {};
7014
7015 // Properties
7016 this.$accessKeyed = null;
7017 this.accessKey = null;
7018
7019 // Initialization
7020 this.setAccessKey( config.accessKey || null );
7021 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7022 };
7023
7024 /* Setup */
7025
7026 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7027
7028 /* Static Properties */
7029
7030 /**
7031 * The access key, a function that returns a key, or `null` for no accesskey.
7032 *
7033 * @static
7034 * @inheritable
7035 * @property {string|Function|null}
7036 */
7037 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7038
7039 /* Methods */
7040
7041 /**
7042 * Set the accesskeyed element.
7043 *
7044 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7045 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7046 *
7047 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7048 */
7049 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7050 if ( this.$accessKeyed ) {
7051 this.$accessKeyed.removeAttr( 'accesskey' );
7052 }
7053
7054 this.$accessKeyed = $accessKeyed;
7055 if ( this.accessKey ) {
7056 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7057 }
7058 };
7059
7060 /**
7061 * Set accesskey.
7062 *
7063 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7064 * @chainable
7065 */
7066 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7067 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7068
7069 if ( this.accessKey !== accessKey ) {
7070 if ( this.$accessKeyed ) {
7071 if ( accessKey !== null ) {
7072 this.$accessKeyed.attr( 'accesskey', accessKey );
7073 } else {
7074 this.$accessKeyed.removeAttr( 'accesskey' );
7075 }
7076 }
7077 this.accessKey = accessKey;
7078 }
7079
7080 return this;
7081 };
7082
7083 /**
7084 * Get accesskey.
7085 *
7086 * @return {string} accessKey string
7087 */
7088 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7089 return this.accessKey;
7090 };
7091
7092 /**
7093 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7094 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7095 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7096 * which creates the tools on demand.
7097 *
7098 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7099 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7100 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7101 *
7102 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7103 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7104 *
7105 * @abstract
7106 * @class
7107 * @extends OO.ui.Widget
7108 * @mixins OO.ui.mixin.IconElement
7109 * @mixins OO.ui.mixin.FlaggedElement
7110 * @mixins OO.ui.mixin.TabIndexedElement
7111 *
7112 * @constructor
7113 * @param {OO.ui.ToolGroup} toolGroup
7114 * @param {Object} [config] Configuration options
7115 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7116 * the {@link #static-title static title} property is used.
7117 *
7118 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7119 * 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
7120 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7121 *
7122 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7123 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7124 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7125 */
7126 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7127 // Allow passing positional parameters inside the config object
7128 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7129 config = toolGroup;
7130 toolGroup = config.toolGroup;
7131 }
7132
7133 // Configuration initialization
7134 config = config || {};
7135
7136 // Parent constructor
7137 OO.ui.Tool.parent.call( this, config );
7138
7139 // Properties
7140 this.toolGroup = toolGroup;
7141 this.toolbar = this.toolGroup.getToolbar();
7142 this.active = false;
7143 this.$title = $( '<span>' );
7144 this.$accel = $( '<span>' );
7145 this.$link = $( '<a>' );
7146 this.title = null;
7147
7148 // Mixin constructors
7149 OO.ui.mixin.IconElement.call( this, config );
7150 OO.ui.mixin.FlaggedElement.call( this, config );
7151 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7152
7153 // Events
7154 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7155
7156 // Initialization
7157 this.$title.addClass( 'oo-ui-tool-title' );
7158 this.$accel
7159 .addClass( 'oo-ui-tool-accel' )
7160 .prop( {
7161 // This may need to be changed if the key names are ever localized,
7162 // but for now they are essentially written in English
7163 dir: 'ltr',
7164 lang: 'en'
7165 } );
7166 this.$link
7167 .addClass( 'oo-ui-tool-link' )
7168 .append( this.$icon, this.$title, this.$accel )
7169 .attr( 'role', 'button' );
7170 this.$element
7171 .data( 'oo-ui-tool', this )
7172 .addClass(
7173 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7174 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7175 )
7176 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7177 .append( this.$link );
7178 this.setTitle( config.title || this.constructor.static.title );
7179 };
7180
7181 /* Setup */
7182
7183 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7184 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7185 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7186 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7187
7188 /* Static Properties */
7189
7190 /**
7191 * @static
7192 * @inheritdoc
7193 */
7194 OO.ui.Tool.static.tagName = 'span';
7195
7196 /**
7197 * Symbolic name of tool.
7198 *
7199 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7200 * also be used when adding tools to toolgroups.
7201 *
7202 * @abstract
7203 * @static
7204 * @inheritable
7205 * @property {string}
7206 */
7207 OO.ui.Tool.static.name = '';
7208
7209 /**
7210 * Symbolic name of the group.
7211 *
7212 * The group name is used to associate tools with each other so that they can be selected later by
7213 * a {@link OO.ui.ToolGroup toolgroup}.
7214 *
7215 * @abstract
7216 * @static
7217 * @inheritable
7218 * @property {string}
7219 */
7220 OO.ui.Tool.static.group = '';
7221
7222 /**
7223 * 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.
7224 *
7225 * @abstract
7226 * @static
7227 * @inheritable
7228 * @property {string|Function}
7229 */
7230 OO.ui.Tool.static.title = '';
7231
7232 /**
7233 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7234 * Normally only the icon is displayed, or only the label if no icon is given.
7235 *
7236 * @static
7237 * @inheritable
7238 * @property {boolean}
7239 */
7240 OO.ui.Tool.static.displayBothIconAndLabel = false;
7241
7242 /**
7243 * Add tool to catch-all groups automatically.
7244 *
7245 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7246 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7247 *
7248 * @static
7249 * @inheritable
7250 * @property {boolean}
7251 */
7252 OO.ui.Tool.static.autoAddToCatchall = true;
7253
7254 /**
7255 * Add tool to named groups automatically.
7256 *
7257 * By default, tools that are configured with a static ‘group’ property are added
7258 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7259 * toolgroups include tools by group name).
7260 *
7261 * @static
7262 * @property {boolean}
7263 * @inheritable
7264 */
7265 OO.ui.Tool.static.autoAddToGroup = true;
7266
7267 /**
7268 * Check if this tool is compatible with given data.
7269 *
7270 * This is a stub that can be overriden to provide support for filtering tools based on an
7271 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7272 * must also call this method so that the compatibility check can be performed.
7273 *
7274 * @static
7275 * @inheritable
7276 * @param {Mixed} data Data to check
7277 * @return {boolean} Tool can be used with data
7278 */
7279 OO.ui.Tool.static.isCompatibleWith = function () {
7280 return false;
7281 };
7282
7283 /* Methods */
7284
7285 /**
7286 * Handle the toolbar state being updated.
7287 *
7288 * This is an abstract method that must be overridden in a concrete subclass.
7289 *
7290 * @protected
7291 * @abstract
7292 */
7293 OO.ui.Tool.prototype.onUpdateState = function () {
7294 throw new Error(
7295 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7296 );
7297 };
7298
7299 /**
7300 * Handle the tool being selected.
7301 *
7302 * This is an abstract method that must be overridden in a concrete subclass.
7303 *
7304 * @protected
7305 * @abstract
7306 */
7307 OO.ui.Tool.prototype.onSelect = function () {
7308 throw new Error(
7309 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7310 );
7311 };
7312
7313 /**
7314 * Check if the tool is active.
7315 *
7316 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7317 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7318 *
7319 * @return {boolean} Tool is active
7320 */
7321 OO.ui.Tool.prototype.isActive = function () {
7322 return this.active;
7323 };
7324
7325 /**
7326 * Make the tool appear active or inactive.
7327 *
7328 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7329 * appear pressed or not.
7330 *
7331 * @param {boolean} state Make tool appear active
7332 */
7333 OO.ui.Tool.prototype.setActive = function ( state ) {
7334 this.active = !!state;
7335 if ( this.active ) {
7336 this.$element.addClass( 'oo-ui-tool-active' );
7337 } else {
7338 this.$element.removeClass( 'oo-ui-tool-active' );
7339 }
7340 };
7341
7342 /**
7343 * Set the tool #title.
7344 *
7345 * @param {string|Function} title Title text or a function that returns text
7346 * @chainable
7347 */
7348 OO.ui.Tool.prototype.setTitle = function ( title ) {
7349 this.title = OO.ui.resolveMsg( title );
7350 this.updateTitle();
7351 return this;
7352 };
7353
7354 /**
7355 * Get the tool #title.
7356 *
7357 * @return {string} Title text
7358 */
7359 OO.ui.Tool.prototype.getTitle = function () {
7360 return this.title;
7361 };
7362
7363 /**
7364 * Get the tool's symbolic name.
7365 *
7366 * @return {string} Symbolic name of tool
7367 */
7368 OO.ui.Tool.prototype.getName = function () {
7369 return this.constructor.static.name;
7370 };
7371
7372 /**
7373 * Update the title.
7374 */
7375 OO.ui.Tool.prototype.updateTitle = function () {
7376 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7377 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7378 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7379 tooltipParts = [];
7380
7381 this.$title.text( this.title );
7382 this.$accel.text( accel );
7383
7384 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7385 tooltipParts.push( this.title );
7386 }
7387 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7388 tooltipParts.push( accel );
7389 }
7390 if ( tooltipParts.length ) {
7391 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7392 } else {
7393 this.$link.removeAttr( 'title' );
7394 }
7395 };
7396
7397 /**
7398 * Destroy tool.
7399 *
7400 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7401 * Call this method whenever you are done using a tool.
7402 */
7403 OO.ui.Tool.prototype.destroy = function () {
7404 this.toolbar.disconnect( this );
7405 this.$element.remove();
7406 };
7407
7408 /**
7409 * Toolbars are complex interface components that permit users to easily access a variety
7410 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7411 * part of the toolbar, but not configured as tools.
7412 *
7413 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7414 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7415 * picture’), and an icon.
7416 *
7417 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7418 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7419 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7420 * any order, but each can only appear once in the toolbar.
7421 *
7422 * The following is an example of a basic toolbar.
7423 *
7424 * @example
7425 * // Example of a toolbar
7426 * // Create the toolbar
7427 * var toolFactory = new OO.ui.ToolFactory();
7428 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7429 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7430 *
7431 * // We will be placing status text in this element when tools are used
7432 * var $area = $( '<p>' ).text( 'Toolbar example' );
7433 *
7434 * // Define the tools that we're going to place in our toolbar
7435 *
7436 * // Create a class inheriting from OO.ui.Tool
7437 * function PictureTool() {
7438 * PictureTool.parent.apply( this, arguments );
7439 * }
7440 * OO.inheritClass( PictureTool, OO.ui.Tool );
7441 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7442 * // of 'icon' and 'title' (displayed icon and text).
7443 * PictureTool.static.name = 'picture';
7444 * PictureTool.static.icon = 'picture';
7445 * PictureTool.static.title = 'Insert picture';
7446 * // Defines the action that will happen when this tool is selected (clicked).
7447 * PictureTool.prototype.onSelect = function () {
7448 * $area.text( 'Picture tool clicked!' );
7449 * // Never display this tool as "active" (selected).
7450 * this.setActive( false );
7451 * };
7452 * // Make this tool available in our toolFactory and thus our toolbar
7453 * toolFactory.register( PictureTool );
7454 *
7455 * // Register two more tools, nothing interesting here
7456 * function SettingsTool() {
7457 * SettingsTool.parent.apply( this, arguments );
7458 * }
7459 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7460 * SettingsTool.static.name = 'settings';
7461 * SettingsTool.static.icon = 'settings';
7462 * SettingsTool.static.title = 'Change settings';
7463 * SettingsTool.prototype.onSelect = function () {
7464 * $area.text( 'Settings tool clicked!' );
7465 * this.setActive( false );
7466 * };
7467 * toolFactory.register( SettingsTool );
7468 *
7469 * // Register two more tools, nothing interesting here
7470 * function StuffTool() {
7471 * StuffTool.parent.apply( this, arguments );
7472 * }
7473 * OO.inheritClass( StuffTool, OO.ui.Tool );
7474 * StuffTool.static.name = 'stuff';
7475 * StuffTool.static.icon = 'ellipsis';
7476 * StuffTool.static.title = 'More stuff';
7477 * StuffTool.prototype.onSelect = function () {
7478 * $area.text( 'More stuff tool clicked!' );
7479 * this.setActive( false );
7480 * };
7481 * toolFactory.register( StuffTool );
7482 *
7483 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7484 * // little popup window (a PopupWidget).
7485 * function HelpTool( toolGroup, config ) {
7486 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7487 * padded: true,
7488 * label: 'Help',
7489 * head: true
7490 * } }, config ) );
7491 * this.popup.$body.append( '<p>I am helpful!</p>' );
7492 * }
7493 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7494 * HelpTool.static.name = 'help';
7495 * HelpTool.static.icon = 'help';
7496 * HelpTool.static.title = 'Help';
7497 * toolFactory.register( HelpTool );
7498 *
7499 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7500 * // used once (but not all defined tools must be used).
7501 * toolbar.setup( [
7502 * {
7503 * // 'bar' tool groups display tools' icons only, side-by-side.
7504 * type: 'bar',
7505 * include: [ 'picture', 'help' ]
7506 * },
7507 * {
7508 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7509 * type: 'list',
7510 * indicator: 'down',
7511 * label: 'More',
7512 * include: [ 'settings', 'stuff' ]
7513 * }
7514 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7515 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7516 * // since it's more complicated to use. (See the next example snippet on this page.)
7517 * ] );
7518 *
7519 * // Create some UI around the toolbar and place it in the document
7520 * var frame = new OO.ui.PanelLayout( {
7521 * expanded: false,
7522 * framed: true
7523 * } );
7524 * var contentFrame = new OO.ui.PanelLayout( {
7525 * expanded: false,
7526 * padded: true
7527 * } );
7528 * frame.$element.append(
7529 * toolbar.$element,
7530 * contentFrame.$element.append( $area )
7531 * );
7532 * $( 'body' ).append( frame.$element );
7533 *
7534 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7535 * // document.
7536 * toolbar.initialize();
7537 *
7538 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7539 * 'updateState' event.
7540 *
7541 * @example
7542 * // Create the toolbar
7543 * var toolFactory = new OO.ui.ToolFactory();
7544 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7545 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7546 *
7547 * // We will be placing status text in this element when tools are used
7548 * var $area = $( '<p>' ).text( 'Toolbar example' );
7549 *
7550 * // Define the tools that we're going to place in our toolbar
7551 *
7552 * // Create a class inheriting from OO.ui.Tool
7553 * function PictureTool() {
7554 * PictureTool.parent.apply( this, arguments );
7555 * }
7556 * OO.inheritClass( PictureTool, OO.ui.Tool );
7557 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7558 * // of 'icon' and 'title' (displayed icon and text).
7559 * PictureTool.static.name = 'picture';
7560 * PictureTool.static.icon = 'picture';
7561 * PictureTool.static.title = 'Insert picture';
7562 * // Defines the action that will happen when this tool is selected (clicked).
7563 * PictureTool.prototype.onSelect = function () {
7564 * $area.text( 'Picture tool clicked!' );
7565 * // Never display this tool as "active" (selected).
7566 * this.setActive( false );
7567 * };
7568 * // The toolbar can be synchronized with the state of some external stuff, like a text
7569 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7570 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7571 * PictureTool.prototype.onUpdateState = function () {
7572 * };
7573 * // Make this tool available in our toolFactory and thus our toolbar
7574 * toolFactory.register( PictureTool );
7575 *
7576 * // Register two more tools, nothing interesting here
7577 * function SettingsTool() {
7578 * SettingsTool.parent.apply( this, arguments );
7579 * this.reallyActive = false;
7580 * }
7581 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7582 * SettingsTool.static.name = 'settings';
7583 * SettingsTool.static.icon = 'settings';
7584 * SettingsTool.static.title = 'Change settings';
7585 * SettingsTool.prototype.onSelect = function () {
7586 * $area.text( 'Settings tool clicked!' );
7587 * // Toggle the active state on each click
7588 * this.reallyActive = !this.reallyActive;
7589 * this.setActive( this.reallyActive );
7590 * // To update the menu label
7591 * this.toolbar.emit( 'updateState' );
7592 * };
7593 * SettingsTool.prototype.onUpdateState = function () {
7594 * };
7595 * toolFactory.register( SettingsTool );
7596 *
7597 * // Register two more tools, nothing interesting here
7598 * function StuffTool() {
7599 * StuffTool.parent.apply( this, arguments );
7600 * this.reallyActive = false;
7601 * }
7602 * OO.inheritClass( StuffTool, OO.ui.Tool );
7603 * StuffTool.static.name = 'stuff';
7604 * StuffTool.static.icon = 'ellipsis';
7605 * StuffTool.static.title = 'More stuff';
7606 * StuffTool.prototype.onSelect = function () {
7607 * $area.text( 'More stuff tool clicked!' );
7608 * // Toggle the active state on each click
7609 * this.reallyActive = !this.reallyActive;
7610 * this.setActive( this.reallyActive );
7611 * // To update the menu label
7612 * this.toolbar.emit( 'updateState' );
7613 * };
7614 * StuffTool.prototype.onUpdateState = function () {
7615 * };
7616 * toolFactory.register( StuffTool );
7617 *
7618 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7619 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7620 * function HelpTool( toolGroup, config ) {
7621 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7622 * padded: true,
7623 * label: 'Help',
7624 * head: true
7625 * } }, config ) );
7626 * this.popup.$body.append( '<p>I am helpful!</p>' );
7627 * }
7628 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7629 * HelpTool.static.name = 'help';
7630 * HelpTool.static.icon = 'help';
7631 * HelpTool.static.title = 'Help';
7632 * toolFactory.register( HelpTool );
7633 *
7634 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7635 * // used once (but not all defined tools must be used).
7636 * toolbar.setup( [
7637 * {
7638 * // 'bar' tool groups display tools' icons only, side-by-side.
7639 * type: 'bar',
7640 * include: [ 'picture', 'help' ]
7641 * },
7642 * {
7643 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7644 * // Menu label indicates which items are selected.
7645 * type: 'menu',
7646 * indicator: 'down',
7647 * include: [ 'settings', 'stuff' ]
7648 * }
7649 * ] );
7650 *
7651 * // Create some UI around the toolbar and place it in the document
7652 * var frame = new OO.ui.PanelLayout( {
7653 * expanded: false,
7654 * framed: true
7655 * } );
7656 * var contentFrame = new OO.ui.PanelLayout( {
7657 * expanded: false,
7658 * padded: true
7659 * } );
7660 * frame.$element.append(
7661 * toolbar.$element,
7662 * contentFrame.$element.append( $area )
7663 * );
7664 * $( 'body' ).append( frame.$element );
7665 *
7666 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7667 * // document.
7668 * toolbar.initialize();
7669 * toolbar.emit( 'updateState' );
7670 *
7671 * @class
7672 * @extends OO.ui.Element
7673 * @mixins OO.EventEmitter
7674 * @mixins OO.ui.mixin.GroupElement
7675 *
7676 * @constructor
7677 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7678 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7679 * @param {Object} [config] Configuration options
7680 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7681 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7682 * the toolbar.
7683 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7684 */
7685 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7686 // Allow passing positional parameters inside the config object
7687 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7688 config = toolFactory;
7689 toolFactory = config.toolFactory;
7690 toolGroupFactory = config.toolGroupFactory;
7691 }
7692
7693 // Configuration initialization
7694 config = config || {};
7695
7696 // Parent constructor
7697 OO.ui.Toolbar.parent.call( this, config );
7698
7699 // Mixin constructors
7700 OO.EventEmitter.call( this );
7701 OO.ui.mixin.GroupElement.call( this, config );
7702
7703 // Properties
7704 this.toolFactory = toolFactory;
7705 this.toolGroupFactory = toolGroupFactory;
7706 this.groups = [];
7707 this.tools = {};
7708 this.$bar = $( '<div>' );
7709 this.$actions = $( '<div>' );
7710 this.initialized = false;
7711 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7712
7713 // Events
7714 this.$element
7715 .add( this.$bar ).add( this.$group ).add( this.$actions )
7716 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7717
7718 // Initialization
7719 this.$group.addClass( 'oo-ui-toolbar-tools' );
7720 if ( config.actions ) {
7721 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7722 }
7723 this.$bar
7724 .addClass( 'oo-ui-toolbar-bar' )
7725 .append( this.$group, '<div style="clear:both"></div>' );
7726 if ( config.shadow ) {
7727 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7728 }
7729 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7730 };
7731
7732 /* Setup */
7733
7734 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7735 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7736 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7737
7738 /* Methods */
7739
7740 /**
7741 * Get the tool factory.
7742 *
7743 * @return {OO.ui.ToolFactory} Tool factory
7744 */
7745 OO.ui.Toolbar.prototype.getToolFactory = function () {
7746 return this.toolFactory;
7747 };
7748
7749 /**
7750 * Get the toolgroup factory.
7751 *
7752 * @return {OO.Factory} Toolgroup factory
7753 */
7754 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7755 return this.toolGroupFactory;
7756 };
7757
7758 /**
7759 * Handles mouse down events.
7760 *
7761 * @private
7762 * @param {jQuery.Event} e Mouse down event
7763 */
7764 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7765 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7766 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7767 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7768 return false;
7769 }
7770 };
7771
7772 /**
7773 * Handle window resize event.
7774 *
7775 * @private
7776 * @param {jQuery.Event} e Window resize event
7777 */
7778 OO.ui.Toolbar.prototype.onWindowResize = function () {
7779 this.$element.toggleClass(
7780 'oo-ui-toolbar-narrow',
7781 this.$bar.width() <= this.narrowThreshold
7782 );
7783 };
7784
7785 /**
7786 * Sets up handles and preloads required information for the toolbar to work.
7787 * This must be called after it is attached to a visible document and before doing anything else.
7788 */
7789 OO.ui.Toolbar.prototype.initialize = function () {
7790 if ( !this.initialized ) {
7791 this.initialized = true;
7792 this.narrowThreshold = this.$group.width() + this.$actions.width();
7793 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7794 this.onWindowResize();
7795 }
7796 };
7797
7798 /**
7799 * Set up the toolbar.
7800 *
7801 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7802 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7803 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7804 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7805 *
7806 * @param {Object.<string,Array>} groups List of toolgroup configurations
7807 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7808 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7809 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7810 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7811 */
7812 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7813 var i, len, type, group,
7814 items = [],
7815 defaultType = 'bar';
7816
7817 // Cleanup previous groups
7818 this.reset();
7819
7820 // Build out new groups
7821 for ( i = 0, len = groups.length; i < len; i++ ) {
7822 group = groups[ i ];
7823 if ( group.include === '*' ) {
7824 // Apply defaults to catch-all groups
7825 if ( group.type === undefined ) {
7826 group.type = 'list';
7827 }
7828 if ( group.label === undefined ) {
7829 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7830 }
7831 }
7832 // Check type has been registered
7833 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7834 items.push(
7835 this.getToolGroupFactory().create( type, this, group )
7836 );
7837 }
7838 this.addItems( items );
7839 };
7840
7841 /**
7842 * Remove all tools and toolgroups from the toolbar.
7843 */
7844 OO.ui.Toolbar.prototype.reset = function () {
7845 var i, len;
7846
7847 this.groups = [];
7848 this.tools = {};
7849 for ( i = 0, len = this.items.length; i < len; i++ ) {
7850 this.items[ i ].destroy();
7851 }
7852 this.clearItems();
7853 };
7854
7855 /**
7856 * Destroy the toolbar.
7857 *
7858 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7859 * this method whenever you are done using a toolbar.
7860 */
7861 OO.ui.Toolbar.prototype.destroy = function () {
7862 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7863 this.reset();
7864 this.$element.remove();
7865 };
7866
7867 /**
7868 * Check if the tool is available.
7869 *
7870 * Available tools are ones that have not yet been added to the toolbar.
7871 *
7872 * @param {string} name Symbolic name of tool
7873 * @return {boolean} Tool is available
7874 */
7875 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7876 return !this.tools[ name ];
7877 };
7878
7879 /**
7880 * Prevent tool from being used again.
7881 *
7882 * @param {OO.ui.Tool} tool Tool to reserve
7883 */
7884 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7885 this.tools[ tool.getName() ] = tool;
7886 };
7887
7888 /**
7889 * Allow tool to be used again.
7890 *
7891 * @param {OO.ui.Tool} tool Tool to release
7892 */
7893 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7894 delete this.tools[ tool.getName() ];
7895 };
7896
7897 /**
7898 * Get accelerator label for tool.
7899 *
7900 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7901 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7902 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7903 *
7904 * @param {string} name Symbolic name of tool
7905 * @return {string|undefined} Tool accelerator label if available
7906 */
7907 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7908 return undefined;
7909 };
7910
7911 /**
7912 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7913 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7914 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7915 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7916 *
7917 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7918 *
7919 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7920 *
7921 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7922 *
7923 * 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.)
7924 *
7925 * include: [ { group: 'group-name' } ]
7926 *
7927 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7928 *
7929 * include: '*'
7930 *
7931 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7932 * please see the [OOjs UI documentation on MediaWiki][1].
7933 *
7934 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7935 *
7936 * @abstract
7937 * @class
7938 * @extends OO.ui.Widget
7939 * @mixins OO.ui.mixin.GroupElement
7940 *
7941 * @constructor
7942 * @param {OO.ui.Toolbar} toolbar
7943 * @param {Object} [config] Configuration options
7944 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7945 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7946 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7947 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7948 * This setting is particularly useful when tools have been added to the toolgroup
7949 * en masse (e.g., via the catch-all selector).
7950 */
7951 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7952 // Allow passing positional parameters inside the config object
7953 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7954 config = toolbar;
7955 toolbar = config.toolbar;
7956 }
7957
7958 // Configuration initialization
7959 config = config || {};
7960
7961 // Parent constructor
7962 OO.ui.ToolGroup.parent.call( this, config );
7963
7964 // Mixin constructors
7965 OO.ui.mixin.GroupElement.call( this, config );
7966
7967 // Properties
7968 this.toolbar = toolbar;
7969 this.tools = {};
7970 this.pressed = null;
7971 this.autoDisabled = false;
7972 this.include = config.include || [];
7973 this.exclude = config.exclude || [];
7974 this.promote = config.promote || [];
7975 this.demote = config.demote || [];
7976 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7977
7978 // Events
7979 this.$element.on( {
7980 mousedown: this.onMouseKeyDown.bind( this ),
7981 mouseup: this.onMouseKeyUp.bind( this ),
7982 keydown: this.onMouseKeyDown.bind( this ),
7983 keyup: this.onMouseKeyUp.bind( this ),
7984 focus: this.onMouseOverFocus.bind( this ),
7985 blur: this.onMouseOutBlur.bind( this ),
7986 mouseover: this.onMouseOverFocus.bind( this ),
7987 mouseout: this.onMouseOutBlur.bind( this )
7988 } );
7989 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7990 this.aggregate( { disable: 'itemDisable' } );
7991 this.connect( this, { itemDisable: 'updateDisabled' } );
7992
7993 // Initialization
7994 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7995 this.$element
7996 .addClass( 'oo-ui-toolGroup' )
7997 .append( this.$group );
7998 this.populate();
7999 };
8000
8001 /* Setup */
8002
8003 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8004 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8005
8006 /* Events */
8007
8008 /**
8009 * @event update
8010 */
8011
8012 /* Static Properties */
8013
8014 /**
8015 * Show labels in tooltips.
8016 *
8017 * @static
8018 * @inheritable
8019 * @property {boolean}
8020 */
8021 OO.ui.ToolGroup.static.titleTooltips = false;
8022
8023 /**
8024 * Show acceleration labels in tooltips.
8025 *
8026 * Note: The OOjs UI library does not include an accelerator system, but does contain
8027 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8028 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8029 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8030 *
8031 * @static
8032 * @inheritable
8033 * @property {boolean}
8034 */
8035 OO.ui.ToolGroup.static.accelTooltips = false;
8036
8037 /**
8038 * Automatically disable the toolgroup when all tools are disabled
8039 *
8040 * @static
8041 * @inheritable
8042 * @property {boolean}
8043 */
8044 OO.ui.ToolGroup.static.autoDisable = true;
8045
8046 /* Methods */
8047
8048 /**
8049 * @inheritdoc
8050 */
8051 OO.ui.ToolGroup.prototype.isDisabled = function () {
8052 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8053 };
8054
8055 /**
8056 * @inheritdoc
8057 */
8058 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8059 var i, item, allDisabled = true;
8060
8061 if ( this.constructor.static.autoDisable ) {
8062 for ( i = this.items.length - 1; i >= 0; i-- ) {
8063 item = this.items[ i ];
8064 if ( !item.isDisabled() ) {
8065 allDisabled = false;
8066 break;
8067 }
8068 }
8069 this.autoDisabled = allDisabled;
8070 }
8071 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8072 };
8073
8074 /**
8075 * Handle mouse down and key down events.
8076 *
8077 * @protected
8078 * @param {jQuery.Event} e Mouse down or key down event
8079 */
8080 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8081 if (
8082 !this.isDisabled() &&
8083 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8084 ) {
8085 this.pressed = this.getTargetTool( e );
8086 if ( this.pressed ) {
8087 this.pressed.setActive( true );
8088 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8089 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8090 }
8091 return false;
8092 }
8093 };
8094
8095 /**
8096 * Handle captured mouse up and key up events.
8097 *
8098 * @protected
8099 * @param {Event} e Mouse up or key up event
8100 */
8101 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8102 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8103 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8104 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8105 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8106 this.onMouseKeyUp( e );
8107 };
8108
8109 /**
8110 * Handle mouse up and key up events.
8111 *
8112 * @protected
8113 * @param {jQuery.Event} e Mouse up or key up event
8114 */
8115 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8116 var tool = this.getTargetTool( e );
8117
8118 if (
8119 !this.isDisabled() && this.pressed && this.pressed === tool &&
8120 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8121 ) {
8122 this.pressed.onSelect();
8123 this.pressed = null;
8124 return false;
8125 }
8126
8127 this.pressed = null;
8128 };
8129
8130 /**
8131 * Handle mouse over and focus events.
8132 *
8133 * @protected
8134 * @param {jQuery.Event} e Mouse over or focus event
8135 */
8136 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8137 var tool = this.getTargetTool( e );
8138
8139 if ( this.pressed && this.pressed === tool ) {
8140 this.pressed.setActive( true );
8141 }
8142 };
8143
8144 /**
8145 * Handle mouse out and blur events.
8146 *
8147 * @protected
8148 * @param {jQuery.Event} e Mouse out or blur event
8149 */
8150 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8151 var tool = this.getTargetTool( e );
8152
8153 if ( this.pressed && this.pressed === tool ) {
8154 this.pressed.setActive( false );
8155 }
8156 };
8157
8158 /**
8159 * Get the closest tool to a jQuery.Event.
8160 *
8161 * Only tool links are considered, which prevents other elements in the tool such as popups from
8162 * triggering tool group interactions.
8163 *
8164 * @private
8165 * @param {jQuery.Event} e
8166 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8167 */
8168 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8169 var tool,
8170 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8171
8172 if ( $item.length ) {
8173 tool = $item.parent().data( 'oo-ui-tool' );
8174 }
8175
8176 return tool && !tool.isDisabled() ? tool : null;
8177 };
8178
8179 /**
8180 * Handle tool registry register events.
8181 *
8182 * If a tool is registered after the group is created, we must repopulate the list to account for:
8183 *
8184 * - a tool being added that may be included
8185 * - a tool already included being overridden
8186 *
8187 * @protected
8188 * @param {string} name Symbolic name of tool
8189 */
8190 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8191 this.populate();
8192 };
8193
8194 /**
8195 * Get the toolbar that contains the toolgroup.
8196 *
8197 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8198 */
8199 OO.ui.ToolGroup.prototype.getToolbar = function () {
8200 return this.toolbar;
8201 };
8202
8203 /**
8204 * Add and remove tools based on configuration.
8205 */
8206 OO.ui.ToolGroup.prototype.populate = function () {
8207 var i, len, name, tool,
8208 toolFactory = this.toolbar.getToolFactory(),
8209 names = {},
8210 add = [],
8211 remove = [],
8212 list = this.toolbar.getToolFactory().getTools(
8213 this.include, this.exclude, this.promote, this.demote
8214 );
8215
8216 // Build a list of needed tools
8217 for ( i = 0, len = list.length; i < len; i++ ) {
8218 name = list[ i ];
8219 if (
8220 // Tool exists
8221 toolFactory.lookup( name ) &&
8222 // Tool is available or is already in this group
8223 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8224 ) {
8225 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8226 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8227 this.toolbar.tools[ name ] = true;
8228 tool = this.tools[ name ];
8229 if ( !tool ) {
8230 // Auto-initialize tools on first use
8231 this.tools[ name ] = tool = toolFactory.create( name, this );
8232 tool.updateTitle();
8233 }
8234 this.toolbar.reserveTool( tool );
8235 add.push( tool );
8236 names[ name ] = true;
8237 }
8238 }
8239 // Remove tools that are no longer needed
8240 for ( name in this.tools ) {
8241 if ( !names[ name ] ) {
8242 this.tools[ name ].destroy();
8243 this.toolbar.releaseTool( this.tools[ name ] );
8244 remove.push( this.tools[ name ] );
8245 delete this.tools[ name ];
8246 }
8247 }
8248 if ( remove.length ) {
8249 this.removeItems( remove );
8250 }
8251 // Update emptiness state
8252 if ( add.length ) {
8253 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8254 } else {
8255 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8256 }
8257 // Re-add tools (moving existing ones to new locations)
8258 this.addItems( add );
8259 // Disabled state may depend on items
8260 this.updateDisabled();
8261 };
8262
8263 /**
8264 * Destroy toolgroup.
8265 */
8266 OO.ui.ToolGroup.prototype.destroy = function () {
8267 var name;
8268
8269 this.clearItems();
8270 this.toolbar.getToolFactory().disconnect( this );
8271 for ( name in this.tools ) {
8272 this.toolbar.releaseTool( this.tools[ name ] );
8273 this.tools[ name ].disconnect( this ).destroy();
8274 delete this.tools[ name ];
8275 }
8276 this.$element.remove();
8277 };
8278
8279 /**
8280 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8281 * consists of a header that contains the dialog title, a body with the message, and a footer that
8282 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8283 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8284 *
8285 * There are two basic types of message dialogs, confirmation and alert:
8286 *
8287 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8288 * more details about the consequences.
8289 * - **alert**: the dialog title describes which event occurred and the message provides more information
8290 * about why the event occurred.
8291 *
8292 * The MessageDialog class specifies two actions: ‘accept’, the primary
8293 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8294 * passing along the selected action.
8295 *
8296 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8297 *
8298 * @example
8299 * // Example: Creating and opening a message dialog window.
8300 * var messageDialog = new OO.ui.MessageDialog();
8301 *
8302 * // Create and append a window manager.
8303 * var windowManager = new OO.ui.WindowManager();
8304 * $( 'body' ).append( windowManager.$element );
8305 * windowManager.addWindows( [ messageDialog ] );
8306 * // Open the window.
8307 * windowManager.openWindow( messageDialog, {
8308 * title: 'Basic message dialog',
8309 * message: 'This is the message'
8310 * } );
8311 *
8312 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8313 *
8314 * @class
8315 * @extends OO.ui.Dialog
8316 *
8317 * @constructor
8318 * @param {Object} [config] Configuration options
8319 */
8320 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8321 // Parent constructor
8322 OO.ui.MessageDialog.parent.call( this, config );
8323
8324 // Properties
8325 this.verticalActionLayout = null;
8326
8327 // Initialization
8328 this.$element.addClass( 'oo-ui-messageDialog' );
8329 };
8330
8331 /* Setup */
8332
8333 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8334
8335 /* Static Properties */
8336
8337 OO.ui.MessageDialog.static.name = 'message';
8338
8339 OO.ui.MessageDialog.static.size = 'small';
8340
8341 OO.ui.MessageDialog.static.verbose = false;
8342
8343 /**
8344 * Dialog title.
8345 *
8346 * The title of a confirmation dialog describes what a progressive action will do. The
8347 * title of an alert dialog describes which event occurred.
8348 *
8349 * @static
8350 * @inheritable
8351 * @property {jQuery|string|Function|null}
8352 */
8353 OO.ui.MessageDialog.static.title = null;
8354
8355 /**
8356 * The message displayed in the dialog body.
8357 *
8358 * A confirmation message describes the consequences of a progressive action. An alert
8359 * message describes why an event occurred.
8360 *
8361 * @static
8362 * @inheritable
8363 * @property {jQuery|string|Function|null}
8364 */
8365 OO.ui.MessageDialog.static.message = null;
8366
8367 OO.ui.MessageDialog.static.actions = [
8368 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8369 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8370 ];
8371
8372 /* Methods */
8373
8374 /**
8375 * @inheritdoc
8376 */
8377 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8378 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8379
8380 // Events
8381 this.manager.connect( this, {
8382 resize: 'onResize'
8383 } );
8384
8385 return this;
8386 };
8387
8388 /**
8389 * @inheritdoc
8390 */
8391 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8392 this.fitActions();
8393 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8394 };
8395
8396 /**
8397 * Handle window resized events.
8398 *
8399 * @private
8400 */
8401 OO.ui.MessageDialog.prototype.onResize = function () {
8402 var dialog = this;
8403 dialog.fitActions();
8404 // Wait for CSS transition to finish and do it again :(
8405 setTimeout( function () {
8406 dialog.fitActions();
8407 }, 300 );
8408 };
8409
8410 /**
8411 * Toggle action layout between vertical and horizontal.
8412 *
8413 * @private
8414 * @param {boolean} [value] Layout actions vertically, omit to toggle
8415 * @chainable
8416 */
8417 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8418 value = value === undefined ? !this.verticalActionLayout : !!value;
8419
8420 if ( value !== this.verticalActionLayout ) {
8421 this.verticalActionLayout = value;
8422 this.$actions
8423 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8424 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8425 }
8426
8427 return this;
8428 };
8429
8430 /**
8431 * @inheritdoc
8432 */
8433 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8434 if ( action ) {
8435 return new OO.ui.Process( function () {
8436 this.close( { action: action } );
8437 }, this );
8438 }
8439 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8440 };
8441
8442 /**
8443 * @inheritdoc
8444 *
8445 * @param {Object} [data] Dialog opening data
8446 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8447 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8448 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8449 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8450 * action item
8451 */
8452 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8453 data = data || {};
8454
8455 // Parent method
8456 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8457 .next( function () {
8458 this.title.setLabel(
8459 data.title !== undefined ? data.title : this.constructor.static.title
8460 );
8461 this.message.setLabel(
8462 data.message !== undefined ? data.message : this.constructor.static.message
8463 );
8464 this.message.$element.toggleClass(
8465 'oo-ui-messageDialog-message-verbose',
8466 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8467 );
8468 }, this );
8469 };
8470
8471 /**
8472 * @inheritdoc
8473 */
8474 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8475 data = data || {};
8476
8477 // Parent method
8478 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8479 .next( function () {
8480 // Focus the primary action button
8481 var actions = this.actions.get();
8482 actions = actions.filter( function ( action ) {
8483 return action.getFlags().indexOf( 'primary' ) > -1;
8484 } );
8485 if ( actions.length > 0 ) {
8486 actions[ 0 ].$button.focus();
8487 }
8488 }, this );
8489 };
8490
8491 /**
8492 * @inheritdoc
8493 */
8494 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8495 var bodyHeight, oldOverflow,
8496 $scrollable = this.container.$element;
8497
8498 oldOverflow = $scrollable[ 0 ].style.overflow;
8499 $scrollable[ 0 ].style.overflow = 'hidden';
8500
8501 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8502
8503 bodyHeight = this.text.$element.outerHeight( true );
8504 $scrollable[ 0 ].style.overflow = oldOverflow;
8505
8506 return bodyHeight;
8507 };
8508
8509 /**
8510 * @inheritdoc
8511 */
8512 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8513 var $scrollable = this.container.$element;
8514 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8515
8516 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8517 // Need to do it after transition completes (250ms), add 50ms just in case.
8518 setTimeout( function () {
8519 var oldOverflow = $scrollable[ 0 ].style.overflow;
8520 $scrollable[ 0 ].style.overflow = 'hidden';
8521
8522 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8523
8524 $scrollable[ 0 ].style.overflow = oldOverflow;
8525 }, 300 );
8526
8527 return this;
8528 };
8529
8530 /**
8531 * @inheritdoc
8532 */
8533 OO.ui.MessageDialog.prototype.initialize = function () {
8534 // Parent method
8535 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8536
8537 // Properties
8538 this.$actions = $( '<div>' );
8539 this.container = new OO.ui.PanelLayout( {
8540 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8541 } );
8542 this.text = new OO.ui.PanelLayout( {
8543 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8544 } );
8545 this.message = new OO.ui.LabelWidget( {
8546 classes: [ 'oo-ui-messageDialog-message' ]
8547 } );
8548
8549 // Initialization
8550 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8551 this.$content.addClass( 'oo-ui-messageDialog-content' );
8552 this.container.$element.append( this.text.$element );
8553 this.text.$element.append( this.title.$element, this.message.$element );
8554 this.$body.append( this.container.$element );
8555 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8556 this.$foot.append( this.$actions );
8557 };
8558
8559 /**
8560 * @inheritdoc
8561 */
8562 OO.ui.MessageDialog.prototype.attachActions = function () {
8563 var i, len, other, special, others;
8564
8565 // Parent method
8566 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8567
8568 special = this.actions.getSpecial();
8569 others = this.actions.getOthers();
8570
8571 if ( special.safe ) {
8572 this.$actions.append( special.safe.$element );
8573 special.safe.toggleFramed( false );
8574 }
8575 if ( others.length ) {
8576 for ( i = 0, len = others.length; i < len; i++ ) {
8577 other = others[ i ];
8578 this.$actions.append( other.$element );
8579 other.toggleFramed( false );
8580 }
8581 }
8582 if ( special.primary ) {
8583 this.$actions.append( special.primary.$element );
8584 special.primary.toggleFramed( false );
8585 }
8586
8587 if ( !this.isOpening() ) {
8588 // If the dialog is currently opening, this will be called automatically soon.
8589 // This also calls #fitActions.
8590 this.updateSize();
8591 }
8592 };
8593
8594 /**
8595 * Fit action actions into columns or rows.
8596 *
8597 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8598 *
8599 * @private
8600 */
8601 OO.ui.MessageDialog.prototype.fitActions = function () {
8602 var i, len, action,
8603 previous = this.verticalActionLayout,
8604 actions = this.actions.get();
8605
8606 // Detect clipping
8607 this.toggleVerticalActionLayout( false );
8608 for ( i = 0, len = actions.length; i < len; i++ ) {
8609 action = actions[ i ];
8610 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8611 this.toggleVerticalActionLayout( true );
8612 break;
8613 }
8614 }
8615
8616 // Move the body out of the way of the foot
8617 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8618
8619 if ( this.verticalActionLayout !== previous ) {
8620 // We changed the layout, window height might need to be updated.
8621 this.updateSize();
8622 }
8623 };
8624
8625 /**
8626 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8627 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8628 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8629 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8630 * required for each process.
8631 *
8632 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8633 * processes with an animation. The header contains the dialog title as well as
8634 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8635 * a ‘primary’ action on the right (e.g., ‘Done’).
8636 *
8637 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8638 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8639 *
8640 * @example
8641 * // Example: Creating and opening a process dialog window.
8642 * function MyProcessDialog( config ) {
8643 * MyProcessDialog.parent.call( this, config );
8644 * }
8645 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8646 *
8647 * MyProcessDialog.static.title = 'Process dialog';
8648 * MyProcessDialog.static.actions = [
8649 * { action: 'save', label: 'Done', flags: 'primary' },
8650 * { label: 'Cancel', flags: 'safe' }
8651 * ];
8652 *
8653 * MyProcessDialog.prototype.initialize = function () {
8654 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8655 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8656 * 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>' );
8657 * this.$body.append( this.content.$element );
8658 * };
8659 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8660 * var dialog = this;
8661 * if ( action ) {
8662 * return new OO.ui.Process( function () {
8663 * dialog.close( { action: action } );
8664 * } );
8665 * }
8666 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8667 * };
8668 *
8669 * var windowManager = new OO.ui.WindowManager();
8670 * $( 'body' ).append( windowManager.$element );
8671 *
8672 * var dialog = new MyProcessDialog();
8673 * windowManager.addWindows( [ dialog ] );
8674 * windowManager.openWindow( dialog );
8675 *
8676 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8677 *
8678 * @abstract
8679 * @class
8680 * @extends OO.ui.Dialog
8681 *
8682 * @constructor
8683 * @param {Object} [config] Configuration options
8684 */
8685 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8686 // Parent constructor
8687 OO.ui.ProcessDialog.parent.call( this, config );
8688
8689 // Properties
8690 this.fitOnOpen = false;
8691
8692 // Initialization
8693 this.$element.addClass( 'oo-ui-processDialog' );
8694 };
8695
8696 /* Setup */
8697
8698 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8699
8700 /* Methods */
8701
8702 /**
8703 * Handle dismiss button click events.
8704 *
8705 * Hides errors.
8706 *
8707 * @private
8708 */
8709 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8710 this.hideErrors();
8711 };
8712
8713 /**
8714 * Handle retry button click events.
8715 *
8716 * Hides errors and then tries again.
8717 *
8718 * @private
8719 */
8720 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8721 this.hideErrors();
8722 this.executeAction( this.currentAction );
8723 };
8724
8725 /**
8726 * @inheritdoc
8727 */
8728 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8729 if ( this.actions.isSpecial( action ) ) {
8730 this.fitLabel();
8731 }
8732 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8733 };
8734
8735 /**
8736 * @inheritdoc
8737 */
8738 OO.ui.ProcessDialog.prototype.initialize = function () {
8739 // Parent method
8740 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8741
8742 // Properties
8743 this.$navigation = $( '<div>' );
8744 this.$location = $( '<div>' );
8745 this.$safeActions = $( '<div>' );
8746 this.$primaryActions = $( '<div>' );
8747 this.$otherActions = $( '<div>' );
8748 this.dismissButton = new OO.ui.ButtonWidget( {
8749 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8750 } );
8751 this.retryButton = new OO.ui.ButtonWidget();
8752 this.$errors = $( '<div>' );
8753 this.$errorsTitle = $( '<div>' );
8754
8755 // Events
8756 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8757 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8758
8759 // Initialization
8760 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8761 this.$location
8762 .append( this.title.$element )
8763 .addClass( 'oo-ui-processDialog-location' );
8764 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8765 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8766 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8767 this.$errorsTitle
8768 .addClass( 'oo-ui-processDialog-errors-title' )
8769 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8770 this.$errors
8771 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8772 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8773 this.$content
8774 .addClass( 'oo-ui-processDialog-content' )
8775 .append( this.$errors );
8776 this.$navigation
8777 .addClass( 'oo-ui-processDialog-navigation' )
8778 .append( this.$safeActions, this.$location, this.$primaryActions );
8779 this.$head.append( this.$navigation );
8780 this.$foot.append( this.$otherActions );
8781 };
8782
8783 /**
8784 * @inheritdoc
8785 */
8786 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8787 var i, len, widgets = [];
8788 for ( i = 0, len = actions.length; i < len; i++ ) {
8789 widgets.push(
8790 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8791 );
8792 }
8793 return widgets;
8794 };
8795
8796 /**
8797 * @inheritdoc
8798 */
8799 OO.ui.ProcessDialog.prototype.attachActions = function () {
8800 var i, len, other, special, others;
8801
8802 // Parent method
8803 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8804
8805 special = this.actions.getSpecial();
8806 others = this.actions.getOthers();
8807 if ( special.primary ) {
8808 this.$primaryActions.append( special.primary.$element );
8809 }
8810 for ( i = 0, len = others.length; i < len; i++ ) {
8811 other = others[ i ];
8812 this.$otherActions.append( other.$element );
8813 }
8814 if ( special.safe ) {
8815 this.$safeActions.append( special.safe.$element );
8816 }
8817
8818 this.fitLabel();
8819 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8820 };
8821
8822 /**
8823 * @inheritdoc
8824 */
8825 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8826 var process = this;
8827 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8828 .fail( function ( errors ) {
8829 process.showErrors( errors || [] );
8830 } );
8831 };
8832
8833 /**
8834 * @inheritdoc
8835 */
8836 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8837 // Parent method
8838 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8839
8840 this.fitLabel();
8841 };
8842
8843 /**
8844 * Fit label between actions.
8845 *
8846 * @private
8847 * @chainable
8848 */
8849 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8850 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8851 size = this.getSizeProperties();
8852
8853 if ( typeof size.width !== 'number' ) {
8854 if ( this.isOpened() ) {
8855 navigationWidth = this.$head.width() - 20;
8856 } else if ( this.isOpening() ) {
8857 if ( !this.fitOnOpen ) {
8858 // Size is relative and the dialog isn't open yet, so wait.
8859 this.manager.opening.done( this.fitLabel.bind( this ) );
8860 this.fitOnOpen = true;
8861 }
8862 return;
8863 } else {
8864 return;
8865 }
8866 } else {
8867 navigationWidth = size.width - 20;
8868 }
8869
8870 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8871 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8872 biggerWidth = Math.max( safeWidth, primaryWidth );
8873
8874 labelWidth = this.title.$element.width();
8875
8876 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8877 // We have enough space to center the label
8878 leftWidth = rightWidth = biggerWidth;
8879 } else {
8880 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8881 if ( this.getDir() === 'ltr' ) {
8882 leftWidth = safeWidth;
8883 rightWidth = primaryWidth;
8884 } else {
8885 leftWidth = primaryWidth;
8886 rightWidth = safeWidth;
8887 }
8888 }
8889
8890 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8891
8892 return this;
8893 };
8894
8895 /**
8896 * Handle errors that occurred during accept or reject processes.
8897 *
8898 * @private
8899 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8900 */
8901 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8902 var i, len, $item, actions,
8903 items = [],
8904 abilities = {},
8905 recoverable = true,
8906 warning = false;
8907
8908 if ( errors instanceof OO.ui.Error ) {
8909 errors = [ errors ];
8910 }
8911
8912 for ( i = 0, len = errors.length; i < len; i++ ) {
8913 if ( !errors[ i ].isRecoverable() ) {
8914 recoverable = false;
8915 }
8916 if ( errors[ i ].isWarning() ) {
8917 warning = true;
8918 }
8919 $item = $( '<div>' )
8920 .addClass( 'oo-ui-processDialog-error' )
8921 .append( errors[ i ].getMessage() );
8922 items.push( $item[ 0 ] );
8923 }
8924 this.$errorItems = $( items );
8925 if ( recoverable ) {
8926 abilities[ this.currentAction ] = true;
8927 // Copy the flags from the first matching action
8928 actions = this.actions.get( { actions: this.currentAction } );
8929 if ( actions.length ) {
8930 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8931 }
8932 } else {
8933 abilities[ this.currentAction ] = false;
8934 this.actions.setAbilities( abilities );
8935 }
8936 if ( warning ) {
8937 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8938 } else {
8939 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8940 }
8941 this.retryButton.toggle( recoverable );
8942 this.$errorsTitle.after( this.$errorItems );
8943 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8944 };
8945
8946 /**
8947 * Hide errors.
8948 *
8949 * @private
8950 */
8951 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8952 this.$errors.addClass( 'oo-ui-element-hidden' );
8953 if ( this.$errorItems ) {
8954 this.$errorItems.remove();
8955 this.$errorItems = null;
8956 }
8957 };
8958
8959 /**
8960 * @inheritdoc
8961 */
8962 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8963 // Parent method
8964 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8965 .first( function () {
8966 // Make sure to hide errors
8967 this.hideErrors();
8968 this.fitOnOpen = false;
8969 }, this );
8970 };
8971
8972 /**
8973 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8974 * which is a widget that is specified by reference before any optional configuration settings.
8975 *
8976 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8977 *
8978 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8979 * A left-alignment is used for forms with many fields.
8980 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8981 * A right-alignment is used for long but familiar forms which users tab through,
8982 * verifying the current field with a quick glance at the label.
8983 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8984 * that users fill out from top to bottom.
8985 * - **inline**: The label is placed after the field-widget and aligned to the left.
8986 * An inline-alignment is best used with checkboxes or radio buttons.
8987 *
8988 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8989 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8990 *
8991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8992 * @class
8993 * @extends OO.ui.Layout
8994 * @mixins OO.ui.mixin.LabelElement
8995 * @mixins OO.ui.mixin.TitledElement
8996 *
8997 * @constructor
8998 * @param {OO.ui.Widget} fieldWidget Field widget
8999 * @param {Object} [config] Configuration options
9000 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9001 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9002 * The array may contain strings or OO.ui.HtmlSnippet instances.
9003 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9004 * The array may contain strings or OO.ui.HtmlSnippet instances.
9005 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9006 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9007 * For important messages, you are advised to use `notices`, as they are always shown.
9008 *
9009 * @throws {Error} An error is thrown if no widget is specified
9010 */
9011 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9012 var hasInputWidget, div, i;
9013
9014 // Allow passing positional parameters inside the config object
9015 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9016 config = fieldWidget;
9017 fieldWidget = config.fieldWidget;
9018 }
9019
9020 // Make sure we have required constructor arguments
9021 if ( fieldWidget === undefined ) {
9022 throw new Error( 'Widget not found' );
9023 }
9024
9025 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9026
9027 // Configuration initialization
9028 config = $.extend( { align: 'left' }, config );
9029
9030 // Parent constructor
9031 OO.ui.FieldLayout.parent.call( this, config );
9032
9033 // Mixin constructors
9034 OO.ui.mixin.LabelElement.call( this, config );
9035 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9036
9037 // Properties
9038 this.fieldWidget = fieldWidget;
9039 this.errors = config.errors || [];
9040 this.notices = config.notices || [];
9041 this.$field = $( '<div>' );
9042 this.$messages = $( '<ul>' );
9043 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9044 this.align = null;
9045 if ( config.help ) {
9046 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9047 classes: [ 'oo-ui-fieldLayout-help' ],
9048 framed: false,
9049 icon: 'info'
9050 } );
9051
9052 div = $( '<div>' );
9053 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9054 div.html( config.help.toString() );
9055 } else {
9056 div.text( config.help );
9057 }
9058 this.popupButtonWidget.getPopup().$body.append(
9059 div.addClass( 'oo-ui-fieldLayout-help-content' )
9060 );
9061 this.$help = this.popupButtonWidget.$element;
9062 } else {
9063 this.$help = $( [] );
9064 }
9065
9066 // Events
9067 if ( hasInputWidget ) {
9068 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9069 }
9070 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9071
9072 // Initialization
9073 this.$element
9074 .addClass( 'oo-ui-fieldLayout' )
9075 .append( this.$help, this.$body );
9076 if ( this.errors.length || this.notices.length ) {
9077 this.$element.append( this.$messages );
9078 }
9079 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9080 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9081 this.$field
9082 .addClass( 'oo-ui-fieldLayout-field' )
9083 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9084 .append( this.fieldWidget.$element );
9085
9086 for ( i = 0; i < this.notices.length; i++ ) {
9087 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9088 }
9089 for ( i = 0; i < this.errors.length; i++ ) {
9090 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9091 }
9092
9093 this.setAlignment( config.align );
9094 };
9095
9096 /* Setup */
9097
9098 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9099 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9100 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9101
9102 /* Methods */
9103
9104 /**
9105 * Handle field disable events.
9106 *
9107 * @private
9108 * @param {boolean} value Field is disabled
9109 */
9110 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9111 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9112 };
9113
9114 /**
9115 * Handle label mouse click events.
9116 *
9117 * @private
9118 * @param {jQuery.Event} e Mouse click event
9119 */
9120 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9121 this.fieldWidget.simulateLabelClick();
9122 return false;
9123 };
9124
9125 /**
9126 * Get the widget contained by the field.
9127 *
9128 * @return {OO.ui.Widget} Field widget
9129 */
9130 OO.ui.FieldLayout.prototype.getField = function () {
9131 return this.fieldWidget;
9132 };
9133
9134 /**
9135 * @param {string} kind 'error' or 'notice'
9136 * @param {string|OO.ui.HtmlSnippet} text
9137 * @return {jQuery}
9138 */
9139 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9140 var $listItem, $icon, message;
9141 $listItem = $( '<li>' );
9142 if ( kind === 'error' ) {
9143 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9144 } else if ( kind === 'notice' ) {
9145 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9146 } else {
9147 $icon = '';
9148 }
9149 message = new OO.ui.LabelWidget( { label: text } );
9150 $listItem
9151 .append( $icon, message.$element )
9152 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9153 return $listItem;
9154 };
9155
9156 /**
9157 * Set the field alignment mode.
9158 *
9159 * @private
9160 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9161 * @chainable
9162 */
9163 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9164 if ( value !== this.align ) {
9165 // Default to 'left'
9166 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9167 value = 'left';
9168 }
9169 // Reorder elements
9170 if ( value === 'inline' ) {
9171 this.$body.append( this.$field, this.$label );
9172 } else {
9173 this.$body.append( this.$label, this.$field );
9174 }
9175 // Set classes. The following classes can be used here:
9176 // * oo-ui-fieldLayout-align-left
9177 // * oo-ui-fieldLayout-align-right
9178 // * oo-ui-fieldLayout-align-top
9179 // * oo-ui-fieldLayout-align-inline
9180 if ( this.align ) {
9181 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9182 }
9183 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9184 this.align = value;
9185 }
9186
9187 return this;
9188 };
9189
9190 /**
9191 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9192 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9193 * is required and is specified before any optional configuration settings.
9194 *
9195 * Labels can be aligned in one of four ways:
9196 *
9197 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9198 * A left-alignment is used for forms with many fields.
9199 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9200 * A right-alignment is used for long but familiar forms which users tab through,
9201 * verifying the current field with a quick glance at the label.
9202 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9203 * that users fill out from top to bottom.
9204 * - **inline**: The label is placed after the field-widget and aligned to the left.
9205 * An inline-alignment is best used with checkboxes or radio buttons.
9206 *
9207 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9208 * text is specified.
9209 *
9210 * @example
9211 * // Example of an ActionFieldLayout
9212 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9213 * new OO.ui.TextInputWidget( {
9214 * placeholder: 'Field widget'
9215 * } ),
9216 * new OO.ui.ButtonWidget( {
9217 * label: 'Button'
9218 * } ),
9219 * {
9220 * label: 'An ActionFieldLayout. This label is aligned top',
9221 * align: 'top',
9222 * help: 'This is help text'
9223 * }
9224 * );
9225 *
9226 * $( 'body' ).append( actionFieldLayout.$element );
9227 *
9228 * @class
9229 * @extends OO.ui.FieldLayout
9230 *
9231 * @constructor
9232 * @param {OO.ui.Widget} fieldWidget Field widget
9233 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9234 */
9235 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9236 // Allow passing positional parameters inside the config object
9237 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9238 config = fieldWidget;
9239 fieldWidget = config.fieldWidget;
9240 buttonWidget = config.buttonWidget;
9241 }
9242
9243 // Parent constructor
9244 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9245
9246 // Properties
9247 this.buttonWidget = buttonWidget;
9248 this.$button = $( '<div>' );
9249 this.$input = $( '<div>' );
9250
9251 // Initialization
9252 this.$element
9253 .addClass( 'oo-ui-actionFieldLayout' );
9254 this.$button
9255 .addClass( 'oo-ui-actionFieldLayout-button' )
9256 .append( this.buttonWidget.$element );
9257 this.$input
9258 .addClass( 'oo-ui-actionFieldLayout-input' )
9259 .append( this.fieldWidget.$element );
9260 this.$field
9261 .append( this.$input, this.$button );
9262 };
9263
9264 /* Setup */
9265
9266 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9267
9268 /**
9269 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9270 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9271 * configured with a label as well. For more information and examples,
9272 * please see the [OOjs UI documentation on MediaWiki][1].
9273 *
9274 * @example
9275 * // Example of a fieldset layout
9276 * var input1 = new OO.ui.TextInputWidget( {
9277 * placeholder: 'A text input field'
9278 * } );
9279 *
9280 * var input2 = new OO.ui.TextInputWidget( {
9281 * placeholder: 'A text input field'
9282 * } );
9283 *
9284 * var fieldset = new OO.ui.FieldsetLayout( {
9285 * label: 'Example of a fieldset layout'
9286 * } );
9287 *
9288 * fieldset.addItems( [
9289 * new OO.ui.FieldLayout( input1, {
9290 * label: 'Field One'
9291 * } ),
9292 * new OO.ui.FieldLayout( input2, {
9293 * label: 'Field Two'
9294 * } )
9295 * ] );
9296 * $( 'body' ).append( fieldset.$element );
9297 *
9298 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9299 *
9300 * @class
9301 * @extends OO.ui.Layout
9302 * @mixins OO.ui.mixin.IconElement
9303 * @mixins OO.ui.mixin.LabelElement
9304 * @mixins OO.ui.mixin.GroupElement
9305 *
9306 * @constructor
9307 * @param {Object} [config] Configuration options
9308 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9309 */
9310 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9311 // Configuration initialization
9312 config = config || {};
9313
9314 // Parent constructor
9315 OO.ui.FieldsetLayout.parent.call( this, config );
9316
9317 // Mixin constructors
9318 OO.ui.mixin.IconElement.call( this, config );
9319 OO.ui.mixin.LabelElement.call( this, config );
9320 OO.ui.mixin.GroupElement.call( this, config );
9321
9322 if ( config.help ) {
9323 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9324 classes: [ 'oo-ui-fieldsetLayout-help' ],
9325 framed: false,
9326 icon: 'info'
9327 } );
9328
9329 this.popupButtonWidget.getPopup().$body.append(
9330 $( '<div>' )
9331 .text( config.help )
9332 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9333 );
9334 this.$help = this.popupButtonWidget.$element;
9335 } else {
9336 this.$help = $( [] );
9337 }
9338
9339 // Initialization
9340 this.$element
9341 .addClass( 'oo-ui-fieldsetLayout' )
9342 .prepend( this.$help, this.$icon, this.$label, this.$group );
9343 if ( Array.isArray( config.items ) ) {
9344 this.addItems( config.items );
9345 }
9346 };
9347
9348 /* Setup */
9349
9350 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9351 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9352 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9353 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9354
9355 /**
9356 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9357 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9358 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9359 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9360 *
9361 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9362 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9363 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9364 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9365 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9366 * often have simplified APIs to match the capabilities of HTML forms.
9367 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9368 *
9369 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9370 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9371 *
9372 * @example
9373 * // Example of a form layout that wraps a fieldset layout
9374 * var input1 = new OO.ui.TextInputWidget( {
9375 * placeholder: 'Username'
9376 * } );
9377 * var input2 = new OO.ui.TextInputWidget( {
9378 * placeholder: 'Password',
9379 * type: 'password'
9380 * } );
9381 * var submit = new OO.ui.ButtonInputWidget( {
9382 * label: 'Submit'
9383 * } );
9384 *
9385 * var fieldset = new OO.ui.FieldsetLayout( {
9386 * label: 'A form layout'
9387 * } );
9388 * fieldset.addItems( [
9389 * new OO.ui.FieldLayout( input1, {
9390 * label: 'Username',
9391 * align: 'top'
9392 * } ),
9393 * new OO.ui.FieldLayout( input2, {
9394 * label: 'Password',
9395 * align: 'top'
9396 * } ),
9397 * new OO.ui.FieldLayout( submit )
9398 * ] );
9399 * var form = new OO.ui.FormLayout( {
9400 * items: [ fieldset ],
9401 * action: '/api/formhandler',
9402 * method: 'get'
9403 * } )
9404 * $( 'body' ).append( form.$element );
9405 *
9406 * @class
9407 * @extends OO.ui.Layout
9408 * @mixins OO.ui.mixin.GroupElement
9409 *
9410 * @constructor
9411 * @param {Object} [config] Configuration options
9412 * @cfg {string} [method] HTML form `method` attribute
9413 * @cfg {string} [action] HTML form `action` attribute
9414 * @cfg {string} [enctype] HTML form `enctype` attribute
9415 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9416 */
9417 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9418 // Configuration initialization
9419 config = config || {};
9420
9421 // Parent constructor
9422 OO.ui.FormLayout.parent.call( this, config );
9423
9424 // Mixin constructors
9425 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9426
9427 // Events
9428 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9429
9430 // Make sure the action is safe
9431 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9432 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9433 }
9434
9435 // Initialization
9436 this.$element
9437 .addClass( 'oo-ui-formLayout' )
9438 .attr( {
9439 method: config.method,
9440 action: config.action,
9441 enctype: config.enctype
9442 } );
9443 if ( Array.isArray( config.items ) ) {
9444 this.addItems( config.items );
9445 }
9446 };
9447
9448 /* Setup */
9449
9450 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9451 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9452
9453 /* Events */
9454
9455 /**
9456 * A 'submit' event is emitted when the form is submitted.
9457 *
9458 * @event submit
9459 */
9460
9461 /* Static Properties */
9462
9463 OO.ui.FormLayout.static.tagName = 'form';
9464
9465 /* Methods */
9466
9467 /**
9468 * Handle form submit events.
9469 *
9470 * @private
9471 * @param {jQuery.Event} e Submit event
9472 * @fires submit
9473 */
9474 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9475 if ( this.emit( 'submit' ) ) {
9476 return false;
9477 }
9478 };
9479
9480 /**
9481 * 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)
9482 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9483 *
9484 * @example
9485 * var menuLayout = new OO.ui.MenuLayout( {
9486 * position: 'top'
9487 * } ),
9488 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9489 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9490 * select = new OO.ui.SelectWidget( {
9491 * items: [
9492 * new OO.ui.OptionWidget( {
9493 * data: 'before',
9494 * label: 'Before',
9495 * } ),
9496 * new OO.ui.OptionWidget( {
9497 * data: 'after',
9498 * label: 'After',
9499 * } ),
9500 * new OO.ui.OptionWidget( {
9501 * data: 'top',
9502 * label: 'Top',
9503 * } ),
9504 * new OO.ui.OptionWidget( {
9505 * data: 'bottom',
9506 * label: 'Bottom',
9507 * } )
9508 * ]
9509 * } ).on( 'select', function ( item ) {
9510 * menuLayout.setMenuPosition( item.getData() );
9511 * } );
9512 *
9513 * menuLayout.$menu.append(
9514 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9515 * );
9516 * menuLayout.$content.append(
9517 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9518 * );
9519 * $( 'body' ).append( menuLayout.$element );
9520 *
9521 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9522 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9523 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9524 * may be omitted.
9525 *
9526 * .oo-ui-menuLayout-menu {
9527 * height: 200px;
9528 * width: 200px;
9529 * }
9530 * .oo-ui-menuLayout-content {
9531 * top: 200px;
9532 * left: 200px;
9533 * right: 200px;
9534 * bottom: 200px;
9535 * }
9536 *
9537 * @class
9538 * @extends OO.ui.Layout
9539 *
9540 * @constructor
9541 * @param {Object} [config] Configuration options
9542 * @cfg {boolean} [showMenu=true] Show menu
9543 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9544 */
9545 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9546 // Configuration initialization
9547 config = $.extend( {
9548 showMenu: true,
9549 menuPosition: 'before'
9550 }, config );
9551
9552 // Parent constructor
9553 OO.ui.MenuLayout.parent.call( this, config );
9554
9555 /**
9556 * Menu DOM node
9557 *
9558 * @property {jQuery}
9559 */
9560 this.$menu = $( '<div>' );
9561 /**
9562 * Content DOM node
9563 *
9564 * @property {jQuery}
9565 */
9566 this.$content = $( '<div>' );
9567
9568 // Initialization
9569 this.$menu
9570 .addClass( 'oo-ui-menuLayout-menu' );
9571 this.$content.addClass( 'oo-ui-menuLayout-content' );
9572 this.$element
9573 .addClass( 'oo-ui-menuLayout' )
9574 .append( this.$content, this.$menu );
9575 this.setMenuPosition( config.menuPosition );
9576 this.toggleMenu( config.showMenu );
9577 };
9578
9579 /* Setup */
9580
9581 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9582
9583 /* Methods */
9584
9585 /**
9586 * Toggle menu.
9587 *
9588 * @param {boolean} showMenu Show menu, omit to toggle
9589 * @chainable
9590 */
9591 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9592 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9593
9594 if ( this.showMenu !== showMenu ) {
9595 this.showMenu = showMenu;
9596 this.$element
9597 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9598 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9599 }
9600
9601 return this;
9602 };
9603
9604 /**
9605 * Check if menu is visible
9606 *
9607 * @return {boolean} Menu is visible
9608 */
9609 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9610 return this.showMenu;
9611 };
9612
9613 /**
9614 * Set menu position.
9615 *
9616 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9617 * @throws {Error} If position value is not supported
9618 * @chainable
9619 */
9620 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9621 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9622 this.menuPosition = position;
9623 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9624
9625 return this;
9626 };
9627
9628 /**
9629 * Get menu position.
9630 *
9631 * @return {string} Menu position
9632 */
9633 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9634 return this.menuPosition;
9635 };
9636
9637 /**
9638 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9639 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9640 * through the pages and select which one to display. By default, only one page is
9641 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9642 * the booklet layout automatically focuses on the first focusable element, unless the
9643 * default setting is changed. Optionally, booklets can be configured to show
9644 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9645 *
9646 * @example
9647 * // Example of a BookletLayout that contains two PageLayouts.
9648 *
9649 * function PageOneLayout( name, config ) {
9650 * PageOneLayout.parent.call( this, name, config );
9651 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9652 * }
9653 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9654 * PageOneLayout.prototype.setupOutlineItem = function () {
9655 * this.outlineItem.setLabel( 'Page One' );
9656 * };
9657 *
9658 * function PageTwoLayout( name, config ) {
9659 * PageTwoLayout.parent.call( this, name, config );
9660 * this.$element.append( '<p>Second page</p>' );
9661 * }
9662 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9663 * PageTwoLayout.prototype.setupOutlineItem = function () {
9664 * this.outlineItem.setLabel( 'Page Two' );
9665 * };
9666 *
9667 * var page1 = new PageOneLayout( 'one' ),
9668 * page2 = new PageTwoLayout( 'two' );
9669 *
9670 * var booklet = new OO.ui.BookletLayout( {
9671 * outlined: true
9672 * } );
9673 *
9674 * booklet.addPages ( [ page1, page2 ] );
9675 * $( 'body' ).append( booklet.$element );
9676 *
9677 * @class
9678 * @extends OO.ui.MenuLayout
9679 *
9680 * @constructor
9681 * @param {Object} [config] Configuration options
9682 * @cfg {boolean} [continuous=false] Show all pages, one after another
9683 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9684 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9685 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9686 */
9687 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9688 // Configuration initialization
9689 config = config || {};
9690
9691 // Parent constructor
9692 OO.ui.BookletLayout.parent.call( this, config );
9693
9694 // Properties
9695 this.currentPageName = null;
9696 this.pages = {};
9697 this.ignoreFocus = false;
9698 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9699 this.$content.append( this.stackLayout.$element );
9700 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9701 this.outlineVisible = false;
9702 this.outlined = !!config.outlined;
9703 if ( this.outlined ) {
9704 this.editable = !!config.editable;
9705 this.outlineControlsWidget = null;
9706 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9707 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9708 this.$menu.append( this.outlinePanel.$element );
9709 this.outlineVisible = true;
9710 if ( this.editable ) {
9711 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9712 this.outlineSelectWidget
9713 );
9714 }
9715 }
9716 this.toggleMenu( this.outlined );
9717
9718 // Events
9719 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9720 if ( this.outlined ) {
9721 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9722 }
9723 if ( this.autoFocus ) {
9724 // Event 'focus' does not bubble, but 'focusin' does
9725 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9726 }
9727
9728 // Initialization
9729 this.$element.addClass( 'oo-ui-bookletLayout' );
9730 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9731 if ( this.outlined ) {
9732 this.outlinePanel.$element
9733 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9734 .append( this.outlineSelectWidget.$element );
9735 if ( this.editable ) {
9736 this.outlinePanel.$element
9737 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9738 .append( this.outlineControlsWidget.$element );
9739 }
9740 }
9741 };
9742
9743 /* Setup */
9744
9745 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9746
9747 /* Events */
9748
9749 /**
9750 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9751 * @event set
9752 * @param {OO.ui.PageLayout} page Current page
9753 */
9754
9755 /**
9756 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9757 *
9758 * @event add
9759 * @param {OO.ui.PageLayout[]} page Added pages
9760 * @param {number} index Index pages were added at
9761 */
9762
9763 /**
9764 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9765 * {@link #removePages removed} from the booklet.
9766 *
9767 * @event remove
9768 * @param {OO.ui.PageLayout[]} pages Removed pages
9769 */
9770
9771 /* Methods */
9772
9773 /**
9774 * Handle stack layout focus.
9775 *
9776 * @private
9777 * @param {jQuery.Event} e Focusin event
9778 */
9779 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9780 var name, $target;
9781
9782 // Find the page that an element was focused within
9783 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9784 for ( name in this.pages ) {
9785 // Check for page match, exclude current page to find only page changes
9786 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9787 this.setPage( name );
9788 break;
9789 }
9790 }
9791 };
9792
9793 /**
9794 * Handle stack layout set events.
9795 *
9796 * @private
9797 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9798 */
9799 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9800 var layout = this;
9801 if ( page ) {
9802 page.scrollElementIntoView( { complete: function () {
9803 if ( layout.autoFocus ) {
9804 layout.focus();
9805 }
9806 } } );
9807 }
9808 };
9809
9810 /**
9811 * Focus the first input in the current page.
9812 *
9813 * If no page is selected, the first selectable page will be selected.
9814 * If the focus is already in an element on the current page, nothing will happen.
9815 * @param {number} [itemIndex] A specific item to focus on
9816 */
9817 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9818 var page,
9819 items = this.stackLayout.getItems();
9820
9821 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9822 page = items[ itemIndex ];
9823 } else {
9824 page = this.stackLayout.getCurrentItem();
9825 }
9826
9827 if ( !page && this.outlined ) {
9828 this.selectFirstSelectablePage();
9829 page = this.stackLayout.getCurrentItem();
9830 }
9831 if ( !page ) {
9832 return;
9833 }
9834 // Only change the focus if is not already in the current page
9835 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
9836 page.focus();
9837 }
9838 };
9839
9840 /**
9841 * Find the first focusable input in the booklet layout and focus
9842 * on it.
9843 */
9844 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9845 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9846 };
9847
9848 /**
9849 * Handle outline widget select events.
9850 *
9851 * @private
9852 * @param {OO.ui.OptionWidget|null} item Selected item
9853 */
9854 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9855 if ( item ) {
9856 this.setPage( item.getData() );
9857 }
9858 };
9859
9860 /**
9861 * Check if booklet has an outline.
9862 *
9863 * @return {boolean} Booklet has an outline
9864 */
9865 OO.ui.BookletLayout.prototype.isOutlined = function () {
9866 return this.outlined;
9867 };
9868
9869 /**
9870 * Check if booklet has editing controls.
9871 *
9872 * @return {boolean} Booklet is editable
9873 */
9874 OO.ui.BookletLayout.prototype.isEditable = function () {
9875 return this.editable;
9876 };
9877
9878 /**
9879 * Check if booklet has a visible outline.
9880 *
9881 * @return {boolean} Outline is visible
9882 */
9883 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9884 return this.outlined && this.outlineVisible;
9885 };
9886
9887 /**
9888 * Hide or show the outline.
9889 *
9890 * @param {boolean} [show] Show outline, omit to invert current state
9891 * @chainable
9892 */
9893 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9894 if ( this.outlined ) {
9895 show = show === undefined ? !this.outlineVisible : !!show;
9896 this.outlineVisible = show;
9897 this.toggleMenu( show );
9898 }
9899
9900 return this;
9901 };
9902
9903 /**
9904 * Get the page closest to the specified page.
9905 *
9906 * @param {OO.ui.PageLayout} page Page to use as a reference point
9907 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9908 */
9909 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9910 var next, prev, level,
9911 pages = this.stackLayout.getItems(),
9912 index = pages.indexOf( page );
9913
9914 if ( index !== -1 ) {
9915 next = pages[ index + 1 ];
9916 prev = pages[ index - 1 ];
9917 // Prefer adjacent pages at the same level
9918 if ( this.outlined ) {
9919 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9920 if (
9921 prev &&
9922 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9923 ) {
9924 return prev;
9925 }
9926 if (
9927 next &&
9928 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9929 ) {
9930 return next;
9931 }
9932 }
9933 }
9934 return prev || next || null;
9935 };
9936
9937 /**
9938 * Get the outline widget.
9939 *
9940 * If the booklet is not outlined, the method will return `null`.
9941 *
9942 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9943 */
9944 OO.ui.BookletLayout.prototype.getOutline = function () {
9945 return this.outlineSelectWidget;
9946 };
9947
9948 /**
9949 * Get the outline controls widget.
9950 *
9951 * If the outline is not editable, the method will return `null`.
9952 *
9953 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9954 */
9955 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9956 return this.outlineControlsWidget;
9957 };
9958
9959 /**
9960 * Get a page by its symbolic name.
9961 *
9962 * @param {string} name Symbolic name of page
9963 * @return {OO.ui.PageLayout|undefined} Page, if found
9964 */
9965 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9966 return this.pages[ name ];
9967 };
9968
9969 /**
9970 * Get the current page.
9971 *
9972 * @return {OO.ui.PageLayout|undefined} Current page, if found
9973 */
9974 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9975 var name = this.getCurrentPageName();
9976 return name ? this.getPage( name ) : undefined;
9977 };
9978
9979 /**
9980 * Get the symbolic name of the current page.
9981 *
9982 * @return {string|null} Symbolic name of the current page
9983 */
9984 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9985 return this.currentPageName;
9986 };
9987
9988 /**
9989 * Add pages to the booklet layout
9990 *
9991 * When pages are added with the same names as existing pages, the existing pages will be
9992 * automatically removed before the new pages are added.
9993 *
9994 * @param {OO.ui.PageLayout[]} pages Pages to add
9995 * @param {number} index Index of the insertion point
9996 * @fires add
9997 * @chainable
9998 */
9999 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10000 var i, len, name, page, item, currentIndex,
10001 stackLayoutPages = this.stackLayout.getItems(),
10002 remove = [],
10003 items = [];
10004
10005 // Remove pages with same names
10006 for ( i = 0, len = pages.length; i < len; i++ ) {
10007 page = pages[ i ];
10008 name = page.getName();
10009
10010 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10011 // Correct the insertion index
10012 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10013 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10014 index--;
10015 }
10016 remove.push( this.pages[ name ] );
10017 }
10018 }
10019 if ( remove.length ) {
10020 this.removePages( remove );
10021 }
10022
10023 // Add new pages
10024 for ( i = 0, len = pages.length; i < len; i++ ) {
10025 page = pages[ i ];
10026 name = page.getName();
10027 this.pages[ page.getName() ] = page;
10028 if ( this.outlined ) {
10029 item = new OO.ui.OutlineOptionWidget( { data: name } );
10030 page.setOutlineItem( item );
10031 items.push( item );
10032 }
10033 }
10034
10035 if ( this.outlined && items.length ) {
10036 this.outlineSelectWidget.addItems( items, index );
10037 this.selectFirstSelectablePage();
10038 }
10039 this.stackLayout.addItems( pages, index );
10040 this.emit( 'add', pages, index );
10041
10042 return this;
10043 };
10044
10045 /**
10046 * Remove the specified pages from the booklet layout.
10047 *
10048 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10049 *
10050 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10051 * @fires remove
10052 * @chainable
10053 */
10054 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10055 var i, len, name, page,
10056 items = [];
10057
10058 for ( i = 0, len = pages.length; i < len; i++ ) {
10059 page = pages[ i ];
10060 name = page.getName();
10061 delete this.pages[ name ];
10062 if ( this.outlined ) {
10063 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10064 page.setOutlineItem( null );
10065 }
10066 }
10067 if ( this.outlined && items.length ) {
10068 this.outlineSelectWidget.removeItems( items );
10069 this.selectFirstSelectablePage();
10070 }
10071 this.stackLayout.removeItems( pages );
10072 this.emit( 'remove', pages );
10073
10074 return this;
10075 };
10076
10077 /**
10078 * Clear all pages from the booklet layout.
10079 *
10080 * To remove only a subset of pages from the booklet, use the #removePages method.
10081 *
10082 * @fires remove
10083 * @chainable
10084 */
10085 OO.ui.BookletLayout.prototype.clearPages = function () {
10086 var i, len,
10087 pages = this.stackLayout.getItems();
10088
10089 this.pages = {};
10090 this.currentPageName = null;
10091 if ( this.outlined ) {
10092 this.outlineSelectWidget.clearItems();
10093 for ( i = 0, len = pages.length; i < len; i++ ) {
10094 pages[ i ].setOutlineItem( null );
10095 }
10096 }
10097 this.stackLayout.clearItems();
10098
10099 this.emit( 'remove', pages );
10100
10101 return this;
10102 };
10103
10104 /**
10105 * Set the current page by symbolic name.
10106 *
10107 * @fires set
10108 * @param {string} name Symbolic name of page
10109 */
10110 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10111 var selectedItem,
10112 $focused,
10113 page = this.pages[ name ],
10114 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10115
10116 if ( name !== this.currentPageName ) {
10117 if ( this.outlined ) {
10118 selectedItem = this.outlineSelectWidget.getSelectedItem();
10119 if ( selectedItem && selectedItem.getData() !== name ) {
10120 this.outlineSelectWidget.selectItemByData( name );
10121 }
10122 }
10123 if ( page ) {
10124 if ( previousPage ) {
10125 previousPage.setActive( false );
10126 // Blur anything focused if the next page doesn't have anything focusable.
10127 // This is not needed if the next page has something focusable (because once it is focused
10128 // this blur happens automatically). If the layout is non-continuous, this check is
10129 // meaningless because the next page is not visible yet and thus can't hold focus.
10130 if (
10131 this.autoFocus &&
10132 this.stackLayout.continuous &&
10133 OO.ui.findFocusable( page.$element ).length !== 0
10134 ) {
10135 $focused = previousPage.$element.find( ':focus' );
10136 if ( $focused.length ) {
10137 $focused[ 0 ].blur();
10138 }
10139 }
10140 }
10141 this.currentPageName = name;
10142 page.setActive( true );
10143 this.stackLayout.setItem( page );
10144 if ( !this.stackLayout.continuous && previousPage ) {
10145 // This should not be necessary, since any inputs on the previous page should have been
10146 // blurred when it was hidden, but browsers are not very consistent about this.
10147 $focused = previousPage.$element.find( ':focus' );
10148 if ( $focused.length ) {
10149 $focused[ 0 ].blur();
10150 }
10151 }
10152 this.emit( 'set', page );
10153 }
10154 }
10155 };
10156
10157 /**
10158 * Select the first selectable page.
10159 *
10160 * @chainable
10161 */
10162 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10163 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10164 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10165 }
10166
10167 return this;
10168 };
10169
10170 /**
10171 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10172 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10173 * select which one to display. By default, only one card is displayed at a time. When a user
10174 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10175 * unless the default setting is changed.
10176 *
10177 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10178 *
10179 * @example
10180 * // Example of a IndexLayout that contains two CardLayouts.
10181 *
10182 * function CardOneLayout( name, config ) {
10183 * CardOneLayout.parent.call( this, name, config );
10184 * this.$element.append( '<p>First card</p>' );
10185 * }
10186 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10187 * CardOneLayout.prototype.setupTabItem = function () {
10188 * this.tabItem.setLabel( 'Card one' );
10189 * };
10190 *
10191 * var card1 = new CardOneLayout( 'one' ),
10192 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10193 *
10194 * card2.$element.append( '<p>Second card</p>' );
10195 *
10196 * var index = new OO.ui.IndexLayout();
10197 *
10198 * index.addCards ( [ card1, card2 ] );
10199 * $( 'body' ).append( index.$element );
10200 *
10201 * @class
10202 * @extends OO.ui.MenuLayout
10203 *
10204 * @constructor
10205 * @param {Object} [config] Configuration options
10206 * @cfg {boolean} [continuous=false] Show all cards, one after another
10207 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10208 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10209 */
10210 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10211 // Configuration initialization
10212 config = $.extend( {}, config, { menuPosition: 'top' } );
10213
10214 // Parent constructor
10215 OO.ui.IndexLayout.parent.call( this, config );
10216
10217 // Properties
10218 this.currentCardName = null;
10219 this.cards = {};
10220 this.ignoreFocus = false;
10221 this.stackLayout = new OO.ui.StackLayout( {
10222 continuous: !!config.continuous,
10223 expanded: config.expanded
10224 } );
10225 this.$content.append( this.stackLayout.$element );
10226 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10227
10228 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10229 this.tabPanel = new OO.ui.PanelLayout();
10230 this.$menu.append( this.tabPanel.$element );
10231
10232 this.toggleMenu( true );
10233
10234 // Events
10235 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10236 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10237 if ( this.autoFocus ) {
10238 // Event 'focus' does not bubble, but 'focusin' does
10239 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10240 }
10241
10242 // Initialization
10243 this.$element.addClass( 'oo-ui-indexLayout' );
10244 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10245 this.tabPanel.$element
10246 .addClass( 'oo-ui-indexLayout-tabPanel' )
10247 .append( this.tabSelectWidget.$element );
10248 };
10249
10250 /* Setup */
10251
10252 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10253
10254 /* Events */
10255
10256 /**
10257 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10258 * @event set
10259 * @param {OO.ui.CardLayout} card Current card
10260 */
10261
10262 /**
10263 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10264 *
10265 * @event add
10266 * @param {OO.ui.CardLayout[]} card Added cards
10267 * @param {number} index Index cards were added at
10268 */
10269
10270 /**
10271 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10272 * {@link #removeCards removed} from the index.
10273 *
10274 * @event remove
10275 * @param {OO.ui.CardLayout[]} cards Removed cards
10276 */
10277
10278 /* Methods */
10279
10280 /**
10281 * Handle stack layout focus.
10282 *
10283 * @private
10284 * @param {jQuery.Event} e Focusin event
10285 */
10286 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10287 var name, $target;
10288
10289 // Find the card that an element was focused within
10290 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10291 for ( name in this.cards ) {
10292 // Check for card match, exclude current card to find only card changes
10293 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10294 this.setCard( name );
10295 break;
10296 }
10297 }
10298 };
10299
10300 /**
10301 * Handle stack layout set events.
10302 *
10303 * @private
10304 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10305 */
10306 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10307 var layout = this;
10308 if ( card ) {
10309 card.scrollElementIntoView( { complete: function () {
10310 if ( layout.autoFocus ) {
10311 layout.focus();
10312 }
10313 } } );
10314 }
10315 };
10316
10317 /**
10318 * Focus the first input in the current card.
10319 *
10320 * If no card is selected, the first selectable card will be selected.
10321 * If the focus is already in an element on the current card, nothing will happen.
10322 * @param {number} [itemIndex] A specific item to focus on
10323 */
10324 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10325 var card,
10326 items = this.stackLayout.getItems();
10327
10328 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10329 card = items[ itemIndex ];
10330 } else {
10331 card = this.stackLayout.getCurrentItem();
10332 }
10333
10334 if ( !card ) {
10335 this.selectFirstSelectableCard();
10336 card = this.stackLayout.getCurrentItem();
10337 }
10338 if ( !card ) {
10339 return;
10340 }
10341 // Only change the focus if is not already in the current page
10342 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10343 card.focus();
10344 }
10345 };
10346
10347 /**
10348 * Find the first focusable input in the index layout and focus
10349 * on it.
10350 */
10351 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10352 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10353 };
10354
10355 /**
10356 * Handle tab widget select events.
10357 *
10358 * @private
10359 * @param {OO.ui.OptionWidget|null} item Selected item
10360 */
10361 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10362 if ( item ) {
10363 this.setCard( item.getData() );
10364 }
10365 };
10366
10367 /**
10368 * Get the card closest to the specified card.
10369 *
10370 * @param {OO.ui.CardLayout} card Card to use as a reference point
10371 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10372 */
10373 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10374 var next, prev, level,
10375 cards = this.stackLayout.getItems(),
10376 index = cards.indexOf( card );
10377
10378 if ( index !== -1 ) {
10379 next = cards[ index + 1 ];
10380 prev = cards[ index - 1 ];
10381 // Prefer adjacent cards at the same level
10382 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10383 if (
10384 prev &&
10385 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10386 ) {
10387 return prev;
10388 }
10389 if (
10390 next &&
10391 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10392 ) {
10393 return next;
10394 }
10395 }
10396 return prev || next || null;
10397 };
10398
10399 /**
10400 * Get the tabs widget.
10401 *
10402 * @return {OO.ui.TabSelectWidget} Tabs widget
10403 */
10404 OO.ui.IndexLayout.prototype.getTabs = function () {
10405 return this.tabSelectWidget;
10406 };
10407
10408 /**
10409 * Get a card by its symbolic name.
10410 *
10411 * @param {string} name Symbolic name of card
10412 * @return {OO.ui.CardLayout|undefined} Card, if found
10413 */
10414 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10415 return this.cards[ name ];
10416 };
10417
10418 /**
10419 * Get the current card.
10420 *
10421 * @return {OO.ui.CardLayout|undefined} Current card, if found
10422 */
10423 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10424 var name = this.getCurrentCardName();
10425 return name ? this.getCard( name ) : undefined;
10426 };
10427
10428 /**
10429 * Get the symbolic name of the current card.
10430 *
10431 * @return {string|null} Symbolic name of the current card
10432 */
10433 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10434 return this.currentCardName;
10435 };
10436
10437 /**
10438 * Add cards to the index layout
10439 *
10440 * When cards are added with the same names as existing cards, the existing cards will be
10441 * automatically removed before the new cards are added.
10442 *
10443 * @param {OO.ui.CardLayout[]} cards Cards to add
10444 * @param {number} index Index of the insertion point
10445 * @fires add
10446 * @chainable
10447 */
10448 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10449 var i, len, name, card, item, currentIndex,
10450 stackLayoutCards = this.stackLayout.getItems(),
10451 remove = [],
10452 items = [];
10453
10454 // Remove cards with same names
10455 for ( i = 0, len = cards.length; i < len; i++ ) {
10456 card = cards[ i ];
10457 name = card.getName();
10458
10459 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10460 // Correct the insertion index
10461 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10462 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10463 index--;
10464 }
10465 remove.push( this.cards[ name ] );
10466 }
10467 }
10468 if ( remove.length ) {
10469 this.removeCards( remove );
10470 }
10471
10472 // Add new cards
10473 for ( i = 0, len = cards.length; i < len; i++ ) {
10474 card = cards[ i ];
10475 name = card.getName();
10476 this.cards[ card.getName() ] = card;
10477 item = new OO.ui.TabOptionWidget( { data: name } );
10478 card.setTabItem( item );
10479 items.push( item );
10480 }
10481
10482 if ( items.length ) {
10483 this.tabSelectWidget.addItems( items, index );
10484 this.selectFirstSelectableCard();
10485 }
10486 this.stackLayout.addItems( cards, index );
10487 this.emit( 'add', cards, index );
10488
10489 return this;
10490 };
10491
10492 /**
10493 * Remove the specified cards from the index layout.
10494 *
10495 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10496 *
10497 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10498 * @fires remove
10499 * @chainable
10500 */
10501 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10502 var i, len, name, card,
10503 items = [];
10504
10505 for ( i = 0, len = cards.length; i < len; i++ ) {
10506 card = cards[ i ];
10507 name = card.getName();
10508 delete this.cards[ name ];
10509 items.push( this.tabSelectWidget.getItemFromData( name ) );
10510 card.setTabItem( null );
10511 }
10512 if ( items.length ) {
10513 this.tabSelectWidget.removeItems( items );
10514 this.selectFirstSelectableCard();
10515 }
10516 this.stackLayout.removeItems( cards );
10517 this.emit( 'remove', cards );
10518
10519 return this;
10520 };
10521
10522 /**
10523 * Clear all cards from the index layout.
10524 *
10525 * To remove only a subset of cards from the index, use the #removeCards method.
10526 *
10527 * @fires remove
10528 * @chainable
10529 */
10530 OO.ui.IndexLayout.prototype.clearCards = function () {
10531 var i, len,
10532 cards = this.stackLayout.getItems();
10533
10534 this.cards = {};
10535 this.currentCardName = null;
10536 this.tabSelectWidget.clearItems();
10537 for ( i = 0, len = cards.length; i < len; i++ ) {
10538 cards[ i ].setTabItem( null );
10539 }
10540 this.stackLayout.clearItems();
10541
10542 this.emit( 'remove', cards );
10543
10544 return this;
10545 };
10546
10547 /**
10548 * Set the current card by symbolic name.
10549 *
10550 * @fires set
10551 * @param {string} name Symbolic name of card
10552 */
10553 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10554 var selectedItem,
10555 $focused,
10556 card = this.cards[ name ],
10557 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10558
10559 if ( name !== this.currentCardName ) {
10560 selectedItem = this.tabSelectWidget.getSelectedItem();
10561 if ( selectedItem && selectedItem.getData() !== name ) {
10562 this.tabSelectWidget.selectItemByData( name );
10563 }
10564 if ( card ) {
10565 if ( previousCard ) {
10566 previousCard.setActive( false );
10567 // Blur anything focused if the next card doesn't have anything focusable.
10568 // This is not needed if the next card has something focusable (because once it is focused
10569 // this blur happens automatically). If the layout is non-continuous, this check is
10570 // meaningless because the next card is not visible yet and thus can't hold focus.
10571 if (
10572 this.autoFocus &&
10573 this.stackLayout.continuous &&
10574 OO.ui.findFocusable( card.$element ).length !== 0
10575 ) {
10576 $focused = previousCard.$element.find( ':focus' );
10577 if ( $focused.length ) {
10578 $focused[ 0 ].blur();
10579 }
10580 }
10581 }
10582 this.currentCardName = name;
10583 card.setActive( true );
10584 this.stackLayout.setItem( card );
10585 if ( !this.stackLayout.continuous && previousCard ) {
10586 // This should not be necessary, since any inputs on the previous card should have been
10587 // blurred when it was hidden, but browsers are not very consistent about this.
10588 $focused = previousCard.$element.find( ':focus' );
10589 if ( $focused.length ) {
10590 $focused[ 0 ].blur();
10591 }
10592 }
10593 this.emit( 'set', card );
10594 }
10595 }
10596 };
10597
10598 /**
10599 * Select the first selectable card.
10600 *
10601 * @chainable
10602 */
10603 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10604 if ( !this.tabSelectWidget.getSelectedItem() ) {
10605 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10606 }
10607
10608 return this;
10609 };
10610
10611 /**
10612 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10613 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10614 *
10615 * @example
10616 * // Example of a panel layout
10617 * var panel = new OO.ui.PanelLayout( {
10618 * expanded: false,
10619 * framed: true,
10620 * padded: true,
10621 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10622 * } );
10623 * $( 'body' ).append( panel.$element );
10624 *
10625 * @class
10626 * @extends OO.ui.Layout
10627 *
10628 * @constructor
10629 * @param {Object} [config] Configuration options
10630 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10631 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10632 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10633 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10634 */
10635 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10636 // Configuration initialization
10637 config = $.extend( {
10638 scrollable: false,
10639 padded: false,
10640 expanded: true,
10641 framed: false
10642 }, config );
10643
10644 // Parent constructor
10645 OO.ui.PanelLayout.parent.call( this, config );
10646
10647 // Initialization
10648 this.$element.addClass( 'oo-ui-panelLayout' );
10649 if ( config.scrollable ) {
10650 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10651 }
10652 if ( config.padded ) {
10653 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10654 }
10655 if ( config.expanded ) {
10656 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10657 }
10658 if ( config.framed ) {
10659 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10660 }
10661 };
10662
10663 /* Setup */
10664
10665 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10666
10667 /* Methods */
10668
10669 /**
10670 * Focus the panel layout
10671 *
10672 * The default implementation just focuses the first focusable element in the panel
10673 */
10674 OO.ui.PanelLayout.prototype.focus = function () {
10675 OO.ui.findFocusable( this.$element ).focus();
10676 };
10677
10678 /**
10679 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10680 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10681 * rather extended to include the required content and functionality.
10682 *
10683 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10684 * item is customized (with a label) using the #setupTabItem method. See
10685 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10686 *
10687 * @class
10688 * @extends OO.ui.PanelLayout
10689 *
10690 * @constructor
10691 * @param {string} name Unique symbolic name of card
10692 * @param {Object} [config] Configuration options
10693 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10694 */
10695 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10696 // Allow passing positional parameters inside the config object
10697 if ( OO.isPlainObject( name ) && config === undefined ) {
10698 config = name;
10699 name = config.name;
10700 }
10701
10702 // Configuration initialization
10703 config = $.extend( { scrollable: true }, config );
10704
10705 // Parent constructor
10706 OO.ui.CardLayout.parent.call( this, config );
10707
10708 // Properties
10709 this.name = name;
10710 this.label = config.label;
10711 this.tabItem = null;
10712 this.active = false;
10713
10714 // Initialization
10715 this.$element.addClass( 'oo-ui-cardLayout' );
10716 };
10717
10718 /* Setup */
10719
10720 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10721
10722 /* Events */
10723
10724 /**
10725 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10726 * shown in a index layout that is configured to display only one card at a time.
10727 *
10728 * @event active
10729 * @param {boolean} active Card is active
10730 */
10731
10732 /* Methods */
10733
10734 /**
10735 * Get the symbolic name of the card.
10736 *
10737 * @return {string} Symbolic name of card
10738 */
10739 OO.ui.CardLayout.prototype.getName = function () {
10740 return this.name;
10741 };
10742
10743 /**
10744 * Check if card is active.
10745 *
10746 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10747 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10748 *
10749 * @return {boolean} Card is active
10750 */
10751 OO.ui.CardLayout.prototype.isActive = function () {
10752 return this.active;
10753 };
10754
10755 /**
10756 * Get tab item.
10757 *
10758 * The tab item allows users to access the card from the index's tab
10759 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10760 *
10761 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10762 */
10763 OO.ui.CardLayout.prototype.getTabItem = function () {
10764 return this.tabItem;
10765 };
10766
10767 /**
10768 * Set or unset the tab item.
10769 *
10770 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10771 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10772 * level), use #setupTabItem instead of this method.
10773 *
10774 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10775 * @chainable
10776 */
10777 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10778 this.tabItem = tabItem || null;
10779 if ( tabItem ) {
10780 this.setupTabItem();
10781 }
10782 return this;
10783 };
10784
10785 /**
10786 * Set up the tab item.
10787 *
10788 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10789 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10790 * the #setTabItem method instead.
10791 *
10792 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10793 * @chainable
10794 */
10795 OO.ui.CardLayout.prototype.setupTabItem = function () {
10796 if ( this.label ) {
10797 this.tabItem.setLabel( this.label );
10798 }
10799 return this;
10800 };
10801
10802 /**
10803 * Set the card to its 'active' state.
10804 *
10805 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10806 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10807 * context, setting the active state on a card does nothing.
10808 *
10809 * @param {boolean} value Card is active
10810 * @fires active
10811 */
10812 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10813 active = !!active;
10814
10815 if ( active !== this.active ) {
10816 this.active = active;
10817 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10818 this.emit( 'active', this.active );
10819 }
10820 };
10821
10822 /**
10823 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10824 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10825 * rather extended to include the required content and functionality.
10826 *
10827 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10828 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10829 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10830 *
10831 * @class
10832 * @extends OO.ui.PanelLayout
10833 *
10834 * @constructor
10835 * @param {string} name Unique symbolic name of page
10836 * @param {Object} [config] Configuration options
10837 */
10838 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10839 // Allow passing positional parameters inside the config object
10840 if ( OO.isPlainObject( name ) && config === undefined ) {
10841 config = name;
10842 name = config.name;
10843 }
10844
10845 // Configuration initialization
10846 config = $.extend( { scrollable: true }, config );
10847
10848 // Parent constructor
10849 OO.ui.PageLayout.parent.call( this, config );
10850
10851 // Properties
10852 this.name = name;
10853 this.outlineItem = null;
10854 this.active = false;
10855
10856 // Initialization
10857 this.$element.addClass( 'oo-ui-pageLayout' );
10858 };
10859
10860 /* Setup */
10861
10862 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10863
10864 /* Events */
10865
10866 /**
10867 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10868 * shown in a booklet layout that is configured to display only one page at a time.
10869 *
10870 * @event active
10871 * @param {boolean} active Page is active
10872 */
10873
10874 /* Methods */
10875
10876 /**
10877 * Get the symbolic name of the page.
10878 *
10879 * @return {string} Symbolic name of page
10880 */
10881 OO.ui.PageLayout.prototype.getName = function () {
10882 return this.name;
10883 };
10884
10885 /**
10886 * Check if page is active.
10887 *
10888 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10889 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10890 *
10891 * @return {boolean} Page is active
10892 */
10893 OO.ui.PageLayout.prototype.isActive = function () {
10894 return this.active;
10895 };
10896
10897 /**
10898 * Get outline item.
10899 *
10900 * The outline item allows users to access the page from the booklet's outline
10901 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10902 *
10903 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10904 */
10905 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10906 return this.outlineItem;
10907 };
10908
10909 /**
10910 * Set or unset the outline item.
10911 *
10912 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10913 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10914 * level), use #setupOutlineItem instead of this method.
10915 *
10916 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10917 * @chainable
10918 */
10919 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10920 this.outlineItem = outlineItem || null;
10921 if ( outlineItem ) {
10922 this.setupOutlineItem();
10923 }
10924 return this;
10925 };
10926
10927 /**
10928 * Set up the outline item.
10929 *
10930 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10931 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10932 * the #setOutlineItem method instead.
10933 *
10934 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10935 * @chainable
10936 */
10937 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10938 return this;
10939 };
10940
10941 /**
10942 * Set the page to its 'active' state.
10943 *
10944 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10945 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10946 * context, setting the active state on a page does nothing.
10947 *
10948 * @param {boolean} value Page is active
10949 * @fires active
10950 */
10951 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10952 active = !!active;
10953
10954 if ( active !== this.active ) {
10955 this.active = active;
10956 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10957 this.emit( 'active', this.active );
10958 }
10959 };
10960
10961 /**
10962 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10963 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10964 * by setting the #continuous option to 'true'.
10965 *
10966 * @example
10967 * // A stack layout with two panels, configured to be displayed continously
10968 * var myStack = new OO.ui.StackLayout( {
10969 * items: [
10970 * new OO.ui.PanelLayout( {
10971 * $content: $( '<p>Panel One</p>' ),
10972 * padded: true,
10973 * framed: true
10974 * } ),
10975 * new OO.ui.PanelLayout( {
10976 * $content: $( '<p>Panel Two</p>' ),
10977 * padded: true,
10978 * framed: true
10979 * } )
10980 * ],
10981 * continuous: true
10982 * } );
10983 * $( 'body' ).append( myStack.$element );
10984 *
10985 * @class
10986 * @extends OO.ui.PanelLayout
10987 * @mixins OO.ui.mixin.GroupElement
10988 *
10989 * @constructor
10990 * @param {Object} [config] Configuration options
10991 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10992 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10993 */
10994 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10995 // Configuration initialization
10996 config = $.extend( { scrollable: true }, config );
10997
10998 // Parent constructor
10999 OO.ui.StackLayout.parent.call( this, config );
11000
11001 // Mixin constructors
11002 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11003
11004 // Properties
11005 this.currentItem = null;
11006 this.continuous = !!config.continuous;
11007
11008 // Initialization
11009 this.$element.addClass( 'oo-ui-stackLayout' );
11010 if ( this.continuous ) {
11011 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11012 }
11013 if ( Array.isArray( config.items ) ) {
11014 this.addItems( config.items );
11015 }
11016 };
11017
11018 /* Setup */
11019
11020 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11021 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11022
11023 /* Events */
11024
11025 /**
11026 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11027 * {@link #clearItems cleared} or {@link #setItem displayed}.
11028 *
11029 * @event set
11030 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11031 */
11032
11033 /* Methods */
11034
11035 /**
11036 * Get the current panel.
11037 *
11038 * @return {OO.ui.Layout|null}
11039 */
11040 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11041 return this.currentItem;
11042 };
11043
11044 /**
11045 * Unset the current item.
11046 *
11047 * @private
11048 * @param {OO.ui.StackLayout} layout
11049 * @fires set
11050 */
11051 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11052 var prevItem = this.currentItem;
11053 if ( prevItem === null ) {
11054 return;
11055 }
11056
11057 this.currentItem = null;
11058 this.emit( 'set', null );
11059 };
11060
11061 /**
11062 * Add panel layouts to the stack layout.
11063 *
11064 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11065 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11066 * by the index.
11067 *
11068 * @param {OO.ui.Layout[]} items Panels to add
11069 * @param {number} [index] Index of the insertion point
11070 * @chainable
11071 */
11072 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11073 // Update the visibility
11074 this.updateHiddenState( items, this.currentItem );
11075
11076 // Mixin method
11077 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11078
11079 if ( !this.currentItem && items.length ) {
11080 this.setItem( items[ 0 ] );
11081 }
11082
11083 return this;
11084 };
11085
11086 /**
11087 * Remove the specified panels from the stack layout.
11088 *
11089 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11090 * you may wish to use the #clearItems method instead.
11091 *
11092 * @param {OO.ui.Layout[]} items Panels to remove
11093 * @chainable
11094 * @fires set
11095 */
11096 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11097 // Mixin method
11098 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11099
11100 if ( items.indexOf( this.currentItem ) !== -1 ) {
11101 if ( this.items.length ) {
11102 this.setItem( this.items[ 0 ] );
11103 } else {
11104 this.unsetCurrentItem();
11105 }
11106 }
11107
11108 return this;
11109 };
11110
11111 /**
11112 * Clear all panels from the stack layout.
11113 *
11114 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11115 * a subset of panels, use the #removeItems method.
11116 *
11117 * @chainable
11118 * @fires set
11119 */
11120 OO.ui.StackLayout.prototype.clearItems = function () {
11121 this.unsetCurrentItem();
11122 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11123
11124 return this;
11125 };
11126
11127 /**
11128 * Show the specified panel.
11129 *
11130 * If another panel is currently displayed, it will be hidden.
11131 *
11132 * @param {OO.ui.Layout} item Panel to show
11133 * @chainable
11134 * @fires set
11135 */
11136 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11137 if ( item !== this.currentItem ) {
11138 this.updateHiddenState( this.items, item );
11139
11140 if ( this.items.indexOf( item ) !== -1 ) {
11141 this.currentItem = item;
11142 this.emit( 'set', item );
11143 } else {
11144 this.unsetCurrentItem();
11145 }
11146 }
11147
11148 return this;
11149 };
11150
11151 /**
11152 * Update the visibility of all items in case of non-continuous view.
11153 *
11154 * Ensure all items are hidden except for the selected one.
11155 * This method does nothing when the stack is continuous.
11156 *
11157 * @private
11158 * @param {OO.ui.Layout[]} items Item list iterate over
11159 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11160 */
11161 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11162 var i, len;
11163
11164 if ( !this.continuous ) {
11165 for ( i = 0, len = items.length; i < len; i++ ) {
11166 if ( !selectedItem || selectedItem !== items[ i ] ) {
11167 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11168 }
11169 }
11170 if ( selectedItem ) {
11171 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11172 }
11173 }
11174 };
11175
11176 /**
11177 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11178 * items), with small margins between them. Convenient when you need to put a number of block-level
11179 * widgets on a single line next to each other.
11180 *
11181 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11182 *
11183 * @example
11184 * // HorizontalLayout with a text input and a label
11185 * var layout = new OO.ui.HorizontalLayout( {
11186 * items: [
11187 * new OO.ui.LabelWidget( { label: 'Label' } ),
11188 * new OO.ui.TextInputWidget( { value: 'Text' } )
11189 * ]
11190 * } );
11191 * $( 'body' ).append( layout.$element );
11192 *
11193 * @class
11194 * @extends OO.ui.Layout
11195 * @mixins OO.ui.mixin.GroupElement
11196 *
11197 * @constructor
11198 * @param {Object} [config] Configuration options
11199 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11200 */
11201 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11202 // Configuration initialization
11203 config = config || {};
11204
11205 // Parent constructor
11206 OO.ui.HorizontalLayout.parent.call( this, config );
11207
11208 // Mixin constructors
11209 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11210
11211 // Initialization
11212 this.$element.addClass( 'oo-ui-horizontalLayout' );
11213 if ( Array.isArray( config.items ) ) {
11214 this.addItems( config.items );
11215 }
11216 };
11217
11218 /* Setup */
11219
11220 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11221 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11222
11223 /**
11224 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11225 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11226 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11227 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11228 * the tool.
11229 *
11230 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11231 * set up.
11232 *
11233 * @example
11234 * // Example of a BarToolGroup with two tools
11235 * var toolFactory = new OO.ui.ToolFactory();
11236 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11237 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11238 *
11239 * // We will be placing status text in this element when tools are used
11240 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11241 *
11242 * // Define the tools that we're going to place in our toolbar
11243 *
11244 * // Create a class inheriting from OO.ui.Tool
11245 * function PictureTool() {
11246 * PictureTool.parent.apply( this, arguments );
11247 * }
11248 * OO.inheritClass( PictureTool, OO.ui.Tool );
11249 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11250 * // of 'icon' and 'title' (displayed icon and text).
11251 * PictureTool.static.name = 'picture';
11252 * PictureTool.static.icon = 'picture';
11253 * PictureTool.static.title = 'Insert picture';
11254 * // Defines the action that will happen when this tool is selected (clicked).
11255 * PictureTool.prototype.onSelect = function () {
11256 * $area.text( 'Picture tool clicked!' );
11257 * // Never display this tool as "active" (selected).
11258 * this.setActive( false );
11259 * };
11260 * // Make this tool available in our toolFactory and thus our toolbar
11261 * toolFactory.register( PictureTool );
11262 *
11263 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11264 * // little popup window (a PopupWidget).
11265 * function HelpTool( toolGroup, config ) {
11266 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11267 * padded: true,
11268 * label: 'Help',
11269 * head: true
11270 * } }, config ) );
11271 * this.popup.$body.append( '<p>I am helpful!</p>' );
11272 * }
11273 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11274 * HelpTool.static.name = 'help';
11275 * HelpTool.static.icon = 'help';
11276 * HelpTool.static.title = 'Help';
11277 * toolFactory.register( HelpTool );
11278 *
11279 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11280 * // used once (but not all defined tools must be used).
11281 * toolbar.setup( [
11282 * {
11283 * // 'bar' tool groups display tools by icon only
11284 * type: 'bar',
11285 * include: [ 'picture', 'help' ]
11286 * }
11287 * ] );
11288 *
11289 * // Create some UI around the toolbar and place it in the document
11290 * var frame = new OO.ui.PanelLayout( {
11291 * expanded: false,
11292 * framed: true
11293 * } );
11294 * var contentFrame = new OO.ui.PanelLayout( {
11295 * expanded: false,
11296 * padded: true
11297 * } );
11298 * frame.$element.append(
11299 * toolbar.$element,
11300 * contentFrame.$element.append( $area )
11301 * );
11302 * $( 'body' ).append( frame.$element );
11303 *
11304 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11305 * // document.
11306 * toolbar.initialize();
11307 *
11308 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11309 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11310 *
11311 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11312 *
11313 * @class
11314 * @extends OO.ui.ToolGroup
11315 *
11316 * @constructor
11317 * @param {OO.ui.Toolbar} toolbar
11318 * @param {Object} [config] Configuration options
11319 */
11320 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11321 // Allow passing positional parameters inside the config object
11322 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11323 config = toolbar;
11324 toolbar = config.toolbar;
11325 }
11326
11327 // Parent constructor
11328 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11329
11330 // Initialization
11331 this.$element.addClass( 'oo-ui-barToolGroup' );
11332 };
11333
11334 /* Setup */
11335
11336 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11337
11338 /* Static Properties */
11339
11340 OO.ui.BarToolGroup.static.titleTooltips = true;
11341
11342 OO.ui.BarToolGroup.static.accelTooltips = true;
11343
11344 OO.ui.BarToolGroup.static.name = 'bar';
11345
11346 /**
11347 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11348 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11349 * optional icon and label. This class can be used for other base classes that also use this functionality.
11350 *
11351 * @abstract
11352 * @class
11353 * @extends OO.ui.ToolGroup
11354 * @mixins OO.ui.mixin.IconElement
11355 * @mixins OO.ui.mixin.IndicatorElement
11356 * @mixins OO.ui.mixin.LabelElement
11357 * @mixins OO.ui.mixin.TitledElement
11358 * @mixins OO.ui.mixin.ClippableElement
11359 * @mixins OO.ui.mixin.TabIndexedElement
11360 *
11361 * @constructor
11362 * @param {OO.ui.Toolbar} toolbar
11363 * @param {Object} [config] Configuration options
11364 * @cfg {string} [header] Text to display at the top of the popup
11365 */
11366 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11367 // Allow passing positional parameters inside the config object
11368 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11369 config = toolbar;
11370 toolbar = config.toolbar;
11371 }
11372
11373 // Configuration initialization
11374 config = config || {};
11375
11376 // Parent constructor
11377 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11378
11379 // Properties
11380 this.active = false;
11381 this.dragging = false;
11382 this.onBlurHandler = this.onBlur.bind( this );
11383 this.$handle = $( '<span>' );
11384
11385 // Mixin constructors
11386 OO.ui.mixin.IconElement.call( this, config );
11387 OO.ui.mixin.IndicatorElement.call( this, config );
11388 OO.ui.mixin.LabelElement.call( this, config );
11389 OO.ui.mixin.TitledElement.call( this, config );
11390 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11391 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11392
11393 // Events
11394 this.$handle.on( {
11395 keydown: this.onHandleMouseKeyDown.bind( this ),
11396 keyup: this.onHandleMouseKeyUp.bind( this ),
11397 mousedown: this.onHandleMouseKeyDown.bind( this ),
11398 mouseup: this.onHandleMouseKeyUp.bind( this )
11399 } );
11400
11401 // Initialization
11402 this.$handle
11403 .addClass( 'oo-ui-popupToolGroup-handle' )
11404 .append( this.$icon, this.$label, this.$indicator );
11405 // If the pop-up should have a header, add it to the top of the toolGroup.
11406 // Note: If this feature is useful for other widgets, we could abstract it into an
11407 // OO.ui.HeaderedElement mixin constructor.
11408 if ( config.header !== undefined ) {
11409 this.$group
11410 .prepend( $( '<span>' )
11411 .addClass( 'oo-ui-popupToolGroup-header' )
11412 .text( config.header )
11413 );
11414 }
11415 this.$element
11416 .addClass( 'oo-ui-popupToolGroup' )
11417 .prepend( this.$handle );
11418 };
11419
11420 /* Setup */
11421
11422 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11423 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11424 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11425 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11426 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11427 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11428 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11429
11430 /* Methods */
11431
11432 /**
11433 * @inheritdoc
11434 */
11435 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11436 // Parent method
11437 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11438
11439 if ( this.isDisabled() && this.isElementAttached() ) {
11440 this.setActive( false );
11441 }
11442 };
11443
11444 /**
11445 * Handle focus being lost.
11446 *
11447 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11448 *
11449 * @protected
11450 * @param {jQuery.Event} e Mouse up or key up event
11451 */
11452 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11453 // Only deactivate when clicking outside the dropdown element
11454 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11455 this.setActive( false );
11456 }
11457 };
11458
11459 /**
11460 * @inheritdoc
11461 */
11462 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11463 // Only close toolgroup when a tool was actually selected
11464 if (
11465 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11466 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11467 ) {
11468 this.setActive( false );
11469 }
11470 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11471 };
11472
11473 /**
11474 * Handle mouse up and key up events.
11475 *
11476 * @protected
11477 * @param {jQuery.Event} e Mouse up or key up event
11478 */
11479 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11480 if (
11481 !this.isDisabled() &&
11482 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11483 ) {
11484 return false;
11485 }
11486 };
11487
11488 /**
11489 * Handle mouse down and key down events.
11490 *
11491 * @protected
11492 * @param {jQuery.Event} e Mouse down or key down event
11493 */
11494 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11495 if (
11496 !this.isDisabled() &&
11497 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11498 ) {
11499 this.setActive( !this.active );
11500 return false;
11501 }
11502 };
11503
11504 /**
11505 * Switch into 'active' mode.
11506 *
11507 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11508 * deactivation.
11509 */
11510 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11511 var containerWidth, containerLeft;
11512 value = !!value;
11513 if ( this.active !== value ) {
11514 this.active = value;
11515 if ( value ) {
11516 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11517 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11518
11519 this.$clippable.css( 'left', '' );
11520 // Try anchoring the popup to the left first
11521 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11522 this.toggleClipping( true );
11523 if ( this.isClippedHorizontally() ) {
11524 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11525 this.toggleClipping( false );
11526 this.$element
11527 .removeClass( 'oo-ui-popupToolGroup-left' )
11528 .addClass( 'oo-ui-popupToolGroup-right' );
11529 this.toggleClipping( true );
11530 }
11531 if ( this.isClippedHorizontally() ) {
11532 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11533 containerWidth = this.$clippableScrollableContainer.width();
11534 containerLeft = this.$clippableScrollableContainer.offset().left;
11535
11536 this.toggleClipping( false );
11537 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11538
11539 this.$clippable.css( {
11540 left: -( this.$element.offset().left - containerLeft ),
11541 width: containerWidth
11542 } );
11543 }
11544 } else {
11545 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11546 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11547 this.$element.removeClass(
11548 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11549 );
11550 this.toggleClipping( false );
11551 }
11552 }
11553 };
11554
11555 /**
11556 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11557 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11558 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11559 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11560 * with a label, icon, indicator, header, and title.
11561 *
11562 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11563 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11564 * users to collapse the list again.
11565 *
11566 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11567 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11568 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11569 *
11570 * @example
11571 * // Example of a ListToolGroup
11572 * var toolFactory = new OO.ui.ToolFactory();
11573 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11574 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11575 *
11576 * // Configure and register two tools
11577 * function SettingsTool() {
11578 * SettingsTool.parent.apply( this, arguments );
11579 * }
11580 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11581 * SettingsTool.static.name = 'settings';
11582 * SettingsTool.static.icon = 'settings';
11583 * SettingsTool.static.title = 'Change settings';
11584 * SettingsTool.prototype.onSelect = function () {
11585 * this.setActive( false );
11586 * };
11587 * toolFactory.register( SettingsTool );
11588 * // Register two more tools, nothing interesting here
11589 * function StuffTool() {
11590 * StuffTool.parent.apply( this, arguments );
11591 * }
11592 * OO.inheritClass( StuffTool, OO.ui.Tool );
11593 * StuffTool.static.name = 'stuff';
11594 * StuffTool.static.icon = 'ellipsis';
11595 * StuffTool.static.title = 'Change the world';
11596 * StuffTool.prototype.onSelect = function () {
11597 * this.setActive( false );
11598 * };
11599 * toolFactory.register( StuffTool );
11600 * toolbar.setup( [
11601 * {
11602 * // Configurations for list toolgroup.
11603 * type: 'list',
11604 * label: 'ListToolGroup',
11605 * indicator: 'down',
11606 * icon: 'picture',
11607 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11608 * header: 'This is the header',
11609 * include: [ 'settings', 'stuff' ],
11610 * allowCollapse: ['stuff']
11611 * }
11612 * ] );
11613 *
11614 * // Create some UI around the toolbar and place it in the document
11615 * var frame = new OO.ui.PanelLayout( {
11616 * expanded: false,
11617 * framed: true
11618 * } );
11619 * frame.$element.append(
11620 * toolbar.$element
11621 * );
11622 * $( 'body' ).append( frame.$element );
11623 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11624 * toolbar.initialize();
11625 *
11626 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11627 *
11628 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11629 *
11630 * @class
11631 * @extends OO.ui.PopupToolGroup
11632 *
11633 * @constructor
11634 * @param {OO.ui.Toolbar} toolbar
11635 * @param {Object} [config] Configuration options
11636 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11637 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11638 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11639 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11640 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11641 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11642 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11643 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11644 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11645 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11646 */
11647 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11648 // Allow passing positional parameters inside the config object
11649 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11650 config = toolbar;
11651 toolbar = config.toolbar;
11652 }
11653
11654 // Configuration initialization
11655 config = config || {};
11656
11657 // Properties (must be set before parent constructor, which calls #populate)
11658 this.allowCollapse = config.allowCollapse;
11659 this.forceExpand = config.forceExpand;
11660 this.expanded = config.expanded !== undefined ? config.expanded : false;
11661 this.collapsibleTools = [];
11662
11663 // Parent constructor
11664 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11665
11666 // Initialization
11667 this.$element.addClass( 'oo-ui-listToolGroup' );
11668 };
11669
11670 /* Setup */
11671
11672 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11673
11674 /* Static Properties */
11675
11676 OO.ui.ListToolGroup.static.name = 'list';
11677
11678 /* Methods */
11679
11680 /**
11681 * @inheritdoc
11682 */
11683 OO.ui.ListToolGroup.prototype.populate = function () {
11684 var i, len, allowCollapse = [];
11685
11686 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11687
11688 // Update the list of collapsible tools
11689 if ( this.allowCollapse !== undefined ) {
11690 allowCollapse = this.allowCollapse;
11691 } else if ( this.forceExpand !== undefined ) {
11692 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11693 }
11694
11695 this.collapsibleTools = [];
11696 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11697 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11698 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11699 }
11700 }
11701
11702 // Keep at the end, even when tools are added
11703 this.$group.append( this.getExpandCollapseTool().$element );
11704
11705 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11706 this.updateCollapsibleState();
11707 };
11708
11709 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11710 var ExpandCollapseTool;
11711 if ( this.expandCollapseTool === undefined ) {
11712 ExpandCollapseTool = function () {
11713 ExpandCollapseTool.parent.apply( this, arguments );
11714 };
11715
11716 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11717
11718 ExpandCollapseTool.prototype.onSelect = function () {
11719 this.toolGroup.expanded = !this.toolGroup.expanded;
11720 this.toolGroup.updateCollapsibleState();
11721 this.setActive( false );
11722 };
11723 ExpandCollapseTool.prototype.onUpdateState = function () {
11724 // Do nothing. Tool interface requires an implementation of this function.
11725 };
11726
11727 ExpandCollapseTool.static.name = 'more-fewer';
11728
11729 this.expandCollapseTool = new ExpandCollapseTool( this );
11730 }
11731 return this.expandCollapseTool;
11732 };
11733
11734 /**
11735 * @inheritdoc
11736 */
11737 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11738 // Do not close the popup when the user wants to show more/fewer tools
11739 if (
11740 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11741 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11742 ) {
11743 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11744 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11745 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11746 } else {
11747 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11748 }
11749 };
11750
11751 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11752 var i, len;
11753
11754 this.getExpandCollapseTool()
11755 .setIcon( this.expanded ? 'collapse' : 'expand' )
11756 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11757
11758 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11759 this.collapsibleTools[ i ].toggle( this.expanded );
11760 }
11761 };
11762
11763 /**
11764 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11765 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11766 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11767 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11768 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11769 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11770 *
11771 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11772 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11773 * a MenuToolGroup is used.
11774 *
11775 * @example
11776 * // Example of a MenuToolGroup
11777 * var toolFactory = new OO.ui.ToolFactory();
11778 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11779 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11780 *
11781 * // We will be placing status text in this element when tools are used
11782 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11783 *
11784 * // Define the tools that we're going to place in our toolbar
11785 *
11786 * function SettingsTool() {
11787 * SettingsTool.parent.apply( this, arguments );
11788 * this.reallyActive = false;
11789 * }
11790 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11791 * SettingsTool.static.name = 'settings';
11792 * SettingsTool.static.icon = 'settings';
11793 * SettingsTool.static.title = 'Change settings';
11794 * SettingsTool.prototype.onSelect = function () {
11795 * $area.text( 'Settings tool clicked!' );
11796 * // Toggle the active state on each click
11797 * this.reallyActive = !this.reallyActive;
11798 * this.setActive( this.reallyActive );
11799 * // To update the menu label
11800 * this.toolbar.emit( 'updateState' );
11801 * };
11802 * SettingsTool.prototype.onUpdateState = function () {
11803 * };
11804 * toolFactory.register( SettingsTool );
11805 *
11806 * function StuffTool() {
11807 * StuffTool.parent.apply( this, arguments );
11808 * this.reallyActive = false;
11809 * }
11810 * OO.inheritClass( StuffTool, OO.ui.Tool );
11811 * StuffTool.static.name = 'stuff';
11812 * StuffTool.static.icon = 'ellipsis';
11813 * StuffTool.static.title = 'More stuff';
11814 * StuffTool.prototype.onSelect = function () {
11815 * $area.text( 'More stuff tool clicked!' );
11816 * // Toggle the active state on each click
11817 * this.reallyActive = !this.reallyActive;
11818 * this.setActive( this.reallyActive );
11819 * // To update the menu label
11820 * this.toolbar.emit( 'updateState' );
11821 * };
11822 * StuffTool.prototype.onUpdateState = function () {
11823 * };
11824 * toolFactory.register( StuffTool );
11825 *
11826 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11827 * // used once (but not all defined tools must be used).
11828 * toolbar.setup( [
11829 * {
11830 * type: 'menu',
11831 * header: 'This is the (optional) header',
11832 * title: 'This is the (optional) title',
11833 * indicator: 'down',
11834 * include: [ 'settings', 'stuff' ]
11835 * }
11836 * ] );
11837 *
11838 * // Create some UI around the toolbar and place it in the document
11839 * var frame = new OO.ui.PanelLayout( {
11840 * expanded: false,
11841 * framed: true
11842 * } );
11843 * var contentFrame = new OO.ui.PanelLayout( {
11844 * expanded: false,
11845 * padded: true
11846 * } );
11847 * frame.$element.append(
11848 * toolbar.$element,
11849 * contentFrame.$element.append( $area )
11850 * );
11851 * $( 'body' ).append( frame.$element );
11852 *
11853 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11854 * // document.
11855 * toolbar.initialize();
11856 * toolbar.emit( 'updateState' );
11857 *
11858 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11859 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11860 *
11861 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11862 *
11863 * @class
11864 * @extends OO.ui.PopupToolGroup
11865 *
11866 * @constructor
11867 * @param {OO.ui.Toolbar} toolbar
11868 * @param {Object} [config] Configuration options
11869 */
11870 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11871 // Allow passing positional parameters inside the config object
11872 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11873 config = toolbar;
11874 toolbar = config.toolbar;
11875 }
11876
11877 // Configuration initialization
11878 config = config || {};
11879
11880 // Parent constructor
11881 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11882
11883 // Events
11884 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11885
11886 // Initialization
11887 this.$element.addClass( 'oo-ui-menuToolGroup' );
11888 };
11889
11890 /* Setup */
11891
11892 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11893
11894 /* Static Properties */
11895
11896 OO.ui.MenuToolGroup.static.name = 'menu';
11897
11898 /* Methods */
11899
11900 /**
11901 * Handle the toolbar state being updated.
11902 *
11903 * When the state changes, the title of each active item in the menu will be joined together and
11904 * used as a label for the group. The label will be empty if none of the items are active.
11905 *
11906 * @private
11907 */
11908 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11909 var name,
11910 labelTexts = [];
11911
11912 for ( name in this.tools ) {
11913 if ( this.tools[ name ].isActive() ) {
11914 labelTexts.push( this.tools[ name ].getTitle() );
11915 }
11916 }
11917
11918 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11919 };
11920
11921 /**
11922 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11923 * 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
11924 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11925 *
11926 * // Example of a popup tool. When selected, a popup tool displays
11927 * // a popup window.
11928 * function HelpTool( toolGroup, config ) {
11929 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11930 * padded: true,
11931 * label: 'Help',
11932 * head: true
11933 * } }, config ) );
11934 * this.popup.$body.append( '<p>I am helpful!</p>' );
11935 * };
11936 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11937 * HelpTool.static.name = 'help';
11938 * HelpTool.static.icon = 'help';
11939 * HelpTool.static.title = 'Help';
11940 * toolFactory.register( HelpTool );
11941 *
11942 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11943 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11944 *
11945 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11946 *
11947 * @abstract
11948 * @class
11949 * @extends OO.ui.Tool
11950 * @mixins OO.ui.mixin.PopupElement
11951 *
11952 * @constructor
11953 * @param {OO.ui.ToolGroup} toolGroup
11954 * @param {Object} [config] Configuration options
11955 */
11956 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11957 // Allow passing positional parameters inside the config object
11958 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11959 config = toolGroup;
11960 toolGroup = config.toolGroup;
11961 }
11962
11963 // Parent constructor
11964 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11965
11966 // Mixin constructors
11967 OO.ui.mixin.PopupElement.call( this, config );
11968
11969 // Initialization
11970 this.$element
11971 .addClass( 'oo-ui-popupTool' )
11972 .append( this.popup.$element );
11973 };
11974
11975 /* Setup */
11976
11977 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11978 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11979
11980 /* Methods */
11981
11982 /**
11983 * Handle the tool being selected.
11984 *
11985 * @inheritdoc
11986 */
11987 OO.ui.PopupTool.prototype.onSelect = function () {
11988 if ( !this.isDisabled() ) {
11989 this.popup.toggle();
11990 }
11991 this.setActive( false );
11992 return false;
11993 };
11994
11995 /**
11996 * Handle the toolbar state being updated.
11997 *
11998 * @inheritdoc
11999 */
12000 OO.ui.PopupTool.prototype.onUpdateState = function () {
12001 this.setActive( false );
12002 };
12003
12004 /**
12005 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12006 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12007 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12008 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12009 * when the ToolGroupTool is selected.
12010 *
12011 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12012 *
12013 * function SettingsTool() {
12014 * SettingsTool.parent.apply( this, arguments );
12015 * };
12016 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12017 * SettingsTool.static.name = 'settings';
12018 * SettingsTool.static.title = 'Change settings';
12019 * SettingsTool.static.groupConfig = {
12020 * icon: 'settings',
12021 * label: 'ToolGroupTool',
12022 * include: [ 'setting1', 'setting2' ]
12023 * };
12024 * toolFactory.register( SettingsTool );
12025 *
12026 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12027 *
12028 * Please note that this implementation is subject to change per [T74159] [2].
12029 *
12030 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12031 * [2]: https://phabricator.wikimedia.org/T74159
12032 *
12033 * @abstract
12034 * @class
12035 * @extends OO.ui.Tool
12036 *
12037 * @constructor
12038 * @param {OO.ui.ToolGroup} toolGroup
12039 * @param {Object} [config] Configuration options
12040 */
12041 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12042 // Allow passing positional parameters inside the config object
12043 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12044 config = toolGroup;
12045 toolGroup = config.toolGroup;
12046 }
12047
12048 // Parent constructor
12049 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12050
12051 // Properties
12052 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12053
12054 // Events
12055 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12056
12057 // Initialization
12058 this.$link.remove();
12059 this.$element
12060 .addClass( 'oo-ui-toolGroupTool' )
12061 .append( this.innerToolGroup.$element );
12062 };
12063
12064 /* Setup */
12065
12066 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12067
12068 /* Static Properties */
12069
12070 /**
12071 * Toolgroup configuration.
12072 *
12073 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12074 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12075 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12076 *
12077 * @property {Object.<string,Array>}
12078 */
12079 OO.ui.ToolGroupTool.static.groupConfig = {};
12080
12081 /* Methods */
12082
12083 /**
12084 * Handle the tool being selected.
12085 *
12086 * @inheritdoc
12087 */
12088 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12089 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12090 return false;
12091 };
12092
12093 /**
12094 * Synchronize disabledness state of the tool with the inner toolgroup.
12095 *
12096 * @private
12097 * @param {boolean} disabled Element is disabled
12098 */
12099 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12100 this.setDisabled( disabled );
12101 };
12102
12103 /**
12104 * Handle the toolbar state being updated.
12105 *
12106 * @inheritdoc
12107 */
12108 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12109 this.setActive( false );
12110 };
12111
12112 /**
12113 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12114 *
12115 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12116 * more information.
12117 * @return {OO.ui.ListToolGroup}
12118 */
12119 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12120 if ( group.include === '*' ) {
12121 // Apply defaults to catch-all groups
12122 if ( group.label === undefined ) {
12123 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12124 }
12125 }
12126
12127 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12128 };
12129
12130 /**
12131 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12132 *
12133 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12134 *
12135 * @private
12136 * @abstract
12137 * @class
12138 * @extends OO.ui.mixin.GroupElement
12139 *
12140 * @constructor
12141 * @param {Object} [config] Configuration options
12142 */
12143 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12144 // Parent constructor
12145 OO.ui.mixin.GroupWidget.parent.call( this, config );
12146 };
12147
12148 /* Setup */
12149
12150 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12151
12152 /* Methods */
12153
12154 /**
12155 * Set the disabled state of the widget.
12156 *
12157 * This will also update the disabled state of child widgets.
12158 *
12159 * @param {boolean} disabled Disable widget
12160 * @chainable
12161 */
12162 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12163 var i, len;
12164
12165 // Parent method
12166 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12167 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12168
12169 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12170 if ( this.items ) {
12171 for ( i = 0, len = this.items.length; i < len; i++ ) {
12172 this.items[ i ].updateDisabled();
12173 }
12174 }
12175
12176 return this;
12177 };
12178
12179 /**
12180 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12181 *
12182 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12183 * allows bidirectional communication.
12184 *
12185 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12186 *
12187 * @private
12188 * @abstract
12189 * @class
12190 *
12191 * @constructor
12192 */
12193 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12194 //
12195 };
12196
12197 /* Methods */
12198
12199 /**
12200 * Check if widget is disabled.
12201 *
12202 * Checks parent if present, making disabled state inheritable.
12203 *
12204 * @return {boolean} Widget is disabled
12205 */
12206 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12207 return this.disabled ||
12208 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12209 };
12210
12211 /**
12212 * Set group element is in.
12213 *
12214 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12215 * @chainable
12216 */
12217 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12218 // Parent method
12219 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12220 OO.ui.Element.prototype.setElementGroup.call( this, group );
12221
12222 // Initialize item disabled states
12223 this.updateDisabled();
12224
12225 return this;
12226 };
12227
12228 /**
12229 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12230 * Controls include moving items up and down, removing items, and adding different kinds of items.
12231 *
12232 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12233 *
12234 * @class
12235 * @extends OO.ui.Widget
12236 * @mixins OO.ui.mixin.GroupElement
12237 * @mixins OO.ui.mixin.IconElement
12238 *
12239 * @constructor
12240 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12241 * @param {Object} [config] Configuration options
12242 * @cfg {Object} [abilities] List of abilties
12243 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12244 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12245 */
12246 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12247 // Allow passing positional parameters inside the config object
12248 if ( OO.isPlainObject( outline ) && config === undefined ) {
12249 config = outline;
12250 outline = config.outline;
12251 }
12252
12253 // Configuration initialization
12254 config = $.extend( { icon: 'add' }, config );
12255
12256 // Parent constructor
12257 OO.ui.OutlineControlsWidget.parent.call( this, config );
12258
12259 // Mixin constructors
12260 OO.ui.mixin.GroupElement.call( this, config );
12261 OO.ui.mixin.IconElement.call( this, config );
12262
12263 // Properties
12264 this.outline = outline;
12265 this.$movers = $( '<div>' );
12266 this.upButton = new OO.ui.ButtonWidget( {
12267 framed: false,
12268 icon: 'collapse',
12269 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12270 } );
12271 this.downButton = new OO.ui.ButtonWidget( {
12272 framed: false,
12273 icon: 'expand',
12274 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12275 } );
12276 this.removeButton = new OO.ui.ButtonWidget( {
12277 framed: false,
12278 icon: 'remove',
12279 title: OO.ui.msg( 'ooui-outline-control-remove' )
12280 } );
12281 this.abilities = { move: true, remove: true };
12282
12283 // Events
12284 outline.connect( this, {
12285 select: 'onOutlineChange',
12286 add: 'onOutlineChange',
12287 remove: 'onOutlineChange'
12288 } );
12289 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12290 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12291 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12292
12293 // Initialization
12294 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12295 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12296 this.$movers
12297 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12298 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12299 this.$element.append( this.$icon, this.$group, this.$movers );
12300 this.setAbilities( config.abilities || {} );
12301 };
12302
12303 /* Setup */
12304
12305 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12306 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12307 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12308
12309 /* Events */
12310
12311 /**
12312 * @event move
12313 * @param {number} places Number of places to move
12314 */
12315
12316 /**
12317 * @event remove
12318 */
12319
12320 /* Methods */
12321
12322 /**
12323 * Set abilities.
12324 *
12325 * @param {Object} abilities List of abilties
12326 * @param {boolean} [abilities.move] Allow moving movable items
12327 * @param {boolean} [abilities.remove] Allow removing removable items
12328 */
12329 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12330 var ability;
12331
12332 for ( ability in this.abilities ) {
12333 if ( abilities[ ability ] !== undefined ) {
12334 this.abilities[ ability ] = !!abilities[ ability ];
12335 }
12336 }
12337
12338 this.onOutlineChange();
12339 };
12340
12341 /**
12342 * @private
12343 * Handle outline change events.
12344 */
12345 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12346 var i, len, firstMovable, lastMovable,
12347 items = this.outline.getItems(),
12348 selectedItem = this.outline.getSelectedItem(),
12349 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12350 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12351
12352 if ( movable ) {
12353 i = -1;
12354 len = items.length;
12355 while ( ++i < len ) {
12356 if ( items[ i ].isMovable() ) {
12357 firstMovable = items[ i ];
12358 break;
12359 }
12360 }
12361 i = len;
12362 while ( i-- ) {
12363 if ( items[ i ].isMovable() ) {
12364 lastMovable = items[ i ];
12365 break;
12366 }
12367 }
12368 }
12369 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12370 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12371 this.removeButton.setDisabled( !removable );
12372 };
12373
12374 /**
12375 * ToggleWidget implements basic behavior of widgets with an on/off state.
12376 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12377 *
12378 * @abstract
12379 * @class
12380 * @extends OO.ui.Widget
12381 *
12382 * @constructor
12383 * @param {Object} [config] Configuration options
12384 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12385 * By default, the toggle is in the 'off' state.
12386 */
12387 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12388 // Configuration initialization
12389 config = config || {};
12390
12391 // Parent constructor
12392 OO.ui.ToggleWidget.parent.call( this, config );
12393
12394 // Properties
12395 this.value = null;
12396
12397 // Initialization
12398 this.$element.addClass( 'oo-ui-toggleWidget' );
12399 this.setValue( !!config.value );
12400 };
12401
12402 /* Setup */
12403
12404 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12405
12406 /* Events */
12407
12408 /**
12409 * @event change
12410 *
12411 * A change event is emitted when the on/off state of the toggle changes.
12412 *
12413 * @param {boolean} value Value representing the new state of the toggle
12414 */
12415
12416 /* Methods */
12417
12418 /**
12419 * Get the value representing the toggle’s state.
12420 *
12421 * @return {boolean} The on/off state of the toggle
12422 */
12423 OO.ui.ToggleWidget.prototype.getValue = function () {
12424 return this.value;
12425 };
12426
12427 /**
12428 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12429 *
12430 * @param {boolean} value The state of the toggle
12431 * @fires change
12432 * @chainable
12433 */
12434 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12435 value = !!value;
12436 if ( this.value !== value ) {
12437 this.value = value;
12438 this.emit( 'change', value );
12439 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12440 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12441 this.$element.attr( 'aria-checked', value.toString() );
12442 }
12443 return this;
12444 };
12445
12446 /**
12447 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12448 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12449 * removed, and cleared from the group.
12450 *
12451 * @example
12452 * // Example: A ButtonGroupWidget with two buttons
12453 * var button1 = new OO.ui.PopupButtonWidget( {
12454 * label: 'Select a category',
12455 * icon: 'menu',
12456 * popup: {
12457 * $content: $( '<p>List of categories...</p>' ),
12458 * padded: true,
12459 * align: 'left'
12460 * }
12461 * } );
12462 * var button2 = new OO.ui.ButtonWidget( {
12463 * label: 'Add item'
12464 * });
12465 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12466 * items: [button1, button2]
12467 * } );
12468 * $( 'body' ).append( buttonGroup.$element );
12469 *
12470 * @class
12471 * @extends OO.ui.Widget
12472 * @mixins OO.ui.mixin.GroupElement
12473 *
12474 * @constructor
12475 * @param {Object} [config] Configuration options
12476 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12477 */
12478 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12479 // Configuration initialization
12480 config = config || {};
12481
12482 // Parent constructor
12483 OO.ui.ButtonGroupWidget.parent.call( this, config );
12484
12485 // Mixin constructors
12486 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12487
12488 // Initialization
12489 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12490 if ( Array.isArray( config.items ) ) {
12491 this.addItems( config.items );
12492 }
12493 };
12494
12495 /* Setup */
12496
12497 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12498 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12499
12500 /**
12501 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12502 * feels, and functionality can be customized via the class’s configuration options
12503 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12504 * and examples.
12505 *
12506 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12507 *
12508 * @example
12509 * // A button widget
12510 * var button = new OO.ui.ButtonWidget( {
12511 * label: 'Button with Icon',
12512 * icon: 'remove',
12513 * iconTitle: 'Remove'
12514 * } );
12515 * $( 'body' ).append( button.$element );
12516 *
12517 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12518 *
12519 * @class
12520 * @extends OO.ui.Widget
12521 * @mixins OO.ui.mixin.ButtonElement
12522 * @mixins OO.ui.mixin.IconElement
12523 * @mixins OO.ui.mixin.IndicatorElement
12524 * @mixins OO.ui.mixin.LabelElement
12525 * @mixins OO.ui.mixin.TitledElement
12526 * @mixins OO.ui.mixin.FlaggedElement
12527 * @mixins OO.ui.mixin.TabIndexedElement
12528 * @mixins OO.ui.mixin.AccessKeyedElement
12529 *
12530 * @constructor
12531 * @param {Object} [config] Configuration options
12532 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12533 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12534 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12535 */
12536 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12537 // Configuration initialization
12538 config = config || {};
12539
12540 // Parent constructor
12541 OO.ui.ButtonWidget.parent.call( this, config );
12542
12543 // Mixin constructors
12544 OO.ui.mixin.ButtonElement.call( this, config );
12545 OO.ui.mixin.IconElement.call( this, config );
12546 OO.ui.mixin.IndicatorElement.call( this, config );
12547 OO.ui.mixin.LabelElement.call( this, config );
12548 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12549 OO.ui.mixin.FlaggedElement.call( this, config );
12550 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12551 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12552
12553 // Properties
12554 this.href = null;
12555 this.target = null;
12556 this.noFollow = false;
12557
12558 // Events
12559 this.connect( this, { disable: 'onDisable' } );
12560
12561 // Initialization
12562 this.$button.append( this.$icon, this.$label, this.$indicator );
12563 this.$element
12564 .addClass( 'oo-ui-buttonWidget' )
12565 .append( this.$button );
12566 this.setHref( config.href );
12567 this.setTarget( config.target );
12568 this.setNoFollow( config.noFollow );
12569 };
12570
12571 /* Setup */
12572
12573 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12574 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12575 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12576 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12577 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12578 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12579 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12580 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12581 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12582
12583 /* Methods */
12584
12585 /**
12586 * @inheritdoc
12587 */
12588 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12589 if ( !this.isDisabled() ) {
12590 // Remove the tab-index while the button is down to prevent the button from stealing focus
12591 this.$button.removeAttr( 'tabindex' );
12592 }
12593
12594 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12595 };
12596
12597 /**
12598 * @inheritdoc
12599 */
12600 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12601 if ( !this.isDisabled() ) {
12602 // Restore the tab-index after the button is up to restore the button's accessibility
12603 this.$button.attr( 'tabindex', this.tabIndex );
12604 }
12605
12606 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12607 };
12608
12609 /**
12610 * Get hyperlink location.
12611 *
12612 * @return {string} Hyperlink location
12613 */
12614 OO.ui.ButtonWidget.prototype.getHref = function () {
12615 return this.href;
12616 };
12617
12618 /**
12619 * Get hyperlink target.
12620 *
12621 * @return {string} Hyperlink target
12622 */
12623 OO.ui.ButtonWidget.prototype.getTarget = function () {
12624 return this.target;
12625 };
12626
12627 /**
12628 * Get search engine traversal hint.
12629 *
12630 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12631 */
12632 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12633 return this.noFollow;
12634 };
12635
12636 /**
12637 * Set hyperlink location.
12638 *
12639 * @param {string|null} href Hyperlink location, null to remove
12640 */
12641 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12642 href = typeof href === 'string' ? href : null;
12643 if ( href !== null ) {
12644 if ( !OO.ui.isSafeUrl( href ) ) {
12645 throw new Error( 'Potentially unsafe href provided: ' + href );
12646 }
12647
12648 }
12649
12650 if ( href !== this.href ) {
12651 this.href = href;
12652 this.updateHref();
12653 }
12654
12655 return this;
12656 };
12657
12658 /**
12659 * Update the `href` attribute, in case of changes to href or
12660 * disabled state.
12661 *
12662 * @private
12663 * @chainable
12664 */
12665 OO.ui.ButtonWidget.prototype.updateHref = function () {
12666 if ( this.href !== null && !this.isDisabled() ) {
12667 this.$button.attr( 'href', this.href );
12668 } else {
12669 this.$button.removeAttr( 'href' );
12670 }
12671
12672 return this;
12673 };
12674
12675 /**
12676 * Handle disable events.
12677 *
12678 * @private
12679 * @param {boolean} disabled Element is disabled
12680 */
12681 OO.ui.ButtonWidget.prototype.onDisable = function () {
12682 this.updateHref();
12683 };
12684
12685 /**
12686 * Set hyperlink target.
12687 *
12688 * @param {string|null} target Hyperlink target, null to remove
12689 */
12690 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12691 target = typeof target === 'string' ? target : null;
12692
12693 if ( target !== this.target ) {
12694 this.target = target;
12695 if ( target !== null ) {
12696 this.$button.attr( 'target', target );
12697 } else {
12698 this.$button.removeAttr( 'target' );
12699 }
12700 }
12701
12702 return this;
12703 };
12704
12705 /**
12706 * Set search engine traversal hint.
12707 *
12708 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12709 */
12710 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12711 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12712
12713 if ( noFollow !== this.noFollow ) {
12714 this.noFollow = noFollow;
12715 if ( noFollow ) {
12716 this.$button.attr( 'rel', 'nofollow' );
12717 } else {
12718 this.$button.removeAttr( 'rel' );
12719 }
12720 }
12721
12722 return this;
12723 };
12724
12725 /**
12726 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12727 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12728 * of the actions.
12729 *
12730 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12731 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12732 * and examples.
12733 *
12734 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12735 *
12736 * @class
12737 * @extends OO.ui.ButtonWidget
12738 * @mixins OO.ui.mixin.PendingElement
12739 *
12740 * @constructor
12741 * @param {Object} [config] Configuration options
12742 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12743 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12744 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12745 * for more information about setting modes.
12746 * @cfg {boolean} [framed=false] Render the action button with a frame
12747 */
12748 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12749 // Configuration initialization
12750 config = $.extend( { framed: false }, config );
12751
12752 // Parent constructor
12753 OO.ui.ActionWidget.parent.call( this, config );
12754
12755 // Mixin constructors
12756 OO.ui.mixin.PendingElement.call( this, config );
12757
12758 // Properties
12759 this.action = config.action || '';
12760 this.modes = config.modes || [];
12761 this.width = 0;
12762 this.height = 0;
12763
12764 // Initialization
12765 this.$element.addClass( 'oo-ui-actionWidget' );
12766 };
12767
12768 /* Setup */
12769
12770 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12771 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12772
12773 /* Events */
12774
12775 /**
12776 * A resize event is emitted when the size of the widget changes.
12777 *
12778 * @event resize
12779 */
12780
12781 /* Methods */
12782
12783 /**
12784 * Check if the action is configured to be available in the specified `mode`.
12785 *
12786 * @param {string} mode Name of mode
12787 * @return {boolean} The action is configured with the mode
12788 */
12789 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12790 return this.modes.indexOf( mode ) !== -1;
12791 };
12792
12793 /**
12794 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12795 *
12796 * @return {string}
12797 */
12798 OO.ui.ActionWidget.prototype.getAction = function () {
12799 return this.action;
12800 };
12801
12802 /**
12803 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12804 *
12805 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12806 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12807 * are hidden.
12808 *
12809 * @return {string[]}
12810 */
12811 OO.ui.ActionWidget.prototype.getModes = function () {
12812 return this.modes.slice();
12813 };
12814
12815 /**
12816 * Emit a resize event if the size has changed.
12817 *
12818 * @private
12819 * @chainable
12820 */
12821 OO.ui.ActionWidget.prototype.propagateResize = function () {
12822 var width, height;
12823
12824 if ( this.isElementAttached() ) {
12825 width = this.$element.width();
12826 height = this.$element.height();
12827
12828 if ( width !== this.width || height !== this.height ) {
12829 this.width = width;
12830 this.height = height;
12831 this.emit( 'resize' );
12832 }
12833 }
12834
12835 return this;
12836 };
12837
12838 /**
12839 * @inheritdoc
12840 */
12841 OO.ui.ActionWidget.prototype.setIcon = function () {
12842 // Mixin method
12843 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12844 this.propagateResize();
12845
12846 return this;
12847 };
12848
12849 /**
12850 * @inheritdoc
12851 */
12852 OO.ui.ActionWidget.prototype.setLabel = function () {
12853 // Mixin method
12854 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12855 this.propagateResize();
12856
12857 return this;
12858 };
12859
12860 /**
12861 * @inheritdoc
12862 */
12863 OO.ui.ActionWidget.prototype.setFlags = function () {
12864 // Mixin method
12865 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12866 this.propagateResize();
12867
12868 return this;
12869 };
12870
12871 /**
12872 * @inheritdoc
12873 */
12874 OO.ui.ActionWidget.prototype.clearFlags = function () {
12875 // Mixin method
12876 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12877 this.propagateResize();
12878
12879 return this;
12880 };
12881
12882 /**
12883 * Toggle the visibility of the action button.
12884 *
12885 * @param {boolean} [show] Show button, omit to toggle visibility
12886 * @chainable
12887 */
12888 OO.ui.ActionWidget.prototype.toggle = function () {
12889 // Parent method
12890 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12891 this.propagateResize();
12892
12893 return this;
12894 };
12895
12896 /**
12897 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12898 * which is used to display additional information or options.
12899 *
12900 * @example
12901 * // Example of a popup button.
12902 * var popupButton = new OO.ui.PopupButtonWidget( {
12903 * label: 'Popup button with options',
12904 * icon: 'menu',
12905 * popup: {
12906 * $content: $( '<p>Additional options here.</p>' ),
12907 * padded: true,
12908 * align: 'force-left'
12909 * }
12910 * } );
12911 * // Append the button to the DOM.
12912 * $( 'body' ).append( popupButton.$element );
12913 *
12914 * @class
12915 * @extends OO.ui.ButtonWidget
12916 * @mixins OO.ui.mixin.PopupElement
12917 *
12918 * @constructor
12919 * @param {Object} [config] Configuration options
12920 */
12921 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12922 // Parent constructor
12923 OO.ui.PopupButtonWidget.parent.call( this, config );
12924
12925 // Mixin constructors
12926 OO.ui.mixin.PopupElement.call( this, config );
12927
12928 // Events
12929 this.connect( this, { click: 'onAction' } );
12930
12931 // Initialization
12932 this.$element
12933 .addClass( 'oo-ui-popupButtonWidget' )
12934 .attr( 'aria-haspopup', 'true' )
12935 .append( this.popup.$element );
12936 };
12937
12938 /* Setup */
12939
12940 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12941 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12942
12943 /* Methods */
12944
12945 /**
12946 * Handle the button action being triggered.
12947 *
12948 * @private
12949 */
12950 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12951 this.popup.toggle();
12952 };
12953
12954 /**
12955 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12956 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12957 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12958 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12959 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12960 * the [OOjs UI documentation][1] on MediaWiki for more information.
12961 *
12962 * @example
12963 * // Toggle buttons in the 'off' and 'on' state.
12964 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12965 * label: 'Toggle Button off'
12966 * } );
12967 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12968 * label: 'Toggle Button on',
12969 * value: true
12970 * } );
12971 * // Append the buttons to the DOM.
12972 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12973 *
12974 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12975 *
12976 * @class
12977 * @extends OO.ui.ToggleWidget
12978 * @mixins OO.ui.mixin.ButtonElement
12979 * @mixins OO.ui.mixin.IconElement
12980 * @mixins OO.ui.mixin.IndicatorElement
12981 * @mixins OO.ui.mixin.LabelElement
12982 * @mixins OO.ui.mixin.TitledElement
12983 * @mixins OO.ui.mixin.FlaggedElement
12984 * @mixins OO.ui.mixin.TabIndexedElement
12985 *
12986 * @constructor
12987 * @param {Object} [config] Configuration options
12988 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12989 * state. By default, the button is in the 'off' state.
12990 */
12991 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12992 // Configuration initialization
12993 config = config || {};
12994
12995 // Parent constructor
12996 OO.ui.ToggleButtonWidget.parent.call( this, config );
12997
12998 // Mixin constructors
12999 OO.ui.mixin.ButtonElement.call( this, config );
13000 OO.ui.mixin.IconElement.call( this, config );
13001 OO.ui.mixin.IndicatorElement.call( this, config );
13002 OO.ui.mixin.LabelElement.call( this, config );
13003 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13004 OO.ui.mixin.FlaggedElement.call( this, config );
13005 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13006
13007 // Events
13008 this.connect( this, { click: 'onAction' } );
13009
13010 // Initialization
13011 this.$button.append( this.$icon, this.$label, this.$indicator );
13012 this.$element
13013 .addClass( 'oo-ui-toggleButtonWidget' )
13014 .append( this.$button );
13015 };
13016
13017 /* Setup */
13018
13019 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13020 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13021 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13022 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13023 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13024 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13025 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13026 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13027
13028 /* Methods */
13029
13030 /**
13031 * Handle the button action being triggered.
13032 *
13033 * @private
13034 */
13035 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13036 this.setValue( !this.value );
13037 };
13038
13039 /**
13040 * @inheritdoc
13041 */
13042 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13043 value = !!value;
13044 if ( value !== this.value ) {
13045 // Might be called from parent constructor before ButtonElement constructor
13046 if ( this.$button ) {
13047 this.$button.attr( 'aria-pressed', value.toString() );
13048 }
13049 this.setActive( value );
13050 }
13051
13052 // Parent method
13053 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13054
13055 return this;
13056 };
13057
13058 /**
13059 * @inheritdoc
13060 */
13061 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13062 if ( this.$button ) {
13063 this.$button.removeAttr( 'aria-pressed' );
13064 }
13065 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13066 this.$button.attr( 'aria-pressed', this.value.toString() );
13067 };
13068
13069 /**
13070 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13071 * that allows for selecting multiple values.
13072 *
13073 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13074 *
13075 * @example
13076 * // Example: A CapsuleMultiSelectWidget.
13077 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13078 * label: 'CapsuleMultiSelectWidget',
13079 * selected: [ 'Option 1', 'Option 3' ],
13080 * menu: {
13081 * items: [
13082 * new OO.ui.MenuOptionWidget( {
13083 * data: 'Option 1',
13084 * label: 'Option One'
13085 * } ),
13086 * new OO.ui.MenuOptionWidget( {
13087 * data: 'Option 2',
13088 * label: 'Option Two'
13089 * } ),
13090 * new OO.ui.MenuOptionWidget( {
13091 * data: 'Option 3',
13092 * label: 'Option Three'
13093 * } ),
13094 * new OO.ui.MenuOptionWidget( {
13095 * data: 'Option 4',
13096 * label: 'Option Four'
13097 * } ),
13098 * new OO.ui.MenuOptionWidget( {
13099 * data: 'Option 5',
13100 * label: 'Option Five'
13101 * } )
13102 * ]
13103 * }
13104 * } );
13105 * $( 'body' ).append( capsule.$element );
13106 *
13107 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13108 *
13109 * @class
13110 * @extends OO.ui.Widget
13111 * @mixins OO.ui.mixin.TabIndexedElement
13112 * @mixins OO.ui.mixin.GroupElement
13113 *
13114 * @constructor
13115 * @param {Object} [config] Configuration options
13116 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13117 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13118 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13119 * If specified, this popup will be shown instead of the menu (but the menu
13120 * will still be used for item labels and allowArbitrary=false). The widgets
13121 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13122 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13123 * This configuration is useful in cases where the expanded menu is larger than
13124 * its containing `<div>`. The specified overlay layer is usually on top of
13125 * the containing `<div>` and has a larger area. By default, the menu uses
13126 * relative positioning.
13127 */
13128 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13129 var $tabFocus;
13130
13131 // Configuration initialization
13132 config = config || {};
13133
13134 // Parent constructor
13135 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13136
13137 // Properties (must be set before mixin constructor calls)
13138 this.$input = config.popup ? null : $( '<input>' );
13139 this.$handle = $( '<div>' );
13140
13141 // Mixin constructors
13142 OO.ui.mixin.GroupElement.call( this, config );
13143 if ( config.popup ) {
13144 config.popup = $.extend( {}, config.popup, {
13145 align: 'forwards',
13146 anchor: false
13147 } );
13148 OO.ui.mixin.PopupElement.call( this, config );
13149 $tabFocus = $( '<span>' );
13150 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13151 } else {
13152 this.popup = null;
13153 $tabFocus = null;
13154 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13155 }
13156 OO.ui.mixin.IndicatorElement.call( this, config );
13157 OO.ui.mixin.IconElement.call( this, config );
13158
13159 // Properties
13160 this.allowArbitrary = !!config.allowArbitrary;
13161 this.$overlay = config.$overlay || this.$element;
13162 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13163 {
13164 widget: this,
13165 $input: this.$input,
13166 $container: this.$element,
13167 filterFromInput: true,
13168 disabled: this.isDisabled()
13169 },
13170 config.menu
13171 ) );
13172
13173 // Events
13174 if ( this.popup ) {
13175 $tabFocus.on( {
13176 focus: this.onFocusForPopup.bind( this )
13177 } );
13178 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13179 if ( this.popup.$autoCloseIgnore ) {
13180 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13181 }
13182 this.popup.connect( this, {
13183 toggle: function ( visible ) {
13184 $tabFocus.toggle( !visible );
13185 }
13186 } );
13187 } else {
13188 this.$input.on( {
13189 focus: this.onInputFocus.bind( this ),
13190 blur: this.onInputBlur.bind( this ),
13191 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13192 keydown: this.onKeyDown.bind( this ),
13193 keypress: this.onKeyPress.bind( this )
13194 } );
13195 }
13196 this.menu.connect( this, {
13197 choose: 'onMenuChoose',
13198 add: 'onMenuItemsChange',
13199 remove: 'onMenuItemsChange'
13200 } );
13201 this.$handle.on( {
13202 click: this.onClick.bind( this )
13203 } );
13204
13205 // Initialization
13206 if ( this.$input ) {
13207 this.$input.prop( 'disabled', this.isDisabled() );
13208 this.$input.attr( {
13209 role: 'combobox',
13210 'aria-autocomplete': 'list'
13211 } );
13212 this.$input.width( '1em' );
13213 }
13214 if ( config.data ) {
13215 this.setItemsFromData( config.data );
13216 }
13217 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13218 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13219 .append( this.$indicator, this.$icon, this.$group );
13220 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13221 .append( this.$handle );
13222 if ( this.popup ) {
13223 this.$handle.append( $tabFocus );
13224 this.$overlay.append( this.popup.$element );
13225 } else {
13226 this.$handle.append( this.$input );
13227 this.$overlay.append( this.menu.$element );
13228 }
13229 this.onMenuItemsChange();
13230 };
13231
13232 /* Setup */
13233
13234 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13235 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13236 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13237 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13238 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13239 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13240
13241 /* Events */
13242
13243 /**
13244 * @event change
13245 *
13246 * A change event is emitted when the set of selected items changes.
13247 *
13248 * @param {Mixed[]} datas Data of the now-selected items
13249 */
13250
13251 /* Methods */
13252
13253 /**
13254 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13255 *
13256 * @protected
13257 * @param {Mixed} data Custom data of any type.
13258 * @param {string} label The label text.
13259 * @return {OO.ui.CapsuleItemWidget}
13260 */
13261 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13262 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13263 };
13264
13265 /**
13266 * Get the data of the items in the capsule
13267 * @return {Mixed[]}
13268 */
13269 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13270 return $.map( this.getItems(), function ( e ) { return e.data; } );
13271 };
13272
13273 /**
13274 * Set the items in the capsule by providing data
13275 * @chainable
13276 * @param {Mixed[]} datas
13277 * @return {OO.ui.CapsuleMultiSelectWidget}
13278 */
13279 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13280 var widget = this,
13281 menu = this.menu,
13282 items = this.getItems();
13283
13284 $.each( datas, function ( i, data ) {
13285 var j, label,
13286 item = menu.getItemFromData( data );
13287
13288 if ( item ) {
13289 label = item.label;
13290 } else if ( widget.allowArbitrary ) {
13291 label = String( data );
13292 } else {
13293 return;
13294 }
13295
13296 item = null;
13297 for ( j = 0; j < items.length; j++ ) {
13298 if ( items[ j ].data === data && items[ j ].label === label ) {
13299 item = items[ j ];
13300 items.splice( j, 1 );
13301 break;
13302 }
13303 }
13304 if ( !item ) {
13305 item = widget.createItemWidget( data, label );
13306 }
13307 widget.addItems( [ item ], i );
13308 } );
13309
13310 if ( items.length ) {
13311 widget.removeItems( items );
13312 }
13313
13314 return this;
13315 };
13316
13317 /**
13318 * Add items to the capsule by providing their data
13319 * @chainable
13320 * @param {Mixed[]} datas
13321 * @return {OO.ui.CapsuleMultiSelectWidget}
13322 */
13323 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13324 var widget = this,
13325 menu = this.menu,
13326 items = [];
13327
13328 $.each( datas, function ( i, data ) {
13329 var item;
13330
13331 if ( !widget.getItemFromData( data ) ) {
13332 item = menu.getItemFromData( data );
13333 if ( item ) {
13334 items.push( widget.createItemWidget( data, item.label ) );
13335 } else if ( widget.allowArbitrary ) {
13336 items.push( widget.createItemWidget( data, String( data ) ) );
13337 }
13338 }
13339 } );
13340
13341 if ( items.length ) {
13342 this.addItems( items );
13343 }
13344
13345 return this;
13346 };
13347
13348 /**
13349 * Remove items by data
13350 * @chainable
13351 * @param {Mixed[]} datas
13352 * @return {OO.ui.CapsuleMultiSelectWidget}
13353 */
13354 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13355 var widget = this,
13356 items = [];
13357
13358 $.each( datas, function ( i, data ) {
13359 var item = widget.getItemFromData( data );
13360 if ( item ) {
13361 items.push( item );
13362 }
13363 } );
13364
13365 if ( items.length ) {
13366 this.removeItems( items );
13367 }
13368
13369 return this;
13370 };
13371
13372 /**
13373 * @inheritdoc
13374 */
13375 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13376 var same, i, l,
13377 oldItems = this.items.slice();
13378
13379 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13380
13381 if ( this.items.length !== oldItems.length ) {
13382 same = false;
13383 } else {
13384 same = true;
13385 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13386 same = same && this.items[ i ] === oldItems[ i ];
13387 }
13388 }
13389 if ( !same ) {
13390 this.emit( 'change', this.getItemsData() );
13391 }
13392
13393 return this;
13394 };
13395
13396 /**
13397 * @inheritdoc
13398 */
13399 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13400 var same, i, l,
13401 oldItems = this.items.slice();
13402
13403 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13404
13405 if ( this.items.length !== oldItems.length ) {
13406 same = false;
13407 } else {
13408 same = true;
13409 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13410 same = same && this.items[ i ] === oldItems[ i ];
13411 }
13412 }
13413 if ( !same ) {
13414 this.emit( 'change', this.getItemsData() );
13415 }
13416
13417 return this;
13418 };
13419
13420 /**
13421 * @inheritdoc
13422 */
13423 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13424 if ( this.items.length ) {
13425 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13426 this.emit( 'change', this.getItemsData() );
13427 }
13428 return this;
13429 };
13430
13431 /**
13432 * Get the capsule widget's menu.
13433 * @return {OO.ui.MenuSelectWidget} Menu widget
13434 */
13435 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13436 return this.menu;
13437 };
13438
13439 /**
13440 * Handle focus events
13441 *
13442 * @private
13443 * @param {jQuery.Event} event
13444 */
13445 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13446 if ( !this.isDisabled() ) {
13447 this.menu.toggle( true );
13448 }
13449 };
13450
13451 /**
13452 * Handle blur events
13453 *
13454 * @private
13455 * @param {jQuery.Event} event
13456 */
13457 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13458 this.clearInput();
13459 };
13460
13461 /**
13462 * Handle focus events
13463 *
13464 * @private
13465 * @param {jQuery.Event} event
13466 */
13467 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13468 if ( !this.isDisabled() ) {
13469 this.popup.setSize( this.$handle.width() );
13470 this.popup.toggle( true );
13471 this.popup.$element.find( '*' )
13472 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13473 .first()
13474 .focus();
13475 }
13476 };
13477
13478 /**
13479 * Handles popup focus out events.
13480 *
13481 * @private
13482 * @param {Event} e Focus out event
13483 */
13484 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13485 var widget = this.popup;
13486
13487 setTimeout( function () {
13488 if (
13489 widget.isVisible() &&
13490 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13491 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13492 ) {
13493 widget.toggle( false );
13494 }
13495 } );
13496 };
13497
13498 /**
13499 * Handle mouse click events.
13500 *
13501 * @private
13502 * @param {jQuery.Event} e Mouse click event
13503 */
13504 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13505 if ( e.which === 1 ) {
13506 this.focus();
13507 return false;
13508 }
13509 };
13510
13511 /**
13512 * Handle key press events.
13513 *
13514 * @private
13515 * @param {jQuery.Event} e Key press event
13516 */
13517 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13518 var item;
13519
13520 if ( !this.isDisabled() ) {
13521 if ( e.which === OO.ui.Keys.ESCAPE ) {
13522 this.clearInput();
13523 return false;
13524 }
13525
13526 if ( !this.popup ) {
13527 this.menu.toggle( true );
13528 if ( e.which === OO.ui.Keys.ENTER ) {
13529 item = this.menu.getItemFromLabel( this.$input.val(), true );
13530 if ( item ) {
13531 this.addItemsFromData( [ item.data ] );
13532 this.clearInput();
13533 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13534 this.addItemsFromData( [ this.$input.val() ] );
13535 this.clearInput();
13536 }
13537 return false;
13538 }
13539
13540 // Make sure the input gets resized.
13541 setTimeout( this.onInputChange.bind( this ), 0 );
13542 }
13543 }
13544 };
13545
13546 /**
13547 * Handle key down events.
13548 *
13549 * @private
13550 * @param {jQuery.Event} e Key down event
13551 */
13552 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13553 if ( !this.isDisabled() ) {
13554 // 'keypress' event is not triggered for Backspace
13555 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13556 if ( this.items.length ) {
13557 this.removeItems( this.items.slice( -1 ) );
13558 }
13559 return false;
13560 }
13561 }
13562 };
13563
13564 /**
13565 * Handle input change events.
13566 *
13567 * @private
13568 * @param {jQuery.Event} e Event of some sort
13569 */
13570 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13571 if ( !this.isDisabled() ) {
13572 this.$input.width( this.$input.val().length + 'em' );
13573 }
13574 };
13575
13576 /**
13577 * Handle menu choose events.
13578 *
13579 * @private
13580 * @param {OO.ui.OptionWidget} item Chosen item
13581 */
13582 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13583 if ( item && item.isVisible() ) {
13584 this.addItemsFromData( [ item.getData() ] );
13585 this.clearInput();
13586 }
13587 };
13588
13589 /**
13590 * Handle menu item change events.
13591 *
13592 * @private
13593 */
13594 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13595 this.setItemsFromData( this.getItemsData() );
13596 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13597 };
13598
13599 /**
13600 * Clear the input field
13601 * @private
13602 */
13603 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13604 if ( this.$input ) {
13605 this.$input.val( '' );
13606 this.$input.width( '1em' );
13607 }
13608 if ( this.popup ) {
13609 this.popup.toggle( false );
13610 }
13611 this.menu.toggle( false );
13612 this.menu.selectItem();
13613 this.menu.highlightItem();
13614 };
13615
13616 /**
13617 * @inheritdoc
13618 */
13619 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13620 var i, len;
13621
13622 // Parent method
13623 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13624
13625 if ( this.$input ) {
13626 this.$input.prop( 'disabled', this.isDisabled() );
13627 }
13628 if ( this.menu ) {
13629 this.menu.setDisabled( this.isDisabled() );
13630 }
13631 if ( this.popup ) {
13632 this.popup.setDisabled( this.isDisabled() );
13633 }
13634
13635 if ( this.items ) {
13636 for ( i = 0, len = this.items.length; i < len; i++ ) {
13637 this.items[ i ].updateDisabled();
13638 }
13639 }
13640
13641 return this;
13642 };
13643
13644 /**
13645 * Focus the widget
13646 * @chainable
13647 * @return {OO.ui.CapsuleMultiSelectWidget}
13648 */
13649 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13650 if ( !this.isDisabled() ) {
13651 if ( this.popup ) {
13652 this.popup.setSize( this.$handle.width() );
13653 this.popup.toggle( true );
13654 this.popup.$element.find( '*' )
13655 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13656 .first()
13657 .focus();
13658 } else {
13659 this.menu.toggle( true );
13660 this.$input.focus();
13661 }
13662 }
13663 return this;
13664 };
13665
13666 /**
13667 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13668 * CapsuleMultiSelectWidget} to display the selected items.
13669 *
13670 * @class
13671 * @extends OO.ui.Widget
13672 * @mixins OO.ui.mixin.ItemWidget
13673 * @mixins OO.ui.mixin.IndicatorElement
13674 * @mixins OO.ui.mixin.LabelElement
13675 * @mixins OO.ui.mixin.FlaggedElement
13676 * @mixins OO.ui.mixin.TabIndexedElement
13677 *
13678 * @constructor
13679 * @param {Object} [config] Configuration options
13680 */
13681 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13682 // Configuration initialization
13683 config = config || {};
13684
13685 // Parent constructor
13686 OO.ui.CapsuleItemWidget.parent.call( this, config );
13687
13688 // Properties (must be set before mixin constructor calls)
13689 this.$indicator = $( '<span>' );
13690
13691 // Mixin constructors
13692 OO.ui.mixin.ItemWidget.call( this );
13693 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13694 OO.ui.mixin.LabelElement.call( this, config );
13695 OO.ui.mixin.FlaggedElement.call( this, config );
13696 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13697
13698 // Events
13699 this.$indicator.on( {
13700 keydown: this.onCloseKeyDown.bind( this ),
13701 click: this.onCloseClick.bind( this )
13702 } );
13703
13704 // Initialization
13705 this.$element
13706 .addClass( 'oo-ui-capsuleItemWidget' )
13707 .append( this.$indicator, this.$label );
13708 };
13709
13710 /* Setup */
13711
13712 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13713 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13714 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13715 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13716 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13717 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13718
13719 /* Methods */
13720
13721 /**
13722 * Handle close icon clicks
13723 * @param {jQuery.Event} event
13724 */
13725 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13726 var element = this.getElementGroup();
13727
13728 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13729 element.removeItems( [ this ] );
13730 element.focus();
13731 }
13732 };
13733
13734 /**
13735 * Handle close keyboard events
13736 * @param {jQuery.Event} event Key down event
13737 */
13738 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13739 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13740 switch ( e.which ) {
13741 case OO.ui.Keys.ENTER:
13742 case OO.ui.Keys.BACKSPACE:
13743 case OO.ui.Keys.SPACE:
13744 this.getElementGroup().removeItems( [ this ] );
13745 return false;
13746 }
13747 }
13748 };
13749
13750 /**
13751 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13752 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13753 * users can interact with it.
13754 *
13755 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13756 * OO.ui.DropdownInputWidget instead.
13757 *
13758 * @example
13759 * // Example: A DropdownWidget with a menu that contains three options
13760 * var dropDown = new OO.ui.DropdownWidget( {
13761 * label: 'Dropdown menu: Select a menu option',
13762 * menu: {
13763 * items: [
13764 * new OO.ui.MenuOptionWidget( {
13765 * data: 'a',
13766 * label: 'First'
13767 * } ),
13768 * new OO.ui.MenuOptionWidget( {
13769 * data: 'b',
13770 * label: 'Second'
13771 * } ),
13772 * new OO.ui.MenuOptionWidget( {
13773 * data: 'c',
13774 * label: 'Third'
13775 * } )
13776 * ]
13777 * }
13778 * } );
13779 *
13780 * $( 'body' ).append( dropDown.$element );
13781 *
13782 * dropDown.getMenu().selectItemByData( 'b' );
13783 *
13784 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13785 *
13786 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13787 *
13788 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13789 *
13790 * @class
13791 * @extends OO.ui.Widget
13792 * @mixins OO.ui.mixin.IconElement
13793 * @mixins OO.ui.mixin.IndicatorElement
13794 * @mixins OO.ui.mixin.LabelElement
13795 * @mixins OO.ui.mixin.TitledElement
13796 * @mixins OO.ui.mixin.TabIndexedElement
13797 *
13798 * @constructor
13799 * @param {Object} [config] Configuration options
13800 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13801 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13802 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13803 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13804 */
13805 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13806 // Configuration initialization
13807 config = $.extend( { indicator: 'down' }, config );
13808
13809 // Parent constructor
13810 OO.ui.DropdownWidget.parent.call( this, config );
13811
13812 // Properties (must be set before TabIndexedElement constructor call)
13813 this.$handle = this.$( '<span>' );
13814 this.$overlay = config.$overlay || this.$element;
13815
13816 // Mixin constructors
13817 OO.ui.mixin.IconElement.call( this, config );
13818 OO.ui.mixin.IndicatorElement.call( this, config );
13819 OO.ui.mixin.LabelElement.call( this, config );
13820 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13821 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13822
13823 // Properties
13824 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13825 widget: this,
13826 $container: this.$element
13827 }, config.menu ) );
13828
13829 // Events
13830 this.$handle.on( {
13831 click: this.onClick.bind( this ),
13832 keypress: this.onKeyPress.bind( this )
13833 } );
13834 this.menu.connect( this, { select: 'onMenuSelect' } );
13835
13836 // Initialization
13837 this.$handle
13838 .addClass( 'oo-ui-dropdownWidget-handle' )
13839 .append( this.$icon, this.$label, this.$indicator );
13840 this.$element
13841 .addClass( 'oo-ui-dropdownWidget' )
13842 .append( this.$handle );
13843 this.$overlay.append( this.menu.$element );
13844 };
13845
13846 /* Setup */
13847
13848 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13849 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13850 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13851 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13852 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13853 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13854
13855 /* Methods */
13856
13857 /**
13858 * Get the menu.
13859 *
13860 * @return {OO.ui.MenuSelectWidget} Menu of widget
13861 */
13862 OO.ui.DropdownWidget.prototype.getMenu = function () {
13863 return this.menu;
13864 };
13865
13866 /**
13867 * Handles menu select events.
13868 *
13869 * @private
13870 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13871 */
13872 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13873 var selectedLabel;
13874
13875 if ( !item ) {
13876 this.setLabel( null );
13877 return;
13878 }
13879
13880 selectedLabel = item.getLabel();
13881
13882 // If the label is a DOM element, clone it, because setLabel will append() it
13883 if ( selectedLabel instanceof jQuery ) {
13884 selectedLabel = selectedLabel.clone();
13885 }
13886
13887 this.setLabel( selectedLabel );
13888 };
13889
13890 /**
13891 * Handle mouse click events.
13892 *
13893 * @private
13894 * @param {jQuery.Event} e Mouse click event
13895 */
13896 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13897 if ( !this.isDisabled() && e.which === 1 ) {
13898 this.menu.toggle();
13899 }
13900 return false;
13901 };
13902
13903 /**
13904 * Handle key press events.
13905 *
13906 * @private
13907 * @param {jQuery.Event} e Key press event
13908 */
13909 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13910 if ( !this.isDisabled() &&
13911 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13912 ) {
13913 this.menu.toggle();
13914 return false;
13915 }
13916 };
13917
13918 /**
13919 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13920 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13921 * OO.ui.mixin.IndicatorElement indicators}.
13922 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13923 *
13924 * @example
13925 * // Example of a file select widget
13926 * var selectFile = new OO.ui.SelectFileWidget();
13927 * $( 'body' ).append( selectFile.$element );
13928 *
13929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13930 *
13931 * @class
13932 * @extends OO.ui.Widget
13933 * @mixins OO.ui.mixin.IconElement
13934 * @mixins OO.ui.mixin.IndicatorElement
13935 * @mixins OO.ui.mixin.PendingElement
13936 * @mixins OO.ui.mixin.LabelElement
13937 *
13938 * @constructor
13939 * @param {Object} [config] Configuration options
13940 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13941 * @cfg {string} [placeholder] Text to display when no file is selected.
13942 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13943 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13944 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13945 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13946 */
13947 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13948 var dragHandler;
13949
13950 // TODO: Remove in next release
13951 if ( config && config.dragDropUI ) {
13952 config.showDropTarget = true;
13953 }
13954
13955 // Configuration initialization
13956 config = $.extend( {
13957 accept: null,
13958 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13959 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13960 droppable: true,
13961 showDropTarget: false
13962 }, config );
13963
13964 // Parent constructor
13965 OO.ui.SelectFileWidget.parent.call( this, config );
13966
13967 // Mixin constructors
13968 OO.ui.mixin.IconElement.call( this, config );
13969 OO.ui.mixin.IndicatorElement.call( this, config );
13970 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
13971 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13972
13973 // Properties
13974 this.$info = $( '<span>' );
13975
13976 // Properties
13977 this.showDropTarget = config.showDropTarget;
13978 this.isSupported = this.constructor.static.isSupported();
13979 this.currentFile = null;
13980 if ( Array.isArray( config.accept ) ) {
13981 this.accept = config.accept;
13982 } else {
13983 this.accept = null;
13984 }
13985 this.placeholder = config.placeholder;
13986 this.notsupported = config.notsupported;
13987 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13988
13989 this.selectButton = new OO.ui.ButtonWidget( {
13990 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
13991 label: 'Select a file',
13992 disabled: this.disabled || !this.isSupported
13993 } );
13994
13995 this.clearButton = new OO.ui.ButtonWidget( {
13996 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13997 framed: false,
13998 icon: 'remove',
13999 disabled: this.disabled
14000 } );
14001
14002 // Events
14003 this.selectButton.$button.on( {
14004 keypress: this.onKeyPress.bind( this )
14005 } );
14006 this.clearButton.connect( this, {
14007 click: 'onClearClick'
14008 } );
14009 if ( config.droppable ) {
14010 dragHandler = this.onDragEnterOrOver.bind( this );
14011 this.$element.on( {
14012 dragenter: dragHandler,
14013 dragover: dragHandler,
14014 dragleave: this.onDragLeave.bind( this ),
14015 drop: this.onDrop.bind( this )
14016 } );
14017 }
14018
14019 // Initialization
14020 this.addInput();
14021 this.updateUI();
14022 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14023 this.$info
14024 .addClass( 'oo-ui-selectFileWidget-info' )
14025 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14026 this.$element
14027 .addClass( 'oo-ui-selectFileWidget' )
14028 .append( this.$info, this.selectButton.$element );
14029 if ( config.droppable && config.showDropTarget ) {
14030 this.$dropTarget = $( '<div>' )
14031 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14032 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14033 .on( {
14034 click: this.onDropTargetClick.bind( this )
14035 } );
14036 this.$element.prepend( this.$dropTarget );
14037 }
14038 };
14039
14040 /* Setup */
14041
14042 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14043 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14044 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14045 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14046 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14047
14048 /* Static Properties */
14049
14050 /**
14051 * Check if this widget is supported
14052 *
14053 * @static
14054 * @return {boolean}
14055 */
14056 OO.ui.SelectFileWidget.static.isSupported = function () {
14057 var $input;
14058 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14059 $input = $( '<input type="file">' );
14060 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14061 }
14062 return OO.ui.SelectFileWidget.static.isSupportedCache;
14063 };
14064
14065 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14066
14067 /* Events */
14068
14069 /**
14070 * @event change
14071 *
14072 * A change event is emitted when the on/off state of the toggle changes.
14073 *
14074 * @param {File|null} value New value
14075 */
14076
14077 /* Methods */
14078
14079 /**
14080 * Get the current value of the field
14081 *
14082 * @return {File|null}
14083 */
14084 OO.ui.SelectFileWidget.prototype.getValue = function () {
14085 return this.currentFile;
14086 };
14087
14088 /**
14089 * Set the current value of the field
14090 *
14091 * @param {File|null} file File to select
14092 */
14093 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14094 if ( this.currentFile !== file ) {
14095 this.currentFile = file;
14096 this.updateUI();
14097 this.emit( 'change', this.currentFile );
14098 }
14099 };
14100
14101 /**
14102 * Update the user interface when a file is selected or unselected
14103 *
14104 * @protected
14105 */
14106 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14107 var $label;
14108 if ( !this.isSupported ) {
14109 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14110 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14111 this.setLabel( this.notsupported );
14112 } else {
14113 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14114 if ( this.currentFile ) {
14115 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14116 $label = $( [] );
14117 if ( this.currentFile.type !== '' ) {
14118 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14119 }
14120 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14121 this.setLabel( $label );
14122 } else {
14123 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14124 this.setLabel( this.placeholder );
14125 }
14126 }
14127
14128 if ( this.$input ) {
14129 this.$input.attr( 'title', this.getLabel() );
14130 }
14131 };
14132
14133 /**
14134 * Add the input to the widget
14135 *
14136 * @private
14137 */
14138 OO.ui.SelectFileWidget.prototype.addInput = function () {
14139 if ( this.$input ) {
14140 this.$input.remove();
14141 }
14142
14143 if ( !this.isSupported ) {
14144 this.$input = null;
14145 return;
14146 }
14147
14148 this.$input = $( '<input type="file">' );
14149 this.$input.on( 'change', this.onFileSelectedHandler );
14150 this.$input.attr( {
14151 tabindex: -1,
14152 title: this.getLabel()
14153 } );
14154 if ( this.accept ) {
14155 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14156 }
14157 this.selectButton.$button.append( this.$input );
14158 };
14159
14160 /**
14161 * Determine if we should accept this file
14162 *
14163 * @private
14164 * @param {string} File MIME type
14165 * @return {boolean}
14166 */
14167 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14168 var i, mimeTest;
14169
14170 if ( !this.accept || !mimeType ) {
14171 return true;
14172 }
14173
14174 for ( i = 0; i < this.accept.length; i++ ) {
14175 mimeTest = this.accept[ i ];
14176 if ( mimeTest === mimeType ) {
14177 return true;
14178 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14179 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14180 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14181 return true;
14182 }
14183 }
14184 }
14185
14186 return false;
14187 };
14188
14189 /**
14190 * Handle file selection from the input
14191 *
14192 * @private
14193 * @param {jQuery.Event} e
14194 */
14195 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14196 var file = OO.getProp( e.target, 'files', 0 ) || null;
14197
14198 if ( file && !this.isAllowedType( file.type ) ) {
14199 file = null;
14200 }
14201
14202 this.setValue( file );
14203 this.addInput();
14204 };
14205
14206 /**
14207 * Handle clear button click events.
14208 *
14209 * @private
14210 */
14211 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14212 this.setValue( null );
14213 return false;
14214 };
14215
14216 /**
14217 * Handle key press events.
14218 *
14219 * @private
14220 * @param {jQuery.Event} e Key press event
14221 */
14222 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14223 if ( this.isSupported && !this.isDisabled() && this.$input &&
14224 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14225 ) {
14226 this.$input.click();
14227 return false;
14228 }
14229 };
14230
14231 /**
14232 * Handle drop target click events.
14233 *
14234 * @private
14235 * @param {jQuery.Event} e Key press event
14236 */
14237 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14238 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14239 this.$input.click();
14240 return false;
14241 }
14242 };
14243
14244 /**
14245 * Handle drag enter and over events
14246 *
14247 * @private
14248 * @param {jQuery.Event} e Drag event
14249 */
14250 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14251 var itemOrFile,
14252 droppableFile = false,
14253 dt = e.originalEvent.dataTransfer;
14254
14255 e.preventDefault();
14256 e.stopPropagation();
14257
14258 if ( this.isDisabled() || !this.isSupported ) {
14259 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14260 dt.dropEffect = 'none';
14261 return false;
14262 }
14263
14264 // DataTransferItem and File both have a type property, but in Chrome files
14265 // have no information at this point.
14266 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14267 if ( itemOrFile ) {
14268 if ( this.isAllowedType( itemOrFile.type ) ) {
14269 droppableFile = true;
14270 }
14271 // dt.types is Array-like, but not an Array
14272 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14273 // File information is not available at this point for security so just assume
14274 // it is acceptable for now.
14275 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14276 droppableFile = true;
14277 }
14278
14279 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14280 if ( !droppableFile ) {
14281 dt.dropEffect = 'none';
14282 }
14283
14284 return false;
14285 };
14286
14287 /**
14288 * Handle drag leave events
14289 *
14290 * @private
14291 * @param {jQuery.Event} e Drag event
14292 */
14293 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14294 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14295 };
14296
14297 /**
14298 * Handle drop events
14299 *
14300 * @private
14301 * @param {jQuery.Event} e Drop event
14302 */
14303 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14304 var file = null,
14305 dt = e.originalEvent.dataTransfer;
14306
14307 e.preventDefault();
14308 e.stopPropagation();
14309 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14310
14311 if ( this.isDisabled() || !this.isSupported ) {
14312 return false;
14313 }
14314
14315 file = OO.getProp( dt, 'files', 0 );
14316 if ( file && !this.isAllowedType( file.type ) ) {
14317 file = null;
14318 }
14319 if ( file ) {
14320 this.setValue( file );
14321 }
14322
14323 return false;
14324 };
14325
14326 /**
14327 * @inheritdoc
14328 */
14329 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14330 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14331 if ( this.selectButton ) {
14332 this.selectButton.setDisabled( disabled );
14333 }
14334 if ( this.clearButton ) {
14335 this.clearButton.setDisabled( disabled );
14336 }
14337 return this;
14338 };
14339
14340 /**
14341 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14342 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14343 * for a list of icons included in the library.
14344 *
14345 * @example
14346 * // An icon widget with a label
14347 * var myIcon = new OO.ui.IconWidget( {
14348 * icon: 'help',
14349 * iconTitle: 'Help'
14350 * } );
14351 * // Create a label.
14352 * var iconLabel = new OO.ui.LabelWidget( {
14353 * label: 'Help'
14354 * } );
14355 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14356 *
14357 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14358 *
14359 * @class
14360 * @extends OO.ui.Widget
14361 * @mixins OO.ui.mixin.IconElement
14362 * @mixins OO.ui.mixin.TitledElement
14363 * @mixins OO.ui.mixin.FlaggedElement
14364 *
14365 * @constructor
14366 * @param {Object} [config] Configuration options
14367 */
14368 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14369 // Configuration initialization
14370 config = config || {};
14371
14372 // Parent constructor
14373 OO.ui.IconWidget.parent.call( this, config );
14374
14375 // Mixin constructors
14376 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14377 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14378 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14379
14380 // Initialization
14381 this.$element.addClass( 'oo-ui-iconWidget' );
14382 };
14383
14384 /* Setup */
14385
14386 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14387 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14388 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14389 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14390
14391 /* Static Properties */
14392
14393 OO.ui.IconWidget.static.tagName = 'span';
14394
14395 /**
14396 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14397 * attention to the status of an item or to clarify the function of a control. For a list of
14398 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14399 *
14400 * @example
14401 * // Example of an indicator widget
14402 * var indicator1 = new OO.ui.IndicatorWidget( {
14403 * indicator: 'alert'
14404 * } );
14405 *
14406 * // Create a fieldset layout to add a label
14407 * var fieldset = new OO.ui.FieldsetLayout();
14408 * fieldset.addItems( [
14409 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14410 * ] );
14411 * $( 'body' ).append( fieldset.$element );
14412 *
14413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14414 *
14415 * @class
14416 * @extends OO.ui.Widget
14417 * @mixins OO.ui.mixin.IndicatorElement
14418 * @mixins OO.ui.mixin.TitledElement
14419 *
14420 * @constructor
14421 * @param {Object} [config] Configuration options
14422 */
14423 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14424 // Configuration initialization
14425 config = config || {};
14426
14427 // Parent constructor
14428 OO.ui.IndicatorWidget.parent.call( this, config );
14429
14430 // Mixin constructors
14431 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14432 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14433
14434 // Initialization
14435 this.$element.addClass( 'oo-ui-indicatorWidget' );
14436 };
14437
14438 /* Setup */
14439
14440 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14441 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14442 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14443
14444 /* Static Properties */
14445
14446 OO.ui.IndicatorWidget.static.tagName = 'span';
14447
14448 /**
14449 * InputWidget is the base class for all input widgets, which
14450 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14451 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14452 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14453 *
14454 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14455 *
14456 * @abstract
14457 * @class
14458 * @extends OO.ui.Widget
14459 * @mixins OO.ui.mixin.FlaggedElement
14460 * @mixins OO.ui.mixin.TabIndexedElement
14461 * @mixins OO.ui.mixin.TitledElement
14462 * @mixins OO.ui.mixin.AccessKeyedElement
14463 *
14464 * @constructor
14465 * @param {Object} [config] Configuration options
14466 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14467 * @cfg {string} [value=''] The value of the input.
14468 * @cfg {string} [accessKey=''] The access key of the input.
14469 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14470 * before it is accepted.
14471 */
14472 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14473 // Configuration initialization
14474 config = config || {};
14475
14476 // Parent constructor
14477 OO.ui.InputWidget.parent.call( this, config );
14478
14479 // Properties
14480 this.$input = this.getInputElement( config );
14481 this.value = '';
14482 this.inputFilter = config.inputFilter;
14483
14484 // Mixin constructors
14485 OO.ui.mixin.FlaggedElement.call( this, config );
14486 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14487 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14488 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14489
14490 // Events
14491 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14492
14493 // Initialization
14494 this.$input
14495 .addClass( 'oo-ui-inputWidget-input' )
14496 .attr( 'name', config.name )
14497 .prop( 'disabled', this.isDisabled() );
14498 this.$element
14499 .addClass( 'oo-ui-inputWidget' )
14500 .append( this.$input );
14501 this.setValue( config.value );
14502 this.setAccessKey( config.accessKey );
14503 };
14504
14505 /* Setup */
14506
14507 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14508 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14509 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14510 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14511 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14512
14513 /* Static Properties */
14514
14515 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14516
14517 /* Events */
14518
14519 /**
14520 * @event change
14521 *
14522 * A change event is emitted when the value of the input changes.
14523 *
14524 * @param {string} value
14525 */
14526
14527 /* Methods */
14528
14529 /**
14530 * Get input element.
14531 *
14532 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14533 * different circumstances. The element must have a `value` property (like form elements).
14534 *
14535 * @protected
14536 * @param {Object} config Configuration options
14537 * @return {jQuery} Input element
14538 */
14539 OO.ui.InputWidget.prototype.getInputElement = function () {
14540 return $( '<input>' );
14541 };
14542
14543 /**
14544 * Handle potentially value-changing events.
14545 *
14546 * @private
14547 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14548 */
14549 OO.ui.InputWidget.prototype.onEdit = function () {
14550 var widget = this;
14551 if ( !this.isDisabled() ) {
14552 // Allow the stack to clear so the value will be updated
14553 setTimeout( function () {
14554 widget.setValue( widget.$input.val() );
14555 } );
14556 }
14557 };
14558
14559 /**
14560 * Get the value of the input.
14561 *
14562 * @return {string} Input value
14563 */
14564 OO.ui.InputWidget.prototype.getValue = function () {
14565 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14566 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14567 var value = this.$input.val();
14568 if ( this.value !== value ) {
14569 this.setValue( value );
14570 }
14571 return this.value;
14572 };
14573
14574 /**
14575 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14576 *
14577 * @param {boolean} isRTL
14578 * Direction is right-to-left
14579 */
14580 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14581 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14582 };
14583
14584 /**
14585 * Set the value of the input.
14586 *
14587 * @param {string} value New value
14588 * @fires change
14589 * @chainable
14590 */
14591 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14592 value = this.cleanUpValue( value );
14593 // Update the DOM if it has changed. Note that with cleanUpValue, it
14594 // is possible for the DOM value to change without this.value changing.
14595 if ( this.$input.val() !== value ) {
14596 this.$input.val( value );
14597 }
14598 if ( this.value !== value ) {
14599 this.value = value;
14600 this.emit( 'change', this.value );
14601 }
14602 return this;
14603 };
14604
14605 /**
14606 * Set the input's access key.
14607 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14608 *
14609 * @param {string} accessKey Input's access key, use empty string to remove
14610 * @chainable
14611 */
14612 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14613 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14614
14615 if ( this.accessKey !== accessKey ) {
14616 if ( this.$input ) {
14617 if ( accessKey !== null ) {
14618 this.$input.attr( 'accesskey', accessKey );
14619 } else {
14620 this.$input.removeAttr( 'accesskey' );
14621 }
14622 }
14623 this.accessKey = accessKey;
14624 }
14625
14626 return this;
14627 };
14628
14629 /**
14630 * Clean up incoming value.
14631 *
14632 * Ensures value is a string, and converts undefined and null to empty string.
14633 *
14634 * @private
14635 * @param {string} value Original value
14636 * @return {string} Cleaned up value
14637 */
14638 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14639 if ( value === undefined || value === null ) {
14640 return '';
14641 } else if ( this.inputFilter ) {
14642 return this.inputFilter( String( value ) );
14643 } else {
14644 return String( value );
14645 }
14646 };
14647
14648 /**
14649 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14650 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14651 * called directly.
14652 */
14653 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14654 if ( !this.isDisabled() ) {
14655 if ( this.$input.is( ':checkbox, :radio' ) ) {
14656 this.$input.click();
14657 }
14658 if ( this.$input.is( ':input' ) ) {
14659 this.$input[ 0 ].focus();
14660 }
14661 }
14662 };
14663
14664 /**
14665 * @inheritdoc
14666 */
14667 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14668 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14669 if ( this.$input ) {
14670 this.$input.prop( 'disabled', this.isDisabled() );
14671 }
14672 return this;
14673 };
14674
14675 /**
14676 * Focus the input.
14677 *
14678 * @chainable
14679 */
14680 OO.ui.InputWidget.prototype.focus = function () {
14681 this.$input[ 0 ].focus();
14682 return this;
14683 };
14684
14685 /**
14686 * Blur the input.
14687 *
14688 * @chainable
14689 */
14690 OO.ui.InputWidget.prototype.blur = function () {
14691 this.$input[ 0 ].blur();
14692 return this;
14693 };
14694
14695 /**
14696 * @inheritdoc
14697 */
14698 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14699 var
14700 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14701 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14702 state.value = $input.val();
14703 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14704 state.focus = $input.is( ':focus' );
14705 return state;
14706 };
14707
14708 /**
14709 * @inheritdoc
14710 */
14711 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14712 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14713 if ( state.value !== undefined && state.value !== this.getValue() ) {
14714 this.setValue( state.value );
14715 }
14716 if ( state.focus ) {
14717 this.focus();
14718 }
14719 };
14720
14721 /**
14722 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14723 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14724 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14725 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14726 * [OOjs UI documentation on MediaWiki] [1] for more information.
14727 *
14728 * @example
14729 * // A ButtonInputWidget rendered as an HTML button, the default.
14730 * var button = new OO.ui.ButtonInputWidget( {
14731 * label: 'Input button',
14732 * icon: 'check',
14733 * value: 'check'
14734 * } );
14735 * $( 'body' ).append( button.$element );
14736 *
14737 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14738 *
14739 * @class
14740 * @extends OO.ui.InputWidget
14741 * @mixins OO.ui.mixin.ButtonElement
14742 * @mixins OO.ui.mixin.IconElement
14743 * @mixins OO.ui.mixin.IndicatorElement
14744 * @mixins OO.ui.mixin.LabelElement
14745 * @mixins OO.ui.mixin.TitledElement
14746 *
14747 * @constructor
14748 * @param {Object} [config] Configuration options
14749 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14750 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14751 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14752 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14753 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14754 */
14755 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14756 // Configuration initialization
14757 config = $.extend( { type: 'button', useInputTag: false }, config );
14758
14759 // Properties (must be set before parent constructor, which calls #setValue)
14760 this.useInputTag = config.useInputTag;
14761
14762 // Parent constructor
14763 OO.ui.ButtonInputWidget.parent.call( this, config );
14764
14765 // Mixin constructors
14766 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14767 OO.ui.mixin.IconElement.call( this, config );
14768 OO.ui.mixin.IndicatorElement.call( this, config );
14769 OO.ui.mixin.LabelElement.call( this, config );
14770 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14771
14772 // Initialization
14773 if ( !config.useInputTag ) {
14774 this.$input.append( this.$icon, this.$label, this.$indicator );
14775 }
14776 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14777 };
14778
14779 /* Setup */
14780
14781 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14782 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14783 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14784 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14785 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14786 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14787
14788 /* Static Properties */
14789
14790 /**
14791 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14792 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14793 */
14794 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14795
14796 /* Methods */
14797
14798 /**
14799 * @inheritdoc
14800 * @protected
14801 */
14802 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14803 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14804 config.type :
14805 'button';
14806 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14807 };
14808
14809 /**
14810 * Set label value.
14811 *
14812 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14813 *
14814 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14815 * text, or `null` for no label
14816 * @chainable
14817 */
14818 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14819 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14820
14821 if ( this.useInputTag ) {
14822 if ( typeof label === 'function' ) {
14823 label = OO.ui.resolveMsg( label );
14824 }
14825 if ( label instanceof jQuery ) {
14826 label = label.text();
14827 }
14828 if ( !label ) {
14829 label = '';
14830 }
14831 this.$input.val( label );
14832 }
14833
14834 return this;
14835 };
14836
14837 /**
14838 * Set the value of the input.
14839 *
14840 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14841 * they do not support {@link #value values}.
14842 *
14843 * @param {string} value New value
14844 * @chainable
14845 */
14846 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14847 if ( !this.useInputTag ) {
14848 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14849 }
14850 return this;
14851 };
14852
14853 /**
14854 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14855 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14856 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14857 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14858 *
14859 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14860 *
14861 * @example
14862 * // An example of selected, unselected, and disabled checkbox inputs
14863 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14864 * value: 'a',
14865 * selected: true
14866 * } );
14867 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14868 * value: 'b'
14869 * } );
14870 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14871 * value:'c',
14872 * disabled: true
14873 * } );
14874 * // Create a fieldset layout with fields for each checkbox.
14875 * var fieldset = new OO.ui.FieldsetLayout( {
14876 * label: 'Checkboxes'
14877 * } );
14878 * fieldset.addItems( [
14879 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14880 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14881 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14882 * ] );
14883 * $( 'body' ).append( fieldset.$element );
14884 *
14885 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14886 *
14887 * @class
14888 * @extends OO.ui.InputWidget
14889 *
14890 * @constructor
14891 * @param {Object} [config] Configuration options
14892 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14893 */
14894 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14895 // Configuration initialization
14896 config = config || {};
14897
14898 // Parent constructor
14899 OO.ui.CheckboxInputWidget.parent.call( this, config );
14900
14901 // Initialization
14902 this.$element
14903 .addClass( 'oo-ui-checkboxInputWidget' )
14904 // Required for pretty styling in MediaWiki theme
14905 .append( $( '<span>' ) );
14906 this.setSelected( config.selected !== undefined ? config.selected : false );
14907 };
14908
14909 /* Setup */
14910
14911 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14912
14913 /* Methods */
14914
14915 /**
14916 * @inheritdoc
14917 * @protected
14918 */
14919 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14920 return $( '<input type="checkbox" />' );
14921 };
14922
14923 /**
14924 * @inheritdoc
14925 */
14926 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14927 var widget = this;
14928 if ( !this.isDisabled() ) {
14929 // Allow the stack to clear so the value will be updated
14930 setTimeout( function () {
14931 widget.setSelected( widget.$input.prop( 'checked' ) );
14932 } );
14933 }
14934 };
14935
14936 /**
14937 * Set selection state of this checkbox.
14938 *
14939 * @param {boolean} state `true` for selected
14940 * @chainable
14941 */
14942 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14943 state = !!state;
14944 if ( this.selected !== state ) {
14945 this.selected = state;
14946 this.$input.prop( 'checked', this.selected );
14947 this.emit( 'change', this.selected );
14948 }
14949 return this;
14950 };
14951
14952 /**
14953 * Check if this checkbox is selected.
14954 *
14955 * @return {boolean} Checkbox is selected
14956 */
14957 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14958 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14959 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14960 var selected = this.$input.prop( 'checked' );
14961 if ( this.selected !== selected ) {
14962 this.setSelected( selected );
14963 }
14964 return this.selected;
14965 };
14966
14967 /**
14968 * @inheritdoc
14969 */
14970 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14971 var
14972 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14973 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14974 state.$input = $input; // shortcut for performance, used in InputWidget
14975 state.checked = $input.prop( 'checked' );
14976 return state;
14977 };
14978
14979 /**
14980 * @inheritdoc
14981 */
14982 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14983 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14984 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14985 this.setSelected( state.checked );
14986 }
14987 };
14988
14989 /**
14990 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14991 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14992 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14993 * more information about input widgets.
14994 *
14995 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14996 * are no options. If no `value` configuration option is provided, the first option is selected.
14997 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14998 *
14999 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15000 *
15001 * @example
15002 * // Example: A DropdownInputWidget with three options
15003 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15004 * options: [
15005 * { data: 'a', label: 'First' },
15006 * { data: 'b', label: 'Second'},
15007 * { data: 'c', label: 'Third' }
15008 * ]
15009 * } );
15010 * $( 'body' ).append( dropdownInput.$element );
15011 *
15012 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15013 *
15014 * @class
15015 * @extends OO.ui.InputWidget
15016 * @mixins OO.ui.mixin.TitledElement
15017 *
15018 * @constructor
15019 * @param {Object} [config] Configuration options
15020 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15021 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15022 */
15023 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15024 // Configuration initialization
15025 config = config || {};
15026
15027 // Properties (must be done before parent constructor which calls #setDisabled)
15028 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15029
15030 // Parent constructor
15031 OO.ui.DropdownInputWidget.parent.call( this, config );
15032
15033 // Mixin constructors
15034 OO.ui.mixin.TitledElement.call( this, config );
15035
15036 // Events
15037 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15038
15039 // Initialization
15040 this.setOptions( config.options || [] );
15041 this.$element
15042 .addClass( 'oo-ui-dropdownInputWidget' )
15043 .append( this.dropdownWidget.$element );
15044 };
15045
15046 /* Setup */
15047
15048 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15049 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15050
15051 /* Methods */
15052
15053 /**
15054 * @inheritdoc
15055 * @protected
15056 */
15057 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
15058 return $( '<input type="hidden">' );
15059 };
15060
15061 /**
15062 * Handles menu select events.
15063 *
15064 * @private
15065 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15066 */
15067 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15068 this.setValue( item.getData() );
15069 };
15070
15071 /**
15072 * @inheritdoc
15073 */
15074 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15075 value = this.cleanUpValue( value );
15076 this.dropdownWidget.getMenu().selectItemByData( value );
15077 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15078 return this;
15079 };
15080
15081 /**
15082 * @inheritdoc
15083 */
15084 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15085 this.dropdownWidget.setDisabled( state );
15086 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15087 return this;
15088 };
15089
15090 /**
15091 * Set the options available for this input.
15092 *
15093 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15094 * @chainable
15095 */
15096 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15097 var
15098 value = this.getValue(),
15099 widget = this;
15100
15101 // Rebuild the dropdown menu
15102 this.dropdownWidget.getMenu()
15103 .clearItems()
15104 .addItems( options.map( function ( opt ) {
15105 var optValue = widget.cleanUpValue( opt.data );
15106 return new OO.ui.MenuOptionWidget( {
15107 data: optValue,
15108 label: opt.label !== undefined ? opt.label : optValue
15109 } );
15110 } ) );
15111
15112 // Restore the previous value, or reset to something sensible
15113 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15114 // Previous value is still available, ensure consistency with the dropdown
15115 this.setValue( value );
15116 } else {
15117 // No longer valid, reset
15118 if ( options.length ) {
15119 this.setValue( options[ 0 ].data );
15120 }
15121 }
15122
15123 return this;
15124 };
15125
15126 /**
15127 * @inheritdoc
15128 */
15129 OO.ui.DropdownInputWidget.prototype.focus = function () {
15130 this.dropdownWidget.getMenu().toggle( true );
15131 return this;
15132 };
15133
15134 /**
15135 * @inheritdoc
15136 */
15137 OO.ui.DropdownInputWidget.prototype.blur = function () {
15138 this.dropdownWidget.getMenu().toggle( false );
15139 return this;
15140 };
15141
15142 /**
15143 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15144 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15145 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15146 * please see the [OOjs UI documentation on MediaWiki][1].
15147 *
15148 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15149 *
15150 * @example
15151 * // An example of selected, unselected, and disabled radio inputs
15152 * var radio1 = new OO.ui.RadioInputWidget( {
15153 * value: 'a',
15154 * selected: true
15155 * } );
15156 * var radio2 = new OO.ui.RadioInputWidget( {
15157 * value: 'b'
15158 * } );
15159 * var radio3 = new OO.ui.RadioInputWidget( {
15160 * value: 'c',
15161 * disabled: true
15162 * } );
15163 * // Create a fieldset layout with fields for each radio button.
15164 * var fieldset = new OO.ui.FieldsetLayout( {
15165 * label: 'Radio inputs'
15166 * } );
15167 * fieldset.addItems( [
15168 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15169 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15170 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15171 * ] );
15172 * $( 'body' ).append( fieldset.$element );
15173 *
15174 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15175 *
15176 * @class
15177 * @extends OO.ui.InputWidget
15178 *
15179 * @constructor
15180 * @param {Object} [config] Configuration options
15181 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15182 */
15183 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15184 // Configuration initialization
15185 config = config || {};
15186
15187 // Parent constructor
15188 OO.ui.RadioInputWidget.parent.call( this, config );
15189
15190 // Initialization
15191 this.$element
15192 .addClass( 'oo-ui-radioInputWidget' )
15193 // Required for pretty styling in MediaWiki theme
15194 .append( $( '<span>' ) );
15195 this.setSelected( config.selected !== undefined ? config.selected : false );
15196 };
15197
15198 /* Setup */
15199
15200 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15201
15202 /* Methods */
15203
15204 /**
15205 * @inheritdoc
15206 * @protected
15207 */
15208 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15209 return $( '<input type="radio" />' );
15210 };
15211
15212 /**
15213 * @inheritdoc
15214 */
15215 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15216 // RadioInputWidget doesn't track its state.
15217 };
15218
15219 /**
15220 * Set selection state of this radio button.
15221 *
15222 * @param {boolean} state `true` for selected
15223 * @chainable
15224 */
15225 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15226 // RadioInputWidget doesn't track its state.
15227 this.$input.prop( 'checked', state );
15228 return this;
15229 };
15230
15231 /**
15232 * Check if this radio button is selected.
15233 *
15234 * @return {boolean} Radio is selected
15235 */
15236 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15237 return this.$input.prop( 'checked' );
15238 };
15239
15240 /**
15241 * @inheritdoc
15242 */
15243 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15244 var
15245 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15246 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15247 state.$input = $input; // shortcut for performance, used in InputWidget
15248 state.checked = $input.prop( 'checked' );
15249 return state;
15250 };
15251
15252 /**
15253 * @inheritdoc
15254 */
15255 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15256 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15257 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15258 this.setSelected( state.checked );
15259 }
15260 };
15261
15262 /**
15263 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15264 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15265 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15266 * more information about input widgets.
15267 *
15268 * This and OO.ui.DropdownInputWidget support the same configuration options.
15269 *
15270 * @example
15271 * // Example: A RadioSelectInputWidget with three options
15272 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15273 * options: [
15274 * { data: 'a', label: 'First' },
15275 * { data: 'b', label: 'Second'},
15276 * { data: 'c', label: 'Third' }
15277 * ]
15278 * } );
15279 * $( 'body' ).append( radioSelectInput.$element );
15280 *
15281 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15282 *
15283 * @class
15284 * @extends OO.ui.InputWidget
15285 *
15286 * @constructor
15287 * @param {Object} [config] Configuration options
15288 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15289 */
15290 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15291 // Configuration initialization
15292 config = config || {};
15293
15294 // Properties (must be done before parent constructor which calls #setDisabled)
15295 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15296
15297 // Parent constructor
15298 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15299
15300 // Events
15301 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15302
15303 // Initialization
15304 this.setOptions( config.options || [] );
15305 this.$element
15306 .addClass( 'oo-ui-radioSelectInputWidget' )
15307 .append( this.radioSelectWidget.$element );
15308 };
15309
15310 /* Setup */
15311
15312 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15313
15314 /* Static Properties */
15315
15316 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15317
15318 /* Methods */
15319
15320 /**
15321 * @inheritdoc
15322 * @protected
15323 */
15324 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15325 return $( '<input type="hidden">' );
15326 };
15327
15328 /**
15329 * Handles menu select events.
15330 *
15331 * @private
15332 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15333 */
15334 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15335 this.setValue( item.getData() );
15336 };
15337
15338 /**
15339 * @inheritdoc
15340 */
15341 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15342 value = this.cleanUpValue( value );
15343 this.radioSelectWidget.selectItemByData( value );
15344 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15345 return this;
15346 };
15347
15348 /**
15349 * @inheritdoc
15350 */
15351 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15352 this.radioSelectWidget.setDisabled( state );
15353 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15354 return this;
15355 };
15356
15357 /**
15358 * Set the options available for this input.
15359 *
15360 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15361 * @chainable
15362 */
15363 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15364 var
15365 value = this.getValue(),
15366 widget = this;
15367
15368 // Rebuild the radioSelect menu
15369 this.radioSelectWidget
15370 .clearItems()
15371 .addItems( options.map( function ( opt ) {
15372 var optValue = widget.cleanUpValue( opt.data );
15373 return new OO.ui.RadioOptionWidget( {
15374 data: optValue,
15375 label: opt.label !== undefined ? opt.label : optValue
15376 } );
15377 } ) );
15378
15379 // Restore the previous value, or reset to something sensible
15380 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15381 // Previous value is still available, ensure consistency with the radioSelect
15382 this.setValue( value );
15383 } else {
15384 // No longer valid, reset
15385 if ( options.length ) {
15386 this.setValue( options[ 0 ].data );
15387 }
15388 }
15389
15390 return this;
15391 };
15392
15393 /**
15394 * @inheritdoc
15395 */
15396 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15397 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15398 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15399 return state;
15400 };
15401
15402 /**
15403 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15404 * size of the field as well as its presentation. In addition, these widgets can be configured
15405 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15406 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15407 * which modifies incoming values rather than validating them.
15408 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15409 *
15410 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15411 *
15412 * @example
15413 * // Example of a text input widget
15414 * var textInput = new OO.ui.TextInputWidget( {
15415 * value: 'Text input'
15416 * } )
15417 * $( 'body' ).append( textInput.$element );
15418 *
15419 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15420 *
15421 * @class
15422 * @extends OO.ui.InputWidget
15423 * @mixins OO.ui.mixin.IconElement
15424 * @mixins OO.ui.mixin.IndicatorElement
15425 * @mixins OO.ui.mixin.PendingElement
15426 * @mixins OO.ui.mixin.LabelElement
15427 *
15428 * @constructor
15429 * @param {Object} [config] Configuration options
15430 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15431 * 'email' or 'url'. Ignored if `multiline` is true.
15432 *
15433 * Some values of `type` result in additional behaviors:
15434 *
15435 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15436 * empties the text field
15437 * @cfg {string} [placeholder] Placeholder text
15438 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15439 * instruct the browser to focus this widget.
15440 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15441 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15442 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15443 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15444 * specifies minimum number of rows to display.
15445 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15446 * Use the #maxRows config to specify a maximum number of displayed rows.
15447 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15448 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15449 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15450 * the value or placeholder text: `'before'` or `'after'`
15451 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15452 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15453 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15454 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15455 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15456 * value for it to be considered valid; when Function, a function receiving the value as parameter
15457 * that must return true, or promise resolving to true, for it to be considered valid.
15458 */
15459 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15460 // Configuration initialization
15461 config = $.extend( {
15462 type: 'text',
15463 labelPosition: 'after'
15464 }, config );
15465 if ( config.type === 'search' ) {
15466 if ( config.icon === undefined ) {
15467 config.icon = 'search';
15468 }
15469 // indicator: 'clear' is set dynamically later, depending on value
15470 }
15471 if ( config.required ) {
15472 if ( config.indicator === undefined ) {
15473 config.indicator = 'required';
15474 }
15475 }
15476
15477 // Parent constructor
15478 OO.ui.TextInputWidget.parent.call( this, config );
15479
15480 // Mixin constructors
15481 OO.ui.mixin.IconElement.call( this, config );
15482 OO.ui.mixin.IndicatorElement.call( this, config );
15483 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15484 OO.ui.mixin.LabelElement.call( this, config );
15485
15486 // Properties
15487 this.type = this.getSaneType( config );
15488 this.readOnly = false;
15489 this.multiline = !!config.multiline;
15490 this.autosize = !!config.autosize;
15491 this.minRows = config.rows !== undefined ? config.rows : '';
15492 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15493 this.validate = null;
15494
15495 // Clone for resizing
15496 if ( this.autosize ) {
15497 this.$clone = this.$input
15498 .clone()
15499 .insertAfter( this.$input )
15500 .attr( 'aria-hidden', 'true' )
15501 .addClass( 'oo-ui-element-hidden' );
15502 }
15503
15504 this.setValidation( config.validate );
15505 this.setLabelPosition( config.labelPosition );
15506
15507 // Events
15508 this.$input.on( {
15509 keypress: this.onKeyPress.bind( this ),
15510 blur: this.onBlur.bind( this )
15511 } );
15512 this.$input.one( {
15513 focus: this.onElementAttach.bind( this )
15514 } );
15515 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15516 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15517 this.on( 'labelChange', this.updatePosition.bind( this ) );
15518 this.connect( this, {
15519 change: 'onChange',
15520 disable: 'onDisable'
15521 } );
15522
15523 // Initialization
15524 this.$element
15525 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15526 .append( this.$icon, this.$indicator );
15527 this.setReadOnly( !!config.readOnly );
15528 this.updateSearchIndicator();
15529 if ( config.placeholder ) {
15530 this.$input.attr( 'placeholder', config.placeholder );
15531 }
15532 if ( config.maxLength !== undefined ) {
15533 this.$input.attr( 'maxlength', config.maxLength );
15534 }
15535 if ( config.autofocus ) {
15536 this.$input.attr( 'autofocus', 'autofocus' );
15537 }
15538 if ( config.required ) {
15539 this.$input.attr( 'required', 'required' );
15540 this.$input.attr( 'aria-required', 'true' );
15541 }
15542 if ( config.autocomplete === false ) {
15543 this.$input.attr( 'autocomplete', 'off' );
15544 // Turning off autocompletion also disables "form caching" when the user navigates to a
15545 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15546 $( window ).on( {
15547 beforeunload: function () {
15548 this.$input.removeAttr( 'autocomplete' );
15549 }.bind( this ),
15550 pageshow: function () {
15551 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15552 // whole page... it shouldn't hurt, though.
15553 this.$input.attr( 'autocomplete', 'off' );
15554 }.bind( this )
15555 } );
15556 }
15557 if ( this.multiline && config.rows ) {
15558 this.$input.attr( 'rows', config.rows );
15559 }
15560 if ( this.label || config.autosize ) {
15561 this.installParentChangeDetector();
15562 }
15563 };
15564
15565 /* Setup */
15566
15567 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15568 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15569 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15570 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15571 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15572
15573 /* Static Properties */
15574
15575 OO.ui.TextInputWidget.static.validationPatterns = {
15576 'non-empty': /.+/,
15577 integer: /^\d+$/
15578 };
15579
15580 /* Events */
15581
15582 /**
15583 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15584 *
15585 * Not emitted if the input is multiline.
15586 *
15587 * @event enter
15588 */
15589
15590 /* Methods */
15591
15592 /**
15593 * Handle icon mouse down events.
15594 *
15595 * @private
15596 * @param {jQuery.Event} e Mouse down event
15597 * @fires icon
15598 */
15599 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15600 if ( e.which === 1 ) {
15601 this.$input[ 0 ].focus();
15602 return false;
15603 }
15604 };
15605
15606 /**
15607 * Handle indicator mouse down events.
15608 *
15609 * @private
15610 * @param {jQuery.Event} e Mouse down event
15611 * @fires indicator
15612 */
15613 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15614 if ( e.which === 1 ) {
15615 if ( this.type === 'search' ) {
15616 // Clear the text field
15617 this.setValue( '' );
15618 }
15619 this.$input[ 0 ].focus();
15620 return false;
15621 }
15622 };
15623
15624 /**
15625 * Handle key press events.
15626 *
15627 * @private
15628 * @param {jQuery.Event} e Key press event
15629 * @fires enter If enter key is pressed and input is not multiline
15630 */
15631 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15632 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15633 this.emit( 'enter', e );
15634 }
15635 };
15636
15637 /**
15638 * Handle blur events.
15639 *
15640 * @private
15641 * @param {jQuery.Event} e Blur event
15642 */
15643 OO.ui.TextInputWidget.prototype.onBlur = function () {
15644 this.setValidityFlag();
15645 };
15646
15647 /**
15648 * Handle element attach events.
15649 *
15650 * @private
15651 * @param {jQuery.Event} e Element attach event
15652 */
15653 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15654 // Any previously calculated size is now probably invalid if we reattached elsewhere
15655 this.valCache = null;
15656 this.adjustSize();
15657 this.positionLabel();
15658 };
15659
15660 /**
15661 * Handle change events.
15662 *
15663 * @param {string} value
15664 * @private
15665 */
15666 OO.ui.TextInputWidget.prototype.onChange = function () {
15667 this.updateSearchIndicator();
15668 this.setValidityFlag();
15669 this.adjustSize();
15670 };
15671
15672 /**
15673 * Handle disable events.
15674 *
15675 * @param {boolean} disabled Element is disabled
15676 * @private
15677 */
15678 OO.ui.TextInputWidget.prototype.onDisable = function () {
15679 this.updateSearchIndicator();
15680 };
15681
15682 /**
15683 * Check if the input is {@link #readOnly read-only}.
15684 *
15685 * @return {boolean}
15686 */
15687 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15688 return this.readOnly;
15689 };
15690
15691 /**
15692 * Set the {@link #readOnly read-only} state of the input.
15693 *
15694 * @param {boolean} state Make input read-only
15695 * @chainable
15696 */
15697 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15698 this.readOnly = !!state;
15699 this.$input.prop( 'readOnly', this.readOnly );
15700 this.updateSearchIndicator();
15701 return this;
15702 };
15703
15704 /**
15705 * Support function for making #onElementAttach work across browsers.
15706 *
15707 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15708 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15709 *
15710 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15711 * first time that the element gets attached to the documented.
15712 */
15713 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15714 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15715 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15716 widget = this;
15717
15718 if ( MutationObserver ) {
15719 // The new way. If only it wasn't so ugly.
15720
15721 if ( this.$element.closest( 'html' ).length ) {
15722 // Widget is attached already, do nothing. This breaks the functionality of this function when
15723 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15724 // would require observation of the whole document, which would hurt performance of other,
15725 // more important code.
15726 return;
15727 }
15728
15729 // Find topmost node in the tree
15730 topmostNode = this.$element[ 0 ];
15731 while ( topmostNode.parentNode ) {
15732 topmostNode = topmostNode.parentNode;
15733 }
15734
15735 // We have no way to detect the $element being attached somewhere without observing the entire
15736 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15737 // parent node of $element, and instead detect when $element is removed from it (and thus
15738 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15739 // doesn't get attached, we end up back here and create the parent.
15740
15741 mutationObserver = new MutationObserver( function ( mutations ) {
15742 var i, j, removedNodes;
15743 for ( i = 0; i < mutations.length; i++ ) {
15744 removedNodes = mutations[ i ].removedNodes;
15745 for ( j = 0; j < removedNodes.length; j++ ) {
15746 if ( removedNodes[ j ] === topmostNode ) {
15747 setTimeout( onRemove, 0 );
15748 return;
15749 }
15750 }
15751 }
15752 } );
15753
15754 onRemove = function () {
15755 // If the node was attached somewhere else, report it
15756 if ( widget.$element.closest( 'html' ).length ) {
15757 widget.onElementAttach();
15758 }
15759 mutationObserver.disconnect();
15760 widget.installParentChangeDetector();
15761 };
15762
15763 // Create a fake parent and observe it
15764 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15765 mutationObserver.observe( fakeParentNode, { childList: true } );
15766 } else {
15767 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15768 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15769 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15770 }
15771 };
15772
15773 /**
15774 * Automatically adjust the size of the text input.
15775 *
15776 * This only affects #multiline inputs that are {@link #autosize autosized}.
15777 *
15778 * @chainable
15779 */
15780 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15781 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15782
15783 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15784 this.$clone
15785 .val( this.$input.val() )
15786 .attr( 'rows', this.minRows )
15787 // Set inline height property to 0 to measure scroll height
15788 .css( 'height', 0 );
15789
15790 this.$clone.removeClass( 'oo-ui-element-hidden' );
15791
15792 this.valCache = this.$input.val();
15793
15794 scrollHeight = this.$clone[ 0 ].scrollHeight;
15795
15796 // Remove inline height property to measure natural heights
15797 this.$clone.css( 'height', '' );
15798 innerHeight = this.$clone.innerHeight();
15799 outerHeight = this.$clone.outerHeight();
15800
15801 // Measure max rows height
15802 this.$clone
15803 .attr( 'rows', this.maxRows )
15804 .css( 'height', 'auto' )
15805 .val( '' );
15806 maxInnerHeight = this.$clone.innerHeight();
15807
15808 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15809 // Equals 1 on Blink-based browsers and 0 everywhere else
15810 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15811 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15812
15813 this.$clone.addClass( 'oo-ui-element-hidden' );
15814
15815 // Only apply inline height when expansion beyond natural height is needed
15816 if ( idealHeight > innerHeight ) {
15817 // Use the difference between the inner and outer height as a buffer
15818 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15819 } else {
15820 this.$input.css( 'height', '' );
15821 }
15822 }
15823 return this;
15824 };
15825
15826 /**
15827 * @inheritdoc
15828 * @protected
15829 */
15830 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15831 return config.multiline ?
15832 $( '<textarea>' ) :
15833 $( '<input type="' + this.getSaneType( config ) + '" />' );
15834 };
15835
15836 /**
15837 * Get sanitized value for 'type' for given config.
15838 *
15839 * @param {Object} config Configuration options
15840 * @return {string|null}
15841 * @private
15842 */
15843 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15844 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15845 config.type :
15846 'text';
15847 return config.multiline ? 'multiline' : type;
15848 };
15849
15850 /**
15851 * Check if the input supports multiple lines.
15852 *
15853 * @return {boolean}
15854 */
15855 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15856 return !!this.multiline;
15857 };
15858
15859 /**
15860 * Check if the input automatically adjusts its size.
15861 *
15862 * @return {boolean}
15863 */
15864 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15865 return !!this.autosize;
15866 };
15867
15868 /**
15869 * Select the entire text of the input.
15870 *
15871 * @chainable
15872 */
15873 OO.ui.TextInputWidget.prototype.select = function () {
15874 this.$input.select();
15875 return this;
15876 };
15877
15878 /**
15879 * Focus the input and move the cursor to the end.
15880 */
15881 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15882 var textRange,
15883 element = this.$input[ 0 ];
15884 this.focus();
15885 if ( element.selectionStart !== undefined ) {
15886 element.selectionStart = element.selectionEnd = element.value.length;
15887 } else if ( element.createTextRange ) {
15888 // IE 8 and below
15889 textRange = element.createTextRange();
15890 textRange.collapse( false );
15891 textRange.select();
15892 }
15893 };
15894
15895 /**
15896 * Set the validation pattern.
15897 *
15898 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15899 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15900 * value must contain only numbers).
15901 *
15902 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15903 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15904 */
15905 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15906 if ( validate instanceof RegExp || validate instanceof Function ) {
15907 this.validate = validate;
15908 } else {
15909 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15910 }
15911 };
15912
15913 /**
15914 * Sets the 'invalid' flag appropriately.
15915 *
15916 * @param {boolean} [isValid] Optionally override validation result
15917 */
15918 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15919 var widget = this,
15920 setFlag = function ( valid ) {
15921 if ( !valid ) {
15922 widget.$input.attr( 'aria-invalid', 'true' );
15923 } else {
15924 widget.$input.removeAttr( 'aria-invalid' );
15925 }
15926 widget.setFlags( { invalid: !valid } );
15927 };
15928
15929 if ( isValid !== undefined ) {
15930 setFlag( isValid );
15931 } else {
15932 this.getValidity().then( function () {
15933 setFlag( true );
15934 }, function () {
15935 setFlag( false );
15936 } );
15937 }
15938 };
15939
15940 /**
15941 * Check if a value is valid.
15942 *
15943 * This method returns a promise that resolves with a boolean `true` if the current value is
15944 * considered valid according to the supplied {@link #validate validation pattern}.
15945 *
15946 * @deprecated
15947 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15948 */
15949 OO.ui.TextInputWidget.prototype.isValid = function () {
15950 var result;
15951
15952 if ( this.validate instanceof Function ) {
15953 result = this.validate( this.getValue() );
15954 if ( $.isFunction( result.promise ) ) {
15955 return result.promise();
15956 } else {
15957 return $.Deferred().resolve( !!result ).promise();
15958 }
15959 } else {
15960 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15961 }
15962 };
15963
15964 /**
15965 * Get the validity of current value.
15966 *
15967 * This method returns a promise that resolves if the value is valid and rejects if
15968 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15969 *
15970 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15971 */
15972 OO.ui.TextInputWidget.prototype.getValidity = function () {
15973 var result, promise;
15974
15975 function rejectOrResolve( valid ) {
15976 if ( valid ) {
15977 return $.Deferred().resolve().promise();
15978 } else {
15979 return $.Deferred().reject().promise();
15980 }
15981 }
15982
15983 if ( this.validate instanceof Function ) {
15984 result = this.validate( this.getValue() );
15985
15986 if ( $.isFunction( result.promise ) ) {
15987 promise = $.Deferred();
15988
15989 result.then( function ( valid ) {
15990 if ( valid ) {
15991 promise.resolve();
15992 } else {
15993 promise.reject();
15994 }
15995 }, function () {
15996 promise.reject();
15997 } );
15998
15999 return promise.promise();
16000 } else {
16001 return rejectOrResolve( result );
16002 }
16003 } else {
16004 return rejectOrResolve( this.getValue().match( this.validate ) );
16005 }
16006 };
16007
16008 /**
16009 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16010 *
16011 * @param {string} labelPosition Label position, 'before' or 'after'
16012 * @chainable
16013 */
16014 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16015 this.labelPosition = labelPosition;
16016 this.updatePosition();
16017 return this;
16018 };
16019
16020 /**
16021 * Deprecated alias of #setLabelPosition
16022 *
16023 * @deprecated Use setLabelPosition instead.
16024 */
16025 OO.ui.TextInputWidget.prototype.setPosition =
16026 OO.ui.TextInputWidget.prototype.setLabelPosition;
16027
16028 /**
16029 * Update the position of the inline label.
16030 *
16031 * This method is called by #setLabelPosition, and can also be called on its own if
16032 * something causes the label to be mispositioned.
16033 *
16034 * @chainable
16035 */
16036 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16037 var after = this.labelPosition === 'after';
16038
16039 this.$element
16040 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16041 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16042
16043 this.positionLabel();
16044
16045 return this;
16046 };
16047
16048 /**
16049 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16050 * already empty or when it's not editable.
16051 */
16052 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16053 if ( this.type === 'search' ) {
16054 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16055 this.setIndicator( null );
16056 } else {
16057 this.setIndicator( 'clear' );
16058 }
16059 }
16060 };
16061
16062 /**
16063 * Position the label by setting the correct padding on the input.
16064 *
16065 * @private
16066 * @chainable
16067 */
16068 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16069 var after, rtl, property;
16070 // Clear old values
16071 this.$input
16072 // Clear old values if present
16073 .css( {
16074 'padding-right': '',
16075 'padding-left': ''
16076 } );
16077
16078 if ( this.label ) {
16079 this.$element.append( this.$label );
16080 } else {
16081 this.$label.detach();
16082 return;
16083 }
16084
16085 after = this.labelPosition === 'after';
16086 rtl = this.$element.css( 'direction' ) === 'rtl';
16087 property = after === rtl ? 'padding-left' : 'padding-right';
16088
16089 this.$input.css( property, this.$label.outerWidth( true ) );
16090
16091 return this;
16092 };
16093
16094 /**
16095 * @inheritdoc
16096 */
16097 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
16098 var
16099 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
16100 $input = $( node ).find( '.oo-ui-inputWidget-input' );
16101 state.$input = $input; // shortcut for performance, used in InputWidget
16102 if ( this.multiline ) {
16103 state.scrollTop = $input.scrollTop();
16104 }
16105 return state;
16106 };
16107
16108 /**
16109 * @inheritdoc
16110 */
16111 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16112 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16113 if ( state.scrollTop !== undefined ) {
16114 this.$input.scrollTop( state.scrollTop );
16115 }
16116 };
16117
16118 /**
16119 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16120 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16121 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16122 *
16123 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16124 * option, that option will appear to be selected.
16125 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16126 * input field.
16127 *
16128 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16129 *
16130 * @example
16131 * // Example: A ComboBoxWidget.
16132 * var comboBox = new OO.ui.ComboBoxWidget( {
16133 * label: 'ComboBoxWidget',
16134 * input: { value: 'Option One' },
16135 * menu: {
16136 * items: [
16137 * new OO.ui.MenuOptionWidget( {
16138 * data: 'Option 1',
16139 * label: 'Option One'
16140 * } ),
16141 * new OO.ui.MenuOptionWidget( {
16142 * data: 'Option 2',
16143 * label: 'Option Two'
16144 * } ),
16145 * new OO.ui.MenuOptionWidget( {
16146 * data: 'Option 3',
16147 * label: 'Option Three'
16148 * } ),
16149 * new OO.ui.MenuOptionWidget( {
16150 * data: 'Option 4',
16151 * label: 'Option Four'
16152 * } ),
16153 * new OO.ui.MenuOptionWidget( {
16154 * data: 'Option 5',
16155 * label: 'Option Five'
16156 * } )
16157 * ]
16158 * }
16159 * } );
16160 * $( 'body' ).append( comboBox.$element );
16161 *
16162 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16163 *
16164 * @class
16165 * @extends OO.ui.Widget
16166 * @mixins OO.ui.mixin.TabIndexedElement
16167 *
16168 * @constructor
16169 * @param {Object} [config] Configuration options
16170 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16171 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16172 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16173 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16174 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16175 */
16176 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
16177 // Configuration initialization
16178 config = config || {};
16179
16180 // Parent constructor
16181 OO.ui.ComboBoxWidget.parent.call( this, config );
16182
16183 // Properties (must be set before TabIndexedElement constructor call)
16184 this.$indicator = this.$( '<span>' );
16185
16186 // Mixin constructors
16187 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
16188
16189 // Properties
16190 this.$overlay = config.$overlay || this.$element;
16191 this.input = new OO.ui.TextInputWidget( $.extend(
16192 {
16193 indicator: 'down',
16194 $indicator: this.$indicator,
16195 disabled: this.isDisabled()
16196 },
16197 config.input
16198 ) );
16199 this.input.$input.eq( 0 ).attr( {
16200 role: 'combobox',
16201 'aria-autocomplete': 'list'
16202 } );
16203 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16204 {
16205 widget: this,
16206 input: this.input,
16207 $container: this.input.$element,
16208 disabled: this.isDisabled()
16209 },
16210 config.menu
16211 ) );
16212
16213 // Events
16214 this.$indicator.on( {
16215 click: this.onClick.bind( this ),
16216 keypress: this.onKeyPress.bind( this )
16217 } );
16218 this.input.connect( this, {
16219 change: 'onInputChange',
16220 enter: 'onInputEnter'
16221 } );
16222 this.menu.connect( this, {
16223 choose: 'onMenuChoose',
16224 add: 'onMenuItemsChange',
16225 remove: 'onMenuItemsChange'
16226 } );
16227
16228 // Initialization
16229 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
16230 this.$overlay.append( this.menu.$element );
16231 this.onMenuItemsChange();
16232 };
16233
16234 /* Setup */
16235
16236 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16237 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16238
16239 /* Methods */
16240
16241 /**
16242 * Get the combobox's menu.
16243 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16244 */
16245 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16246 return this.menu;
16247 };
16248
16249 /**
16250 * Get the combobox's text input widget.
16251 * @return {OO.ui.TextInputWidget} Text input widget
16252 */
16253 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16254 return this.input;
16255 };
16256
16257 /**
16258 * Handle input change events.
16259 *
16260 * @private
16261 * @param {string} value New value
16262 */
16263 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16264 var match = this.menu.getItemFromData( value );
16265
16266 this.menu.selectItem( match );
16267 if ( this.menu.getHighlightedItem() ) {
16268 this.menu.highlightItem( match );
16269 }
16270
16271 if ( !this.isDisabled() ) {
16272 this.menu.toggle( true );
16273 }
16274 };
16275
16276 /**
16277 * Handle mouse click events.
16278 *
16279 * @private
16280 * @param {jQuery.Event} e Mouse click event
16281 */
16282 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16283 if ( !this.isDisabled() && e.which === 1 ) {
16284 this.menu.toggle();
16285 this.input.$input[ 0 ].focus();
16286 }
16287 return false;
16288 };
16289
16290 /**
16291 * Handle key press events.
16292 *
16293 * @private
16294 * @param {jQuery.Event} e Key press event
16295 */
16296 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16297 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16298 this.menu.toggle();
16299 this.input.$input[ 0 ].focus();
16300 return false;
16301 }
16302 };
16303
16304 /**
16305 * Handle input enter events.
16306 *
16307 * @private
16308 */
16309 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16310 if ( !this.isDisabled() ) {
16311 this.menu.toggle( false );
16312 }
16313 };
16314
16315 /**
16316 * Handle menu choose events.
16317 *
16318 * @private
16319 * @param {OO.ui.OptionWidget} item Chosen item
16320 */
16321 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16322 this.input.setValue( item.getData() );
16323 };
16324
16325 /**
16326 * Handle menu item change events.
16327 *
16328 * @private
16329 */
16330 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16331 var match = this.menu.getItemFromData( this.input.getValue() );
16332 this.menu.selectItem( match );
16333 if ( this.menu.getHighlightedItem() ) {
16334 this.menu.highlightItem( match );
16335 }
16336 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16337 };
16338
16339 /**
16340 * @inheritdoc
16341 */
16342 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16343 // Parent method
16344 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16345
16346 if ( this.input ) {
16347 this.input.setDisabled( this.isDisabled() );
16348 }
16349 if ( this.menu ) {
16350 this.menu.setDisabled( this.isDisabled() );
16351 }
16352
16353 return this;
16354 };
16355
16356 /**
16357 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16358 * be configured with a `label` option that is set to a string, a label node, or a function:
16359 *
16360 * - String: a plaintext string
16361 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16362 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16363 * - Function: a function that will produce a string in the future. Functions are used
16364 * in cases where the value of the label is not currently defined.
16365 *
16366 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16367 * will come into focus when the label is clicked.
16368 *
16369 * @example
16370 * // Examples of LabelWidgets
16371 * var label1 = new OO.ui.LabelWidget( {
16372 * label: 'plaintext label'
16373 * } );
16374 * var label2 = new OO.ui.LabelWidget( {
16375 * label: $( '<a href="default.html">jQuery label</a>' )
16376 * } );
16377 * // Create a fieldset layout with fields for each example
16378 * var fieldset = new OO.ui.FieldsetLayout();
16379 * fieldset.addItems( [
16380 * new OO.ui.FieldLayout( label1 ),
16381 * new OO.ui.FieldLayout( label2 )
16382 * ] );
16383 * $( 'body' ).append( fieldset.$element );
16384 *
16385 * @class
16386 * @extends OO.ui.Widget
16387 * @mixins OO.ui.mixin.LabelElement
16388 *
16389 * @constructor
16390 * @param {Object} [config] Configuration options
16391 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16392 * Clicking the label will focus the specified input field.
16393 */
16394 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16395 // Configuration initialization
16396 config = config || {};
16397
16398 // Parent constructor
16399 OO.ui.LabelWidget.parent.call( this, config );
16400
16401 // Mixin constructors
16402 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16403 OO.ui.mixin.TitledElement.call( this, config );
16404
16405 // Properties
16406 this.input = config.input;
16407
16408 // Events
16409 if ( this.input instanceof OO.ui.InputWidget ) {
16410 this.$element.on( 'click', this.onClick.bind( this ) );
16411 }
16412
16413 // Initialization
16414 this.$element.addClass( 'oo-ui-labelWidget' );
16415 };
16416
16417 /* Setup */
16418
16419 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16420 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16421 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16422
16423 /* Static Properties */
16424
16425 OO.ui.LabelWidget.static.tagName = 'span';
16426
16427 /* Methods */
16428
16429 /**
16430 * Handles label mouse click events.
16431 *
16432 * @private
16433 * @param {jQuery.Event} e Mouse click event
16434 */
16435 OO.ui.LabelWidget.prototype.onClick = function () {
16436 this.input.simulateLabelClick();
16437 return false;
16438 };
16439
16440 /**
16441 * OptionWidgets are special elements that can be selected and configured with data. The
16442 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16443 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16444 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16445 *
16446 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16447 *
16448 * @class
16449 * @extends OO.ui.Widget
16450 * @mixins OO.ui.mixin.LabelElement
16451 * @mixins OO.ui.mixin.FlaggedElement
16452 *
16453 * @constructor
16454 * @param {Object} [config] Configuration options
16455 */
16456 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16457 // Configuration initialization
16458 config = config || {};
16459
16460 // Parent constructor
16461 OO.ui.OptionWidget.parent.call( this, config );
16462
16463 // Mixin constructors
16464 OO.ui.mixin.ItemWidget.call( this );
16465 OO.ui.mixin.LabelElement.call( this, config );
16466 OO.ui.mixin.FlaggedElement.call( this, config );
16467
16468 // Properties
16469 this.selected = false;
16470 this.highlighted = false;
16471 this.pressed = false;
16472
16473 // Initialization
16474 this.$element
16475 .data( 'oo-ui-optionWidget', this )
16476 .attr( 'role', 'option' )
16477 .attr( 'aria-selected', 'false' )
16478 .addClass( 'oo-ui-optionWidget' )
16479 .append( this.$label );
16480 };
16481
16482 /* Setup */
16483
16484 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16485 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16486 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16487 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16488
16489 /* Static Properties */
16490
16491 OO.ui.OptionWidget.static.selectable = true;
16492
16493 OO.ui.OptionWidget.static.highlightable = true;
16494
16495 OO.ui.OptionWidget.static.pressable = true;
16496
16497 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16498
16499 /* Methods */
16500
16501 /**
16502 * Check if the option can be selected.
16503 *
16504 * @return {boolean} Item is selectable
16505 */
16506 OO.ui.OptionWidget.prototype.isSelectable = function () {
16507 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16508 };
16509
16510 /**
16511 * Check if the option can be highlighted. A highlight indicates that the option
16512 * may be selected when a user presses enter or clicks. Disabled items cannot
16513 * be highlighted.
16514 *
16515 * @return {boolean} Item is highlightable
16516 */
16517 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16518 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16519 };
16520
16521 /**
16522 * Check if the option can be pressed. The pressed state occurs when a user mouses
16523 * down on an item, but has not yet let go of the mouse.
16524 *
16525 * @return {boolean} Item is pressable
16526 */
16527 OO.ui.OptionWidget.prototype.isPressable = function () {
16528 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16529 };
16530
16531 /**
16532 * Check if the option is selected.
16533 *
16534 * @return {boolean} Item is selected
16535 */
16536 OO.ui.OptionWidget.prototype.isSelected = function () {
16537 return this.selected;
16538 };
16539
16540 /**
16541 * Check if the option is highlighted. A highlight indicates that the
16542 * item may be selected when a user presses enter or clicks.
16543 *
16544 * @return {boolean} Item is highlighted
16545 */
16546 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16547 return this.highlighted;
16548 };
16549
16550 /**
16551 * Check if the option is pressed. The pressed state occurs when a user mouses
16552 * down on an item, but has not yet let go of the mouse. The item may appear
16553 * selected, but it will not be selected until the user releases the mouse.
16554 *
16555 * @return {boolean} Item is pressed
16556 */
16557 OO.ui.OptionWidget.prototype.isPressed = function () {
16558 return this.pressed;
16559 };
16560
16561 /**
16562 * Set the option’s selected state. In general, all modifications to the selection
16563 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16564 * method instead of this method.
16565 *
16566 * @param {boolean} [state=false] Select option
16567 * @chainable
16568 */
16569 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16570 if ( this.constructor.static.selectable ) {
16571 this.selected = !!state;
16572 this.$element
16573 .toggleClass( 'oo-ui-optionWidget-selected', state )
16574 .attr( 'aria-selected', state.toString() );
16575 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16576 this.scrollElementIntoView();
16577 }
16578 this.updateThemeClasses();
16579 }
16580 return this;
16581 };
16582
16583 /**
16584 * Set the option’s highlighted state. In general, all programmatic
16585 * modifications to the highlight should be handled by the
16586 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16587 * method instead of this method.
16588 *
16589 * @param {boolean} [state=false] Highlight option
16590 * @chainable
16591 */
16592 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16593 if ( this.constructor.static.highlightable ) {
16594 this.highlighted = !!state;
16595 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16596 this.updateThemeClasses();
16597 }
16598 return this;
16599 };
16600
16601 /**
16602 * Set the option’s pressed state. In general, all
16603 * programmatic modifications to the pressed state should be handled by the
16604 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16605 * method instead of this method.
16606 *
16607 * @param {boolean} [state=false] Press option
16608 * @chainable
16609 */
16610 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16611 if ( this.constructor.static.pressable ) {
16612 this.pressed = !!state;
16613 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16614 this.updateThemeClasses();
16615 }
16616 return this;
16617 };
16618
16619 /**
16620 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16621 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16622 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16623 * options. For more information about options and selects, please see the
16624 * [OOjs UI documentation on MediaWiki][1].
16625 *
16626 * @example
16627 * // Decorated options in a select widget
16628 * var select = new OO.ui.SelectWidget( {
16629 * items: [
16630 * new OO.ui.DecoratedOptionWidget( {
16631 * data: 'a',
16632 * label: 'Option with icon',
16633 * icon: 'help'
16634 * } ),
16635 * new OO.ui.DecoratedOptionWidget( {
16636 * data: 'b',
16637 * label: 'Option with indicator',
16638 * indicator: 'next'
16639 * } )
16640 * ]
16641 * } );
16642 * $( 'body' ).append( select.$element );
16643 *
16644 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16645 *
16646 * @class
16647 * @extends OO.ui.OptionWidget
16648 * @mixins OO.ui.mixin.IconElement
16649 * @mixins OO.ui.mixin.IndicatorElement
16650 *
16651 * @constructor
16652 * @param {Object} [config] Configuration options
16653 */
16654 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16655 // Parent constructor
16656 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16657
16658 // Mixin constructors
16659 OO.ui.mixin.IconElement.call( this, config );
16660 OO.ui.mixin.IndicatorElement.call( this, config );
16661
16662 // Initialization
16663 this.$element
16664 .addClass( 'oo-ui-decoratedOptionWidget' )
16665 .prepend( this.$icon )
16666 .append( this.$indicator );
16667 };
16668
16669 /* Setup */
16670
16671 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16672 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16673 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16674
16675 /**
16676 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16677 * can be selected and configured with data. The class is
16678 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16679 * [OOjs UI documentation on MediaWiki] [1] for more information.
16680 *
16681 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16682 *
16683 * @class
16684 * @extends OO.ui.DecoratedOptionWidget
16685 * @mixins OO.ui.mixin.ButtonElement
16686 * @mixins OO.ui.mixin.TabIndexedElement
16687 * @mixins OO.ui.mixin.TitledElement
16688 *
16689 * @constructor
16690 * @param {Object} [config] Configuration options
16691 */
16692 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16693 // Configuration initialization
16694 config = config || {};
16695
16696 // Parent constructor
16697 OO.ui.ButtonOptionWidget.parent.call( this, config );
16698
16699 // Mixin constructors
16700 OO.ui.mixin.ButtonElement.call( this, config );
16701 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16702 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16703 $tabIndexed: this.$button,
16704 tabIndex: -1
16705 } ) );
16706
16707 // Initialization
16708 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16709 this.$button.append( this.$element.contents() );
16710 this.$element.append( this.$button );
16711 };
16712
16713 /* Setup */
16714
16715 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16716 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16717 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16718 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16719
16720 /* Static Properties */
16721
16722 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16723 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16724
16725 OO.ui.ButtonOptionWidget.static.highlightable = false;
16726
16727 /* Methods */
16728
16729 /**
16730 * @inheritdoc
16731 */
16732 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16733 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16734
16735 if ( this.constructor.static.selectable ) {
16736 this.setActive( state );
16737 }
16738
16739 return this;
16740 };
16741
16742 /**
16743 * RadioOptionWidget is an option widget that looks like a radio button.
16744 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16745 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16746 *
16747 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16748 *
16749 * @class
16750 * @extends OO.ui.OptionWidget
16751 *
16752 * @constructor
16753 * @param {Object} [config] Configuration options
16754 */
16755 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16756 // Configuration initialization
16757 config = config || {};
16758
16759 // Properties (must be done before parent constructor which calls #setDisabled)
16760 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16761
16762 // Parent constructor
16763 OO.ui.RadioOptionWidget.parent.call( this, config );
16764
16765 // Events
16766 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16767
16768 // Initialization
16769 // Remove implicit role, we're handling it ourselves
16770 this.radio.$input.attr( 'role', 'presentation' );
16771 this.$element
16772 .addClass( 'oo-ui-radioOptionWidget' )
16773 .attr( 'role', 'radio' )
16774 .attr( 'aria-checked', 'false' )
16775 .removeAttr( 'aria-selected' )
16776 .prepend( this.radio.$element );
16777 };
16778
16779 /* Setup */
16780
16781 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16782
16783 /* Static Properties */
16784
16785 OO.ui.RadioOptionWidget.static.highlightable = false;
16786
16787 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16788
16789 OO.ui.RadioOptionWidget.static.pressable = false;
16790
16791 OO.ui.RadioOptionWidget.static.tagName = 'label';
16792
16793 /* Methods */
16794
16795 /**
16796 * @param {jQuery.Event} e Focus event
16797 * @private
16798 */
16799 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16800 this.radio.$input.blur();
16801 this.$element.parent().focus();
16802 };
16803
16804 /**
16805 * @inheritdoc
16806 */
16807 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16808 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16809
16810 this.radio.setSelected( state );
16811 this.$element
16812 .attr( 'aria-checked', state.toString() )
16813 .removeAttr( 'aria-selected' );
16814
16815 return this;
16816 };
16817
16818 /**
16819 * @inheritdoc
16820 */
16821 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16822 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16823
16824 this.radio.setDisabled( this.isDisabled() );
16825
16826 return this;
16827 };
16828
16829 /**
16830 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16831 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16832 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16833 *
16834 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16835 *
16836 * @class
16837 * @extends OO.ui.DecoratedOptionWidget
16838 *
16839 * @constructor
16840 * @param {Object} [config] Configuration options
16841 */
16842 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16843 // Configuration initialization
16844 config = $.extend( { icon: 'check' }, config );
16845
16846 // Parent constructor
16847 OO.ui.MenuOptionWidget.parent.call( this, config );
16848
16849 // Initialization
16850 this.$element
16851 .attr( 'role', 'menuitem' )
16852 .addClass( 'oo-ui-menuOptionWidget' );
16853 };
16854
16855 /* Setup */
16856
16857 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16858
16859 /* Static Properties */
16860
16861 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16862
16863 /**
16864 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16865 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16866 *
16867 * @example
16868 * var myDropdown = new OO.ui.DropdownWidget( {
16869 * menu: {
16870 * items: [
16871 * new OO.ui.MenuSectionOptionWidget( {
16872 * label: 'Dogs'
16873 * } ),
16874 * new OO.ui.MenuOptionWidget( {
16875 * data: 'corgi',
16876 * label: 'Welsh Corgi'
16877 * } ),
16878 * new OO.ui.MenuOptionWidget( {
16879 * data: 'poodle',
16880 * label: 'Standard Poodle'
16881 * } ),
16882 * new OO.ui.MenuSectionOptionWidget( {
16883 * label: 'Cats'
16884 * } ),
16885 * new OO.ui.MenuOptionWidget( {
16886 * data: 'lion',
16887 * label: 'Lion'
16888 * } )
16889 * ]
16890 * }
16891 * } );
16892 * $( 'body' ).append( myDropdown.$element );
16893 *
16894 * @class
16895 * @extends OO.ui.DecoratedOptionWidget
16896 *
16897 * @constructor
16898 * @param {Object} [config] Configuration options
16899 */
16900 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16901 // Parent constructor
16902 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16903
16904 // Initialization
16905 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16906 };
16907
16908 /* Setup */
16909
16910 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16911
16912 /* Static Properties */
16913
16914 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16915
16916 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16917
16918 /**
16919 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16920 *
16921 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16922 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16923 * for an example.
16924 *
16925 * @class
16926 * @extends OO.ui.DecoratedOptionWidget
16927 *
16928 * @constructor
16929 * @param {Object} [config] Configuration options
16930 * @cfg {number} [level] Indentation level
16931 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16932 */
16933 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16934 // Configuration initialization
16935 config = config || {};
16936
16937 // Parent constructor
16938 OO.ui.OutlineOptionWidget.parent.call( this, config );
16939
16940 // Properties
16941 this.level = 0;
16942 this.movable = !!config.movable;
16943 this.removable = !!config.removable;
16944
16945 // Initialization
16946 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16947 this.setLevel( config.level );
16948 };
16949
16950 /* Setup */
16951
16952 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16953
16954 /* Static Properties */
16955
16956 OO.ui.OutlineOptionWidget.static.highlightable = false;
16957
16958 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16959
16960 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16961
16962 OO.ui.OutlineOptionWidget.static.levels = 3;
16963
16964 /* Methods */
16965
16966 /**
16967 * Check if item is movable.
16968 *
16969 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16970 *
16971 * @return {boolean} Item is movable
16972 */
16973 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16974 return this.movable;
16975 };
16976
16977 /**
16978 * Check if item is removable.
16979 *
16980 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16981 *
16982 * @return {boolean} Item is removable
16983 */
16984 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16985 return this.removable;
16986 };
16987
16988 /**
16989 * Get indentation level.
16990 *
16991 * @return {number} Indentation level
16992 */
16993 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16994 return this.level;
16995 };
16996
16997 /**
16998 * Set movability.
16999 *
17000 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17001 *
17002 * @param {boolean} movable Item is movable
17003 * @chainable
17004 */
17005 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17006 this.movable = !!movable;
17007 this.updateThemeClasses();
17008 return this;
17009 };
17010
17011 /**
17012 * Set removability.
17013 *
17014 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17015 *
17016 * @param {boolean} movable Item is removable
17017 * @chainable
17018 */
17019 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17020 this.removable = !!removable;
17021 this.updateThemeClasses();
17022 return this;
17023 };
17024
17025 /**
17026 * Set indentation level.
17027 *
17028 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17029 * @chainable
17030 */
17031 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17032 var levels = this.constructor.static.levels,
17033 levelClass = this.constructor.static.levelClass,
17034 i = levels;
17035
17036 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17037 while ( i-- ) {
17038 if ( this.level === i ) {
17039 this.$element.addClass( levelClass + i );
17040 } else {
17041 this.$element.removeClass( levelClass + i );
17042 }
17043 }
17044 this.updateThemeClasses();
17045
17046 return this;
17047 };
17048
17049 /**
17050 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17051 *
17052 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17053 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17054 * for an example.
17055 *
17056 * @class
17057 * @extends OO.ui.OptionWidget
17058 *
17059 * @constructor
17060 * @param {Object} [config] Configuration options
17061 */
17062 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17063 // Configuration initialization
17064 config = config || {};
17065
17066 // Parent constructor
17067 OO.ui.TabOptionWidget.parent.call( this, config );
17068
17069 // Initialization
17070 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17071 };
17072
17073 /* Setup */
17074
17075 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17076
17077 /* Static Properties */
17078
17079 OO.ui.TabOptionWidget.static.highlightable = false;
17080
17081 /**
17082 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17083 * By default, each popup has an anchor that points toward its origin.
17084 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17085 *
17086 * @example
17087 * // A popup widget.
17088 * var popup = new OO.ui.PopupWidget( {
17089 * $content: $( '<p>Hi there!</p>' ),
17090 * padded: true,
17091 * width: 300
17092 * } );
17093 *
17094 * $( 'body' ).append( popup.$element );
17095 * // To display the popup, toggle the visibility to 'true'.
17096 * popup.toggle( true );
17097 *
17098 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17099 *
17100 * @class
17101 * @extends OO.ui.Widget
17102 * @mixins OO.ui.mixin.LabelElement
17103 * @mixins OO.ui.mixin.ClippableElement
17104 *
17105 * @constructor
17106 * @param {Object} [config] Configuration options
17107 * @cfg {number} [width=320] Width of popup in pixels
17108 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17109 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17110 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17111 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17112 * popup is leaning towards the right of the screen.
17113 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17114 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17115 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17116 * sentence in the given language.
17117 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17118 * See the [OOjs UI docs on MediaWiki][3] for an example.
17119 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17120 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17121 * @cfg {jQuery} [$content] Content to append to the popup's body
17122 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17123 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17124 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17125 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17126 * for an example.
17127 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17128 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17129 * button.
17130 * @cfg {boolean} [padded] Add padding to the popup's body
17131 */
17132 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17133 // Configuration initialization
17134 config = config || {};
17135
17136 // Parent constructor
17137 OO.ui.PopupWidget.parent.call( this, config );
17138
17139 // Properties (must be set before ClippableElement constructor call)
17140 this.$body = $( '<div>' );
17141 this.$popup = $( '<div>' );
17142
17143 // Mixin constructors
17144 OO.ui.mixin.LabelElement.call( this, config );
17145 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17146 $clippable: this.$body,
17147 $clippableContainer: this.$popup
17148 } ) );
17149
17150 // Properties
17151 this.$head = $( '<div>' );
17152 this.$footer = $( '<div>' );
17153 this.$anchor = $( '<div>' );
17154 // If undefined, will be computed lazily in updateDimensions()
17155 this.$container = config.$container;
17156 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17157 this.autoClose = !!config.autoClose;
17158 this.$autoCloseIgnore = config.$autoCloseIgnore;
17159 this.transitionTimeout = null;
17160 this.anchor = null;
17161 this.width = config.width !== undefined ? config.width : 320;
17162 this.height = config.height !== undefined ? config.height : null;
17163 this.setAlignment( config.align );
17164 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17165 this.onMouseDownHandler = this.onMouseDown.bind( this );
17166 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17167
17168 // Events
17169 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17170
17171 // Initialization
17172 this.toggleAnchor( config.anchor === undefined || config.anchor );
17173 this.$body.addClass( 'oo-ui-popupWidget-body' );
17174 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17175 this.$head
17176 .addClass( 'oo-ui-popupWidget-head' )
17177 .append( this.$label, this.closeButton.$element );
17178 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17179 if ( !config.head ) {
17180 this.$head.addClass( 'oo-ui-element-hidden' );
17181 }
17182 if ( !config.$footer ) {
17183 this.$footer.addClass( 'oo-ui-element-hidden' );
17184 }
17185 this.$popup
17186 .addClass( 'oo-ui-popupWidget-popup' )
17187 .append( this.$head, this.$body, this.$footer );
17188 this.$element
17189 .addClass( 'oo-ui-popupWidget' )
17190 .append( this.$popup, this.$anchor );
17191 // Move content, which was added to #$element by OO.ui.Widget, to the body
17192 if ( config.$content instanceof jQuery ) {
17193 this.$body.append( config.$content );
17194 }
17195 if ( config.$footer instanceof jQuery ) {
17196 this.$footer.append( config.$footer );
17197 }
17198 if ( config.padded ) {
17199 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17200 }
17201
17202 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17203 // that reference properties not initialized at that time of parent class construction
17204 // TODO: Find a better way to handle post-constructor setup
17205 this.visible = false;
17206 this.$element.addClass( 'oo-ui-element-hidden' );
17207 };
17208
17209 /* Setup */
17210
17211 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17212 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17213 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17214
17215 /* Methods */
17216
17217 /**
17218 * Handles mouse down events.
17219 *
17220 * @private
17221 * @param {MouseEvent} e Mouse down event
17222 */
17223 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17224 if (
17225 this.isVisible() &&
17226 !$.contains( this.$element[ 0 ], e.target ) &&
17227 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17228 ) {
17229 this.toggle( false );
17230 }
17231 };
17232
17233 /**
17234 * Bind mouse down listener.
17235 *
17236 * @private
17237 */
17238 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17239 // Capture clicks outside popup
17240 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17241 };
17242
17243 /**
17244 * Handles close button click events.
17245 *
17246 * @private
17247 */
17248 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17249 if ( this.isVisible() ) {
17250 this.toggle( false );
17251 }
17252 };
17253
17254 /**
17255 * Unbind mouse down listener.
17256 *
17257 * @private
17258 */
17259 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17260 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17261 };
17262
17263 /**
17264 * Handles key down events.
17265 *
17266 * @private
17267 * @param {KeyboardEvent} e Key down event
17268 */
17269 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17270 if (
17271 e.which === OO.ui.Keys.ESCAPE &&
17272 this.isVisible()
17273 ) {
17274 this.toggle( false );
17275 e.preventDefault();
17276 e.stopPropagation();
17277 }
17278 };
17279
17280 /**
17281 * Bind key down listener.
17282 *
17283 * @private
17284 */
17285 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17286 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17287 };
17288
17289 /**
17290 * Unbind key down listener.
17291 *
17292 * @private
17293 */
17294 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17295 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17296 };
17297
17298 /**
17299 * Show, hide, or toggle the visibility of the anchor.
17300 *
17301 * @param {boolean} [show] Show anchor, omit to toggle
17302 */
17303 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17304 show = show === undefined ? !this.anchored : !!show;
17305
17306 if ( this.anchored !== show ) {
17307 if ( show ) {
17308 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17309 } else {
17310 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17311 }
17312 this.anchored = show;
17313 }
17314 };
17315
17316 /**
17317 * Check if the anchor is visible.
17318 *
17319 * @return {boolean} Anchor is visible
17320 */
17321 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17322 return this.anchor;
17323 };
17324
17325 /**
17326 * @inheritdoc
17327 */
17328 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17329 var change;
17330 show = show === undefined ? !this.isVisible() : !!show;
17331
17332 change = show !== this.isVisible();
17333
17334 // Parent method
17335 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17336
17337 if ( change ) {
17338 if ( show ) {
17339 if ( this.autoClose ) {
17340 this.bindMouseDownListener();
17341 this.bindKeyDownListener();
17342 }
17343 this.updateDimensions();
17344 this.toggleClipping( true );
17345 } else {
17346 this.toggleClipping( false );
17347 if ( this.autoClose ) {
17348 this.unbindMouseDownListener();
17349 this.unbindKeyDownListener();
17350 }
17351 }
17352 }
17353
17354 return this;
17355 };
17356
17357 /**
17358 * Set the size of the popup.
17359 *
17360 * Changing the size may also change the popup's position depending on the alignment.
17361 *
17362 * @param {number} width Width in pixels
17363 * @param {number} height Height in pixels
17364 * @param {boolean} [transition=false] Use a smooth transition
17365 * @chainable
17366 */
17367 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17368 this.width = width;
17369 this.height = height !== undefined ? height : null;
17370 if ( this.isVisible() ) {
17371 this.updateDimensions( transition );
17372 }
17373 };
17374
17375 /**
17376 * Update the size and position.
17377 *
17378 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17379 * be called automatically.
17380 *
17381 * @param {boolean} [transition=false] Use a smooth transition
17382 * @chainable
17383 */
17384 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17385 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17386 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17387 align = this.align,
17388 widget = this;
17389
17390 if ( !this.$container ) {
17391 // Lazy-initialize $container if not specified in constructor
17392 this.$container = $( this.getClosestScrollableElementContainer() );
17393 }
17394
17395 // Set height and width before measuring things, since it might cause our measurements
17396 // to change (e.g. due to scrollbars appearing or disappearing)
17397 this.$popup.css( {
17398 width: this.width,
17399 height: this.height !== null ? this.height : 'auto'
17400 } );
17401
17402 // If we are in RTL, we need to flip the alignment, unless it is center
17403 if ( align === 'forwards' || align === 'backwards' ) {
17404 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17405 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17406 } else {
17407 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17408 }
17409
17410 }
17411
17412 // Compute initial popupOffset based on alignment
17413 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17414
17415 // Figure out if this will cause the popup to go beyond the edge of the container
17416 originOffset = this.$element.offset().left;
17417 containerLeft = this.$container.offset().left;
17418 containerWidth = this.$container.innerWidth();
17419 containerRight = containerLeft + containerWidth;
17420 popupLeft = popupOffset - this.containerPadding;
17421 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17422 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17423 overlapRight = containerRight - ( originOffset + popupRight );
17424
17425 // Adjust offset to make the popup not go beyond the edge, if needed
17426 if ( overlapRight < 0 ) {
17427 popupOffset += overlapRight;
17428 } else if ( overlapLeft < 0 ) {
17429 popupOffset -= overlapLeft;
17430 }
17431
17432 // Adjust offset to avoid anchor being rendered too close to the edge
17433 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17434 // TODO: Find a measurement that works for CSS anchors and image anchors
17435 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17436 if ( popupOffset + this.width < anchorWidth ) {
17437 popupOffset = anchorWidth - this.width;
17438 } else if ( -popupOffset < anchorWidth ) {
17439 popupOffset = -anchorWidth;
17440 }
17441
17442 // Prevent transition from being interrupted
17443 clearTimeout( this.transitionTimeout );
17444 if ( transition ) {
17445 // Enable transition
17446 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17447 }
17448
17449 // Position body relative to anchor
17450 this.$popup.css( 'margin-left', popupOffset );
17451
17452 if ( transition ) {
17453 // Prevent transitioning after transition is complete
17454 this.transitionTimeout = setTimeout( function () {
17455 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17456 }, 200 );
17457 } else {
17458 // Prevent transitioning immediately
17459 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17460 }
17461
17462 // Reevaluate clipping state since we've relocated and resized the popup
17463 this.clip();
17464
17465 return this;
17466 };
17467
17468 /**
17469 * Set popup alignment
17470 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17471 * `backwards` or `forwards`.
17472 */
17473 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17474 // Validate alignment and transform deprecated values
17475 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17476 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17477 } else {
17478 this.align = 'center';
17479 }
17480 };
17481
17482 /**
17483 * Get popup alignment
17484 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17485 * `backwards` or `forwards`.
17486 */
17487 OO.ui.PopupWidget.prototype.getAlignment = function () {
17488 return this.align;
17489 };
17490
17491 /**
17492 * Progress bars visually display the status of an operation, such as a download,
17493 * and can be either determinate or indeterminate:
17494 *
17495 * - **determinate** process bars show the percent of an operation that is complete.
17496 *
17497 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17498 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17499 * not use percentages.
17500 *
17501 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17502 *
17503 * @example
17504 * // Examples of determinate and indeterminate progress bars.
17505 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17506 * progress: 33
17507 * } );
17508 * var progressBar2 = new OO.ui.ProgressBarWidget();
17509 *
17510 * // Create a FieldsetLayout to layout progress bars
17511 * var fieldset = new OO.ui.FieldsetLayout;
17512 * fieldset.addItems( [
17513 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17514 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17515 * ] );
17516 * $( 'body' ).append( fieldset.$element );
17517 *
17518 * @class
17519 * @extends OO.ui.Widget
17520 *
17521 * @constructor
17522 * @param {Object} [config] Configuration options
17523 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17524 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17525 * By default, the progress bar is indeterminate.
17526 */
17527 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17528 // Configuration initialization
17529 config = config || {};
17530
17531 // Parent constructor
17532 OO.ui.ProgressBarWidget.parent.call( this, config );
17533
17534 // Properties
17535 this.$bar = $( '<div>' );
17536 this.progress = null;
17537
17538 // Initialization
17539 this.setProgress( config.progress !== undefined ? config.progress : false );
17540 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17541 this.$element
17542 .attr( {
17543 role: 'progressbar',
17544 'aria-valuemin': 0,
17545 'aria-valuemax': 100
17546 } )
17547 .addClass( 'oo-ui-progressBarWidget' )
17548 .append( this.$bar );
17549 };
17550
17551 /* Setup */
17552
17553 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17554
17555 /* Static Properties */
17556
17557 OO.ui.ProgressBarWidget.static.tagName = 'div';
17558
17559 /* Methods */
17560
17561 /**
17562 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17563 *
17564 * @return {number|boolean} Progress percent
17565 */
17566 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17567 return this.progress;
17568 };
17569
17570 /**
17571 * Set the percent of the process completed or `false` for an indeterminate process.
17572 *
17573 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17574 */
17575 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17576 this.progress = progress;
17577
17578 if ( progress !== false ) {
17579 this.$bar.css( 'width', this.progress + '%' );
17580 this.$element.attr( 'aria-valuenow', this.progress );
17581 } else {
17582 this.$bar.css( 'width', '' );
17583 this.$element.removeAttr( 'aria-valuenow' );
17584 }
17585 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17586 };
17587
17588 /**
17589 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17590 * and a menu of search results, which is displayed beneath the query
17591 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17592 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17593 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17594 *
17595 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17596 * the [OOjs UI demos][1] for an example.
17597 *
17598 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17599 *
17600 * @class
17601 * @extends OO.ui.Widget
17602 *
17603 * @constructor
17604 * @param {Object} [config] Configuration options
17605 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17606 * @cfg {string} [value] Initial query value
17607 */
17608 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17609 // Configuration initialization
17610 config = config || {};
17611
17612 // Parent constructor
17613 OO.ui.SearchWidget.parent.call( this, config );
17614
17615 // Properties
17616 this.query = new OO.ui.TextInputWidget( {
17617 icon: 'search',
17618 placeholder: config.placeholder,
17619 value: config.value
17620 } );
17621 this.results = new OO.ui.SelectWidget();
17622 this.$query = $( '<div>' );
17623 this.$results = $( '<div>' );
17624
17625 // Events
17626 this.query.connect( this, {
17627 change: 'onQueryChange',
17628 enter: 'onQueryEnter'
17629 } );
17630 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17631
17632 // Initialization
17633 this.$query
17634 .addClass( 'oo-ui-searchWidget-query' )
17635 .append( this.query.$element );
17636 this.$results
17637 .addClass( 'oo-ui-searchWidget-results' )
17638 .append( this.results.$element );
17639 this.$element
17640 .addClass( 'oo-ui-searchWidget' )
17641 .append( this.$results, this.$query );
17642 };
17643
17644 /* Setup */
17645
17646 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17647
17648 /* Methods */
17649
17650 /**
17651 * Handle query key down events.
17652 *
17653 * @private
17654 * @param {jQuery.Event} e Key down event
17655 */
17656 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17657 var highlightedItem, nextItem,
17658 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17659
17660 if ( dir ) {
17661 highlightedItem = this.results.getHighlightedItem();
17662 if ( !highlightedItem ) {
17663 highlightedItem = this.results.getSelectedItem();
17664 }
17665 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17666 this.results.highlightItem( nextItem );
17667 nextItem.scrollElementIntoView();
17668 }
17669 };
17670
17671 /**
17672 * Handle select widget select events.
17673 *
17674 * Clears existing results. Subclasses should repopulate items according to new query.
17675 *
17676 * @private
17677 * @param {string} value New value
17678 */
17679 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17680 // Reset
17681 this.results.clearItems();
17682 };
17683
17684 /**
17685 * Handle select widget enter key events.
17686 *
17687 * Chooses highlighted item.
17688 *
17689 * @private
17690 * @param {string} value New value
17691 */
17692 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17693 var highlightedItem = this.results.getHighlightedItem();
17694 if ( highlightedItem ) {
17695 this.results.chooseItem( highlightedItem );
17696 }
17697 };
17698
17699 /**
17700 * Get the query input.
17701 *
17702 * @return {OO.ui.TextInputWidget} Query input
17703 */
17704 OO.ui.SearchWidget.prototype.getQuery = function () {
17705 return this.query;
17706 };
17707
17708 /**
17709 * Get the search results menu.
17710 *
17711 * @return {OO.ui.SelectWidget} Menu of search results
17712 */
17713 OO.ui.SearchWidget.prototype.getResults = function () {
17714 return this.results;
17715 };
17716
17717 /**
17718 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17719 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17720 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17721 * menu selects}.
17722 *
17723 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17724 * information, please see the [OOjs UI documentation on MediaWiki][1].
17725 *
17726 * @example
17727 * // Example of a select widget with three options
17728 * var select = new OO.ui.SelectWidget( {
17729 * items: [
17730 * new OO.ui.OptionWidget( {
17731 * data: 'a',
17732 * label: 'Option One',
17733 * } ),
17734 * new OO.ui.OptionWidget( {
17735 * data: 'b',
17736 * label: 'Option Two',
17737 * } ),
17738 * new OO.ui.OptionWidget( {
17739 * data: 'c',
17740 * label: 'Option Three',
17741 * } )
17742 * ]
17743 * } );
17744 * $( 'body' ).append( select.$element );
17745 *
17746 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17747 *
17748 * @abstract
17749 * @class
17750 * @extends OO.ui.Widget
17751 * @mixins OO.ui.mixin.GroupWidget
17752 *
17753 * @constructor
17754 * @param {Object} [config] Configuration options
17755 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17756 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17757 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17758 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17759 */
17760 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17761 // Configuration initialization
17762 config = config || {};
17763
17764 // Parent constructor
17765 OO.ui.SelectWidget.parent.call( this, config );
17766
17767 // Mixin constructors
17768 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17769
17770 // Properties
17771 this.pressed = false;
17772 this.selecting = null;
17773 this.onMouseUpHandler = this.onMouseUp.bind( this );
17774 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17775 this.onKeyDownHandler = this.onKeyDown.bind( this );
17776 this.onKeyPressHandler = this.onKeyPress.bind( this );
17777 this.keyPressBuffer = '';
17778 this.keyPressBufferTimer = null;
17779
17780 // Events
17781 this.connect( this, {
17782 toggle: 'onToggle'
17783 } );
17784 this.$element.on( {
17785 mousedown: this.onMouseDown.bind( this ),
17786 mouseover: this.onMouseOver.bind( this ),
17787 mouseleave: this.onMouseLeave.bind( this )
17788 } );
17789
17790 // Initialization
17791 this.$element
17792 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17793 .attr( 'role', 'listbox' );
17794 if ( Array.isArray( config.items ) ) {
17795 this.addItems( config.items );
17796 }
17797 };
17798
17799 /* Setup */
17800
17801 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17802
17803 // Need to mixin base class as well
17804 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17805 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17806
17807 /* Static */
17808 OO.ui.SelectWidget.static.passAllFilter = function () {
17809 return true;
17810 };
17811
17812 /* Events */
17813
17814 /**
17815 * @event highlight
17816 *
17817 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17818 *
17819 * @param {OO.ui.OptionWidget|null} item Highlighted item
17820 */
17821
17822 /**
17823 * @event press
17824 *
17825 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17826 * pressed state of an option.
17827 *
17828 * @param {OO.ui.OptionWidget|null} item Pressed item
17829 */
17830
17831 /**
17832 * @event select
17833 *
17834 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17835 *
17836 * @param {OO.ui.OptionWidget|null} item Selected item
17837 */
17838
17839 /**
17840 * @event choose
17841 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17842 * @param {OO.ui.OptionWidget} item Chosen item
17843 */
17844
17845 /**
17846 * @event add
17847 *
17848 * An `add` event is emitted when options are added to the select with the #addItems method.
17849 *
17850 * @param {OO.ui.OptionWidget[]} items Added items
17851 * @param {number} index Index of insertion point
17852 */
17853
17854 /**
17855 * @event remove
17856 *
17857 * A `remove` event is emitted when options are removed from the select with the #clearItems
17858 * or #removeItems methods.
17859 *
17860 * @param {OO.ui.OptionWidget[]} items Removed items
17861 */
17862
17863 /* Methods */
17864
17865 /**
17866 * Handle mouse down events.
17867 *
17868 * @private
17869 * @param {jQuery.Event} e Mouse down event
17870 */
17871 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17872 var item;
17873
17874 if ( !this.isDisabled() && e.which === 1 ) {
17875 this.togglePressed( true );
17876 item = this.getTargetItem( e );
17877 if ( item && item.isSelectable() ) {
17878 this.pressItem( item );
17879 this.selecting = item;
17880 OO.ui.addCaptureEventListener(
17881 this.getElementDocument(),
17882 'mouseup',
17883 this.onMouseUpHandler
17884 );
17885 OO.ui.addCaptureEventListener(
17886 this.getElementDocument(),
17887 'mousemove',
17888 this.onMouseMoveHandler
17889 );
17890 }
17891 }
17892 return false;
17893 };
17894
17895 /**
17896 * Handle mouse up events.
17897 *
17898 * @private
17899 * @param {jQuery.Event} e Mouse up event
17900 */
17901 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17902 var item;
17903
17904 this.togglePressed( false );
17905 if ( !this.selecting ) {
17906 item = this.getTargetItem( e );
17907 if ( item && item.isSelectable() ) {
17908 this.selecting = item;
17909 }
17910 }
17911 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17912 this.pressItem( null );
17913 this.chooseItem( this.selecting );
17914 this.selecting = null;
17915 }
17916
17917 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17918 this.onMouseUpHandler );
17919 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17920 this.onMouseMoveHandler );
17921
17922 return false;
17923 };
17924
17925 /**
17926 * Handle mouse move events.
17927 *
17928 * @private
17929 * @param {jQuery.Event} e Mouse move event
17930 */
17931 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17932 var item;
17933
17934 if ( !this.isDisabled() && this.pressed ) {
17935 item = this.getTargetItem( e );
17936 if ( item && item !== this.selecting && item.isSelectable() ) {
17937 this.pressItem( item );
17938 this.selecting = item;
17939 }
17940 }
17941 return false;
17942 };
17943
17944 /**
17945 * Handle mouse over events.
17946 *
17947 * @private
17948 * @param {jQuery.Event} e Mouse over event
17949 */
17950 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17951 var item;
17952
17953 if ( !this.isDisabled() ) {
17954 item = this.getTargetItem( e );
17955 this.highlightItem( item && item.isHighlightable() ? item : null );
17956 }
17957 return false;
17958 };
17959
17960 /**
17961 * Handle mouse leave events.
17962 *
17963 * @private
17964 * @param {jQuery.Event} e Mouse over event
17965 */
17966 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17967 if ( !this.isDisabled() ) {
17968 this.highlightItem( null );
17969 }
17970 return false;
17971 };
17972
17973 /**
17974 * Handle key down events.
17975 *
17976 * @protected
17977 * @param {jQuery.Event} e Key down event
17978 */
17979 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17980 var nextItem,
17981 handled = false,
17982 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17983
17984 if ( !this.isDisabled() && this.isVisible() ) {
17985 switch ( e.keyCode ) {
17986 case OO.ui.Keys.ENTER:
17987 if ( currentItem && currentItem.constructor.static.highlightable ) {
17988 // Was only highlighted, now let's select it. No-op if already selected.
17989 this.chooseItem( currentItem );
17990 handled = true;
17991 }
17992 break;
17993 case OO.ui.Keys.UP:
17994 case OO.ui.Keys.LEFT:
17995 this.clearKeyPressBuffer();
17996 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17997 handled = true;
17998 break;
17999 case OO.ui.Keys.DOWN:
18000 case OO.ui.Keys.RIGHT:
18001 this.clearKeyPressBuffer();
18002 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18003 handled = true;
18004 break;
18005 case OO.ui.Keys.ESCAPE:
18006 case OO.ui.Keys.TAB:
18007 if ( currentItem && currentItem.constructor.static.highlightable ) {
18008 currentItem.setHighlighted( false );
18009 }
18010 this.unbindKeyDownListener();
18011 this.unbindKeyPressListener();
18012 // Don't prevent tabbing away / defocusing
18013 handled = false;
18014 break;
18015 }
18016
18017 if ( nextItem ) {
18018 if ( nextItem.constructor.static.highlightable ) {
18019 this.highlightItem( nextItem );
18020 } else {
18021 this.chooseItem( nextItem );
18022 }
18023 nextItem.scrollElementIntoView();
18024 }
18025
18026 if ( handled ) {
18027 // Can't just return false, because e is not always a jQuery event
18028 e.preventDefault();
18029 e.stopPropagation();
18030 }
18031 }
18032 };
18033
18034 /**
18035 * Bind key down listener.
18036 *
18037 * @protected
18038 */
18039 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18040 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18041 };
18042
18043 /**
18044 * Unbind key down listener.
18045 *
18046 * @protected
18047 */
18048 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18049 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18050 };
18051
18052 /**
18053 * Clear the key-press buffer
18054 *
18055 * @protected
18056 */
18057 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18058 if ( this.keyPressBufferTimer ) {
18059 clearTimeout( this.keyPressBufferTimer );
18060 this.keyPressBufferTimer = null;
18061 }
18062 this.keyPressBuffer = '';
18063 };
18064
18065 /**
18066 * Handle key press events.
18067 *
18068 * @protected
18069 * @param {jQuery.Event} e Key press event
18070 */
18071 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18072 var c, filter, item;
18073
18074 if ( !e.charCode ) {
18075 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18076 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18077 return false;
18078 }
18079 return;
18080 }
18081 if ( String.fromCodePoint ) {
18082 c = String.fromCodePoint( e.charCode );
18083 } else {
18084 c = String.fromCharCode( e.charCode );
18085 }
18086
18087 if ( this.keyPressBufferTimer ) {
18088 clearTimeout( this.keyPressBufferTimer );
18089 }
18090 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18091
18092 item = this.getHighlightedItem() || this.getSelectedItem();
18093
18094 if ( this.keyPressBuffer === c ) {
18095 // Common (if weird) special case: typing "xxxx" will cycle through all
18096 // the items beginning with "x".
18097 if ( item ) {
18098 item = this.getRelativeSelectableItem( item, 1 );
18099 }
18100 } else {
18101 this.keyPressBuffer += c;
18102 }
18103
18104 filter = this.getItemMatcher( this.keyPressBuffer, false );
18105 if ( !item || !filter( item ) ) {
18106 item = this.getRelativeSelectableItem( item, 1, filter );
18107 }
18108 if ( item ) {
18109 if ( item.constructor.static.highlightable ) {
18110 this.highlightItem( item );
18111 } else {
18112 this.chooseItem( item );
18113 }
18114 item.scrollElementIntoView();
18115 }
18116
18117 return false;
18118 };
18119
18120 /**
18121 * Get a matcher for the specific string
18122 *
18123 * @protected
18124 * @param {string} s String to match against items
18125 * @param {boolean} [exact=false] Only accept exact matches
18126 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18127 */
18128 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18129 var re;
18130
18131 if ( s.normalize ) {
18132 s = s.normalize();
18133 }
18134 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18135 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18136 if ( exact ) {
18137 re += '\\s*$';
18138 }
18139 re = new RegExp( re, 'i' );
18140 return function ( item ) {
18141 var l = item.getLabel();
18142 if ( typeof l !== 'string' ) {
18143 l = item.$label.text();
18144 }
18145 if ( l.normalize ) {
18146 l = l.normalize();
18147 }
18148 return re.test( l );
18149 };
18150 };
18151
18152 /**
18153 * Bind key press listener.
18154 *
18155 * @protected
18156 */
18157 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18158 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18159 };
18160
18161 /**
18162 * Unbind key down listener.
18163 *
18164 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18165 * implementation.
18166 *
18167 * @protected
18168 */
18169 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18170 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18171 this.clearKeyPressBuffer();
18172 };
18173
18174 /**
18175 * Visibility change handler
18176 *
18177 * @protected
18178 * @param {boolean} visible
18179 */
18180 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18181 if ( !visible ) {
18182 this.clearKeyPressBuffer();
18183 }
18184 };
18185
18186 /**
18187 * Get the closest item to a jQuery.Event.
18188 *
18189 * @private
18190 * @param {jQuery.Event} e
18191 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18192 */
18193 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18194 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18195 };
18196
18197 /**
18198 * Get selected item.
18199 *
18200 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18201 */
18202 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18203 var i, len;
18204
18205 for ( i = 0, len = this.items.length; i < len; i++ ) {
18206 if ( this.items[ i ].isSelected() ) {
18207 return this.items[ i ];
18208 }
18209 }
18210 return null;
18211 };
18212
18213 /**
18214 * Get highlighted item.
18215 *
18216 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18217 */
18218 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18219 var i, len;
18220
18221 for ( i = 0, len = this.items.length; i < len; i++ ) {
18222 if ( this.items[ i ].isHighlighted() ) {
18223 return this.items[ i ];
18224 }
18225 }
18226 return null;
18227 };
18228
18229 /**
18230 * Toggle pressed state.
18231 *
18232 * Press is a state that occurs when a user mouses down on an item, but
18233 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18234 * until the user releases the mouse.
18235 *
18236 * @param {boolean} pressed An option is being pressed
18237 */
18238 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18239 if ( pressed === undefined ) {
18240 pressed = !this.pressed;
18241 }
18242 if ( pressed !== this.pressed ) {
18243 this.$element
18244 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18245 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18246 this.pressed = pressed;
18247 }
18248 };
18249
18250 /**
18251 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18252 * and any existing highlight will be removed. The highlight is mutually exclusive.
18253 *
18254 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18255 * @fires highlight
18256 * @chainable
18257 */
18258 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18259 var i, len, highlighted,
18260 changed = false;
18261
18262 for ( i = 0, len = this.items.length; i < len; i++ ) {
18263 highlighted = this.items[ i ] === item;
18264 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18265 this.items[ i ].setHighlighted( highlighted );
18266 changed = true;
18267 }
18268 }
18269 if ( changed ) {
18270 this.emit( 'highlight', item );
18271 }
18272
18273 return this;
18274 };
18275
18276 /**
18277 * Fetch an item by its label.
18278 *
18279 * @param {string} label Label of the item to select.
18280 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18281 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18282 */
18283 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18284 var i, item, found,
18285 len = this.items.length,
18286 filter = this.getItemMatcher( label, true );
18287
18288 for ( i = 0; i < len; i++ ) {
18289 item = this.items[ i ];
18290 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18291 return item;
18292 }
18293 }
18294
18295 if ( prefix ) {
18296 found = null;
18297 filter = this.getItemMatcher( label, false );
18298 for ( i = 0; i < len; i++ ) {
18299 item = this.items[ i ];
18300 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18301 if ( found ) {
18302 return null;
18303 }
18304 found = item;
18305 }
18306 }
18307 if ( found ) {
18308 return found;
18309 }
18310 }
18311
18312 return null;
18313 };
18314
18315 /**
18316 * Programmatically select an option by its label. If the item does not exist,
18317 * all options will be deselected.
18318 *
18319 * @param {string} [label] Label of the item to select.
18320 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18321 * @fires select
18322 * @chainable
18323 */
18324 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18325 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18326 if ( label === undefined || !itemFromLabel ) {
18327 return this.selectItem();
18328 }
18329 return this.selectItem( itemFromLabel );
18330 };
18331
18332 /**
18333 * Programmatically select an option by its data. If the `data` parameter is omitted,
18334 * or if the item does not exist, all options will be deselected.
18335 *
18336 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18337 * @fires select
18338 * @chainable
18339 */
18340 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18341 var itemFromData = this.getItemFromData( data );
18342 if ( data === undefined || !itemFromData ) {
18343 return this.selectItem();
18344 }
18345 return this.selectItem( itemFromData );
18346 };
18347
18348 /**
18349 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18350 * all options will be deselected.
18351 *
18352 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18353 * @fires select
18354 * @chainable
18355 */
18356 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18357 var i, len, selected,
18358 changed = false;
18359
18360 for ( i = 0, len = this.items.length; i < len; i++ ) {
18361 selected = this.items[ i ] === item;
18362 if ( this.items[ i ].isSelected() !== selected ) {
18363 this.items[ i ].setSelected( selected );
18364 changed = true;
18365 }
18366 }
18367 if ( changed ) {
18368 this.emit( 'select', item );
18369 }
18370
18371 return this;
18372 };
18373
18374 /**
18375 * Press an item.
18376 *
18377 * Press is a state that occurs when a user mouses down on an item, but has not
18378 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18379 * releases the mouse.
18380 *
18381 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18382 * @fires press
18383 * @chainable
18384 */
18385 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18386 var i, len, pressed,
18387 changed = false;
18388
18389 for ( i = 0, len = this.items.length; i < len; i++ ) {
18390 pressed = this.items[ i ] === item;
18391 if ( this.items[ i ].isPressed() !== pressed ) {
18392 this.items[ i ].setPressed( pressed );
18393 changed = true;
18394 }
18395 }
18396 if ( changed ) {
18397 this.emit( 'press', item );
18398 }
18399
18400 return this;
18401 };
18402
18403 /**
18404 * Choose an item.
18405 *
18406 * Note that ‘choose’ should never be modified programmatically. A user can choose
18407 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18408 * use the #selectItem method.
18409 *
18410 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18411 * when users choose an item with the keyboard or mouse.
18412 *
18413 * @param {OO.ui.OptionWidget} item Item to choose
18414 * @fires choose
18415 * @chainable
18416 */
18417 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18418 if ( item ) {
18419 this.selectItem( item );
18420 this.emit( 'choose', item );
18421 }
18422
18423 return this;
18424 };
18425
18426 /**
18427 * Get an option by its position relative to the specified item (or to the start of the option array,
18428 * if item is `null`). The direction in which to search through the option array is specified with a
18429 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18430 * `null` if there are no options in the array.
18431 *
18432 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18433 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18434 * @param {Function} filter Only consider items for which this function returns
18435 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18436 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18437 */
18438 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18439 var currentIndex, nextIndex, i,
18440 increase = direction > 0 ? 1 : -1,
18441 len = this.items.length;
18442
18443 if ( !$.isFunction( filter ) ) {
18444 filter = OO.ui.SelectWidget.static.passAllFilter;
18445 }
18446
18447 if ( item instanceof OO.ui.OptionWidget ) {
18448 currentIndex = this.items.indexOf( item );
18449 nextIndex = ( currentIndex + increase + len ) % len;
18450 } else {
18451 // If no item is selected and moving forward, start at the beginning.
18452 // If moving backward, start at the end.
18453 nextIndex = direction > 0 ? 0 : len - 1;
18454 }
18455
18456 for ( i = 0; i < len; i++ ) {
18457 item = this.items[ nextIndex ];
18458 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18459 return item;
18460 }
18461 nextIndex = ( nextIndex + increase + len ) % len;
18462 }
18463 return null;
18464 };
18465
18466 /**
18467 * Get the next selectable item or `null` if there are no selectable items.
18468 * Disabled options and menu-section markers and breaks are not selectable.
18469 *
18470 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18471 */
18472 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18473 var i, len, item;
18474
18475 for ( i = 0, len = this.items.length; i < len; i++ ) {
18476 item = this.items[ i ];
18477 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18478 return item;
18479 }
18480 }
18481
18482 return null;
18483 };
18484
18485 /**
18486 * Add an array of options to the select. Optionally, an index number can be used to
18487 * specify an insertion point.
18488 *
18489 * @param {OO.ui.OptionWidget[]} items Items to add
18490 * @param {number} [index] Index to insert items after
18491 * @fires add
18492 * @chainable
18493 */
18494 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18495 // Mixin method
18496 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18497
18498 // Always provide an index, even if it was omitted
18499 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18500
18501 return this;
18502 };
18503
18504 /**
18505 * Remove the specified array of options from the select. Options will be detached
18506 * from the DOM, not removed, so they can be reused later. To remove all options from
18507 * the select, you may wish to use the #clearItems method instead.
18508 *
18509 * @param {OO.ui.OptionWidget[]} items Items to remove
18510 * @fires remove
18511 * @chainable
18512 */
18513 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18514 var i, len, item;
18515
18516 // Deselect items being removed
18517 for ( i = 0, len = items.length; i < len; i++ ) {
18518 item = items[ i ];
18519 if ( item.isSelected() ) {
18520 this.selectItem( null );
18521 }
18522 }
18523
18524 // Mixin method
18525 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18526
18527 this.emit( 'remove', items );
18528
18529 return this;
18530 };
18531
18532 /**
18533 * Clear all options from the select. Options will be detached from the DOM, not removed,
18534 * so that they can be reused later. To remove a subset of options from the select, use
18535 * the #removeItems method.
18536 *
18537 * @fires remove
18538 * @chainable
18539 */
18540 OO.ui.SelectWidget.prototype.clearItems = function () {
18541 var items = this.items.slice();
18542
18543 // Mixin method
18544 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18545
18546 // Clear selection
18547 this.selectItem( null );
18548
18549 this.emit( 'remove', items );
18550
18551 return this;
18552 };
18553
18554 /**
18555 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18556 * button options and is used together with
18557 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18558 * highlighting, choosing, and selecting mutually exclusive options. Please see
18559 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18560 *
18561 * @example
18562 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18563 * var option1 = new OO.ui.ButtonOptionWidget( {
18564 * data: 1,
18565 * label: 'Option 1',
18566 * title: 'Button option 1'
18567 * } );
18568 *
18569 * var option2 = new OO.ui.ButtonOptionWidget( {
18570 * data: 2,
18571 * label: 'Option 2',
18572 * title: 'Button option 2'
18573 * } );
18574 *
18575 * var option3 = new OO.ui.ButtonOptionWidget( {
18576 * data: 3,
18577 * label: 'Option 3',
18578 * title: 'Button option 3'
18579 * } );
18580 *
18581 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18582 * items: [ option1, option2, option3 ]
18583 * } );
18584 * $( 'body' ).append( buttonSelect.$element );
18585 *
18586 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18587 *
18588 * @class
18589 * @extends OO.ui.SelectWidget
18590 * @mixins OO.ui.mixin.TabIndexedElement
18591 *
18592 * @constructor
18593 * @param {Object} [config] Configuration options
18594 */
18595 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18596 // Parent constructor
18597 OO.ui.ButtonSelectWidget.parent.call( this, config );
18598
18599 // Mixin constructors
18600 OO.ui.mixin.TabIndexedElement.call( this, config );
18601
18602 // Events
18603 this.$element.on( {
18604 focus: this.bindKeyDownListener.bind( this ),
18605 blur: this.unbindKeyDownListener.bind( this )
18606 } );
18607
18608 // Initialization
18609 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18610 };
18611
18612 /* Setup */
18613
18614 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18615 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18616
18617 /**
18618 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18619 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18620 * an interface for adding, removing and selecting options.
18621 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18622 *
18623 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18624 * OO.ui.RadioSelectInputWidget instead.
18625 *
18626 * @example
18627 * // A RadioSelectWidget with RadioOptions.
18628 * var option1 = new OO.ui.RadioOptionWidget( {
18629 * data: 'a',
18630 * label: 'Selected radio option'
18631 * } );
18632 *
18633 * var option2 = new OO.ui.RadioOptionWidget( {
18634 * data: 'b',
18635 * label: 'Unselected radio option'
18636 * } );
18637 *
18638 * var radioSelect=new OO.ui.RadioSelectWidget( {
18639 * items: [ option1, option2 ]
18640 * } );
18641 *
18642 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18643 * radioSelect.selectItem( option1 );
18644 *
18645 * $( 'body' ).append( radioSelect.$element );
18646 *
18647 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18648
18649 *
18650 * @class
18651 * @extends OO.ui.SelectWidget
18652 * @mixins OO.ui.mixin.TabIndexedElement
18653 *
18654 * @constructor
18655 * @param {Object} [config] Configuration options
18656 */
18657 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18658 // Parent constructor
18659 OO.ui.RadioSelectWidget.parent.call( this, config );
18660
18661 // Mixin constructors
18662 OO.ui.mixin.TabIndexedElement.call( this, config );
18663
18664 // Events
18665 this.$element.on( {
18666 focus: this.bindKeyDownListener.bind( this ),
18667 blur: this.unbindKeyDownListener.bind( this )
18668 } );
18669
18670 // Initialization
18671 this.$element
18672 .addClass( 'oo-ui-radioSelectWidget' )
18673 .attr( 'role', 'radiogroup' );
18674 };
18675
18676 /* Setup */
18677
18678 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18679 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18680
18681 /**
18682 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18683 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18684 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18685 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18686 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18687 * and customized to be opened, closed, and displayed as needed.
18688 *
18689 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18690 * mouse outside the menu.
18691 *
18692 * Menus also have support for keyboard interaction:
18693 *
18694 * - Enter/Return key: choose and select a menu option
18695 * - Up-arrow key: highlight the previous menu option
18696 * - Down-arrow key: highlight the next menu option
18697 * - Esc key: hide the menu
18698 *
18699 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18700 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18701 *
18702 * @class
18703 * @extends OO.ui.SelectWidget
18704 * @mixins OO.ui.mixin.ClippableElement
18705 *
18706 * @constructor
18707 * @param {Object} [config] Configuration options
18708 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18709 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18710 * and {@link OO.ui.mixin.LookupElement LookupElement}
18711 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18712 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18713 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18714 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18715 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18716 * that button, unless the button (or its parent widget) is passed in here.
18717 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18718 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18719 */
18720 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18721 // Configuration initialization
18722 config = config || {};
18723
18724 // Parent constructor
18725 OO.ui.MenuSelectWidget.parent.call( this, config );
18726
18727 // Mixin constructors
18728 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18729
18730 // Properties
18731 this.newItems = null;
18732 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18733 this.filterFromInput = !!config.filterFromInput;
18734 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18735 this.$widget = config.widget ? config.widget.$element : null;
18736 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18737 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18738
18739 // Initialization
18740 this.$element
18741 .addClass( 'oo-ui-menuSelectWidget' )
18742 .attr( 'role', 'menu' );
18743
18744 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18745 // that reference properties not initialized at that time of parent class construction
18746 // TODO: Find a better way to handle post-constructor setup
18747 this.visible = false;
18748 this.$element.addClass( 'oo-ui-element-hidden' );
18749 };
18750
18751 /* Setup */
18752
18753 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18754 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18755
18756 /* Methods */
18757
18758 /**
18759 * Handles document mouse down events.
18760 *
18761 * @protected
18762 * @param {jQuery.Event} e Key down event
18763 */
18764 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18765 if (
18766 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18767 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18768 ) {
18769 this.toggle( false );
18770 }
18771 };
18772
18773 /**
18774 * @inheritdoc
18775 */
18776 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18777 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18778
18779 if ( !this.isDisabled() && this.isVisible() ) {
18780 switch ( e.keyCode ) {
18781 case OO.ui.Keys.LEFT:
18782 case OO.ui.Keys.RIGHT:
18783 // Do nothing if a text field is associated, arrow keys will be handled natively
18784 if ( !this.$input ) {
18785 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18786 }
18787 break;
18788 case OO.ui.Keys.ESCAPE:
18789 case OO.ui.Keys.TAB:
18790 if ( currentItem ) {
18791 currentItem.setHighlighted( false );
18792 }
18793 this.toggle( false );
18794 // Don't prevent tabbing away, prevent defocusing
18795 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18796 e.preventDefault();
18797 e.stopPropagation();
18798 }
18799 break;
18800 default:
18801 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18802 return;
18803 }
18804 }
18805 };
18806
18807 /**
18808 * Update menu item visibility after input changes.
18809 * @protected
18810 */
18811 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18812 var i, item,
18813 len = this.items.length,
18814 showAll = !this.isVisible(),
18815 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18816
18817 for ( i = 0; i < len; i++ ) {
18818 item = this.items[ i ];
18819 if ( item instanceof OO.ui.OptionWidget ) {
18820 item.toggle( showAll || filter( item ) );
18821 }
18822 }
18823
18824 // Reevaluate clipping
18825 this.clip();
18826 };
18827
18828 /**
18829 * @inheritdoc
18830 */
18831 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18832 if ( this.$input ) {
18833 this.$input.on( 'keydown', this.onKeyDownHandler );
18834 } else {
18835 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18836 }
18837 };
18838
18839 /**
18840 * @inheritdoc
18841 */
18842 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18843 if ( this.$input ) {
18844 this.$input.off( 'keydown', this.onKeyDownHandler );
18845 } else {
18846 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18847 }
18848 };
18849
18850 /**
18851 * @inheritdoc
18852 */
18853 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18854 if ( this.$input ) {
18855 if ( this.filterFromInput ) {
18856 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18857 }
18858 } else {
18859 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18860 }
18861 };
18862
18863 /**
18864 * @inheritdoc
18865 */
18866 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18867 if ( this.$input ) {
18868 if ( this.filterFromInput ) {
18869 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18870 this.updateItemVisibility();
18871 }
18872 } else {
18873 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18874 }
18875 };
18876
18877 /**
18878 * Choose an item.
18879 *
18880 * When a user chooses an item, the menu is closed.
18881 *
18882 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18883 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18884 * @param {OO.ui.OptionWidget} item Item to choose
18885 * @chainable
18886 */
18887 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18888 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18889 this.toggle( false );
18890 return this;
18891 };
18892
18893 /**
18894 * @inheritdoc
18895 */
18896 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18897 var i, len, item;
18898
18899 // Parent method
18900 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18901
18902 // Auto-initialize
18903 if ( !this.newItems ) {
18904 this.newItems = [];
18905 }
18906
18907 for ( i = 0, len = items.length; i < len; i++ ) {
18908 item = items[ i ];
18909 if ( this.isVisible() ) {
18910 // Defer fitting label until item has been attached
18911 item.fitLabel();
18912 } else {
18913 this.newItems.push( item );
18914 }
18915 }
18916
18917 // Reevaluate clipping
18918 this.clip();
18919
18920 return this;
18921 };
18922
18923 /**
18924 * @inheritdoc
18925 */
18926 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18927 // Parent method
18928 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18929
18930 // Reevaluate clipping
18931 this.clip();
18932
18933 return this;
18934 };
18935
18936 /**
18937 * @inheritdoc
18938 */
18939 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18940 // Parent method
18941 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18942
18943 // Reevaluate clipping
18944 this.clip();
18945
18946 return this;
18947 };
18948
18949 /**
18950 * @inheritdoc
18951 */
18952 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18953 var i, len, change;
18954
18955 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18956 change = visible !== this.isVisible();
18957
18958 // Parent method
18959 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18960
18961 if ( change ) {
18962 if ( visible ) {
18963 this.bindKeyDownListener();
18964 this.bindKeyPressListener();
18965
18966 if ( this.newItems && this.newItems.length ) {
18967 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18968 this.newItems[ i ].fitLabel();
18969 }
18970 this.newItems = null;
18971 }
18972 this.toggleClipping( true );
18973
18974 // Auto-hide
18975 if ( this.autoHide ) {
18976 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18977 }
18978 } else {
18979 this.unbindKeyDownListener();
18980 this.unbindKeyPressListener();
18981 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18982 this.toggleClipping( false );
18983 }
18984 }
18985
18986 return this;
18987 };
18988
18989 /**
18990 * FloatingMenuSelectWidget is a menu that will stick under a specified
18991 * container, even when it is inserted elsewhere in the document (for example,
18992 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18993 * menu from being clipped too aggresively.
18994 *
18995 * The menu's position is automatically calculated and maintained when the menu
18996 * is toggled or the window is resized.
18997 *
18998 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18999 *
19000 * @class
19001 * @extends OO.ui.MenuSelectWidget
19002 * @mixins OO.ui.mixin.FloatableElement
19003 *
19004 * @constructor
19005 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19006 * Deprecated, omit this parameter and specify `$container` instead.
19007 * @param {Object} [config] Configuration options
19008 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19009 */
19010 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19011 // Allow 'inputWidget' parameter and config for backwards compatibility
19012 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19013 config = inputWidget;
19014 inputWidget = config.inputWidget;
19015 }
19016
19017 // Configuration initialization
19018 config = config || {};
19019
19020 // Parent constructor
19021 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19022
19023 // Properties (must be set before mixin constructors)
19024 this.inputWidget = inputWidget; // For backwards compatibility
19025 this.$container = config.$container || this.inputWidget.$element;
19026
19027 // Mixins constructors
19028 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19029
19030 // Initialization
19031 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19032 // For backwards compatibility
19033 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19034 };
19035
19036 /* Setup */
19037
19038 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19039 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19040
19041 // For backwards compatibility
19042 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19043
19044 /* Methods */
19045
19046 /**
19047 * @inheritdoc
19048 */
19049 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19050 var change;
19051 visible = visible === undefined ? !this.isVisible() : !!visible;
19052 change = visible !== this.isVisible();
19053
19054 if ( change && visible ) {
19055 // Make sure the width is set before the parent method runs.
19056 this.setIdealSize( this.$container.width() );
19057 }
19058
19059 // Parent method
19060 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19061 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19062
19063 if ( change ) {
19064 this.togglePositioning( this.isVisible() );
19065 }
19066
19067 return this;
19068 };
19069
19070 /**
19071 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19072 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19073 *
19074 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19075 *
19076 * @class
19077 * @extends OO.ui.SelectWidget
19078 * @mixins OO.ui.mixin.TabIndexedElement
19079 *
19080 * @constructor
19081 * @param {Object} [config] Configuration options
19082 */
19083 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19084 // Parent constructor
19085 OO.ui.OutlineSelectWidget.parent.call( this, config );
19086
19087 // Mixin constructors
19088 OO.ui.mixin.TabIndexedElement.call( this, config );
19089
19090 // Events
19091 this.$element.on( {
19092 focus: this.bindKeyDownListener.bind( this ),
19093 blur: this.unbindKeyDownListener.bind( this )
19094 } );
19095
19096 // Initialization
19097 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19098 };
19099
19100 /* Setup */
19101
19102 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19103 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19104
19105 /**
19106 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19107 *
19108 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19109 *
19110 * @class
19111 * @extends OO.ui.SelectWidget
19112 * @mixins OO.ui.mixin.TabIndexedElement
19113 *
19114 * @constructor
19115 * @param {Object} [config] Configuration options
19116 */
19117 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19118 // Parent constructor
19119 OO.ui.TabSelectWidget.parent.call( this, config );
19120
19121 // Mixin constructors
19122 OO.ui.mixin.TabIndexedElement.call( this, config );
19123
19124 // Events
19125 this.$element.on( {
19126 focus: this.bindKeyDownListener.bind( this ),
19127 blur: this.unbindKeyDownListener.bind( this )
19128 } );
19129
19130 // Initialization
19131 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19132 };
19133
19134 /* Setup */
19135
19136 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19137 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19138
19139 /**
19140 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19141 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19142 * (to adjust the value in increments) to allow the user to enter a number.
19143 *
19144 * @example
19145 * // Example: A NumberInputWidget.
19146 * var numberInput = new OO.ui.NumberInputWidget( {
19147 * label: 'NumberInputWidget',
19148 * input: { value: 5, min: 1, max: 10 }
19149 * } );
19150 * $( 'body' ).append( numberInput.$element );
19151 *
19152 * @class
19153 * @extends OO.ui.Widget
19154 *
19155 * @constructor
19156 * @param {Object} [config] Configuration options
19157 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19158 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19159 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19160 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19161 * @cfg {number} [min=-Infinity] Minimum allowed value
19162 * @cfg {number} [max=Infinity] Maximum allowed value
19163 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19164 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19165 */
19166 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19167 // Configuration initialization
19168 config = $.extend( {
19169 isInteger: false,
19170 min: -Infinity,
19171 max: Infinity,
19172 step: 1,
19173 pageStep: null
19174 }, config );
19175
19176 // Parent constructor
19177 OO.ui.NumberInputWidget.parent.call( this, config );
19178
19179 // Properties
19180 this.input = new OO.ui.TextInputWidget( $.extend(
19181 {
19182 disabled: this.isDisabled()
19183 },
19184 config.input
19185 ) );
19186 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19187 {
19188 disabled: this.isDisabled(),
19189 tabIndex: -1
19190 },
19191 config.minusButton,
19192 {
19193 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19194 label: '−'
19195 }
19196 ) );
19197 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19198 {
19199 disabled: this.isDisabled(),
19200 tabIndex: -1
19201 },
19202 config.plusButton,
19203 {
19204 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19205 label: '+'
19206 }
19207 ) );
19208
19209 // Events
19210 this.input.connect( this, {
19211 change: this.emit.bind( this, 'change' ),
19212 enter: this.emit.bind( this, 'enter' )
19213 } );
19214 this.input.$input.on( {
19215 keydown: this.onKeyDown.bind( this ),
19216 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19217 } );
19218 this.plusButton.connect( this, {
19219 click: [ 'onButtonClick', +1 ]
19220 } );
19221 this.minusButton.connect( this, {
19222 click: [ 'onButtonClick', -1 ]
19223 } );
19224
19225 // Initialization
19226 this.setIsInteger( !!config.isInteger );
19227 this.setRange( config.min, config.max );
19228 this.setStep( config.step, config.pageStep );
19229
19230 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19231 .append(
19232 this.minusButton.$element,
19233 this.input.$element,
19234 this.plusButton.$element
19235 );
19236 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19237 this.input.setValidation( this.validateNumber.bind( this ) );
19238 };
19239
19240 /* Setup */
19241
19242 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19243
19244 /* Events */
19245
19246 /**
19247 * A `change` event is emitted when the value of the input changes.
19248 *
19249 * @event change
19250 */
19251
19252 /**
19253 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19254 *
19255 * @event enter
19256 */
19257
19258 /* Methods */
19259
19260 /**
19261 * Set whether only integers are allowed
19262 * @param {boolean} flag
19263 */
19264 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19265 this.isInteger = !!flag;
19266 this.input.setValidityFlag();
19267 };
19268
19269 /**
19270 * Get whether only integers are allowed
19271 * @return {boolean} Flag value
19272 */
19273 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19274 return this.isInteger;
19275 };
19276
19277 /**
19278 * Set the range of allowed values
19279 * @param {number} min Minimum allowed value
19280 * @param {number} max Maximum allowed value
19281 */
19282 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19283 if ( min > max ) {
19284 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19285 }
19286 this.min = min;
19287 this.max = max;
19288 this.input.setValidityFlag();
19289 };
19290
19291 /**
19292 * Get the current range
19293 * @return {number[]} Minimum and maximum values
19294 */
19295 OO.ui.NumberInputWidget.prototype.getRange = function () {
19296 return [ this.min, this.max ];
19297 };
19298
19299 /**
19300 * Set the stepping deltas
19301 * @param {number} step Normal step
19302 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19303 */
19304 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19305 if ( step <= 0 ) {
19306 throw new Error( 'Step value must be positive' );
19307 }
19308 if ( pageStep === null ) {
19309 pageStep = step * 10;
19310 } else if ( pageStep <= 0 ) {
19311 throw new Error( 'Page step value must be positive' );
19312 }
19313 this.step = step;
19314 this.pageStep = pageStep;
19315 };
19316
19317 /**
19318 * Get the current stepping values
19319 * @return {number[]} Step and page step
19320 */
19321 OO.ui.NumberInputWidget.prototype.getStep = function () {
19322 return [ this.step, this.pageStep ];
19323 };
19324
19325 /**
19326 * Get the current value of the widget
19327 * @return {string}
19328 */
19329 OO.ui.NumberInputWidget.prototype.getValue = function () {
19330 return this.input.getValue();
19331 };
19332
19333 /**
19334 * Get the current value of the widget as a number
19335 * @return {number} May be NaN, or an invalid number
19336 */
19337 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19338 return +this.input.getValue();
19339 };
19340
19341 /**
19342 * Set the value of the widget
19343 * @param {string} value Invalid values are allowed
19344 */
19345 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19346 this.input.setValue( value );
19347 };
19348
19349 /**
19350 * Adjust the value of the widget
19351 * @param {number} delta Adjustment amount
19352 */
19353 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19354 var n, v = this.getNumericValue();
19355
19356 delta = +delta;
19357 if ( isNaN( delta ) || !isFinite( delta ) ) {
19358 throw new Error( 'Delta must be a finite number' );
19359 }
19360
19361 if ( isNaN( v ) ) {
19362 n = 0;
19363 } else {
19364 n = v + delta;
19365 n = Math.max( Math.min( n, this.max ), this.min );
19366 if ( this.isInteger ) {
19367 n = Math.round( n );
19368 }
19369 }
19370
19371 if ( n !== v ) {
19372 this.setValue( n );
19373 }
19374 };
19375
19376 /**
19377 * Validate input
19378 * @private
19379 * @param {string} value Field value
19380 * @return {boolean}
19381 */
19382 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19383 var n = +value;
19384 if ( isNaN( n ) || !isFinite( n ) ) {
19385 return false;
19386 }
19387
19388 /*jshint bitwise: false */
19389 if ( this.isInteger && ( n | 0 ) !== n ) {
19390 return false;
19391 }
19392 /*jshint bitwise: true */
19393
19394 if ( n < this.min || n > this.max ) {
19395 return false;
19396 }
19397
19398 return true;
19399 };
19400
19401 /**
19402 * Handle mouse click events.
19403 *
19404 * @private
19405 * @param {number} dir +1 or -1
19406 */
19407 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19408 this.adjustValue( dir * this.step );
19409 };
19410
19411 /**
19412 * Handle mouse wheel events.
19413 *
19414 * @private
19415 * @param {jQuery.Event} event
19416 */
19417 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19418 var delta = 0;
19419
19420 // Standard 'wheel' event
19421 if ( event.originalEvent.deltaMode !== undefined ) {
19422 this.sawWheelEvent = true;
19423 }
19424 if ( event.originalEvent.deltaY ) {
19425 delta = -event.originalEvent.deltaY;
19426 } else if ( event.originalEvent.deltaX ) {
19427 delta = event.originalEvent.deltaX;
19428 }
19429
19430 // Non-standard events
19431 if ( !this.sawWheelEvent ) {
19432 if ( event.originalEvent.wheelDeltaX ) {
19433 delta = -event.originalEvent.wheelDeltaX;
19434 } else if ( event.originalEvent.wheelDeltaY ) {
19435 delta = event.originalEvent.wheelDeltaY;
19436 } else if ( event.originalEvent.wheelDelta ) {
19437 delta = event.originalEvent.wheelDelta;
19438 } else if ( event.originalEvent.detail ) {
19439 delta = -event.originalEvent.detail;
19440 }
19441 }
19442
19443 if ( delta ) {
19444 delta = delta < 0 ? -1 : 1;
19445 this.adjustValue( delta * this.step );
19446 }
19447
19448 return false;
19449 };
19450
19451 /**
19452 * Handle key down events.
19453 *
19454 * @private
19455 * @param {jQuery.Event} e Key down event
19456 */
19457 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19458 if ( !this.isDisabled() ) {
19459 switch ( e.which ) {
19460 case OO.ui.Keys.UP:
19461 this.adjustValue( this.step );
19462 return false;
19463 case OO.ui.Keys.DOWN:
19464 this.adjustValue( -this.step );
19465 return false;
19466 case OO.ui.Keys.PAGEUP:
19467 this.adjustValue( this.pageStep );
19468 return false;
19469 case OO.ui.Keys.PAGEDOWN:
19470 this.adjustValue( -this.pageStep );
19471 return false;
19472 }
19473 }
19474 };
19475
19476 /**
19477 * @inheritdoc
19478 */
19479 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19480 // Parent method
19481 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19482
19483 if ( this.input ) {
19484 this.input.setDisabled( this.isDisabled() );
19485 }
19486 if ( this.minusButton ) {
19487 this.minusButton.setDisabled( this.isDisabled() );
19488 }
19489 if ( this.plusButton ) {
19490 this.plusButton.setDisabled( this.isDisabled() );
19491 }
19492
19493 return this;
19494 };
19495
19496 /**
19497 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19498 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19499 * visually by a slider in the leftmost position.
19500 *
19501 * @example
19502 * // Toggle switches in the 'off' and 'on' position.
19503 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19504 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19505 * value: true
19506 * } );
19507 *
19508 * // Create a FieldsetLayout to layout and label switches
19509 * var fieldset = new OO.ui.FieldsetLayout( {
19510 * label: 'Toggle switches'
19511 * } );
19512 * fieldset.addItems( [
19513 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19514 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19515 * ] );
19516 * $( 'body' ).append( fieldset.$element );
19517 *
19518 * @class
19519 * @extends OO.ui.ToggleWidget
19520 * @mixins OO.ui.mixin.TabIndexedElement
19521 *
19522 * @constructor
19523 * @param {Object} [config] Configuration options
19524 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19525 * By default, the toggle switch is in the 'off' position.
19526 */
19527 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19528 // Parent constructor
19529 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19530
19531 // Mixin constructors
19532 OO.ui.mixin.TabIndexedElement.call( this, config );
19533
19534 // Properties
19535 this.dragging = false;
19536 this.dragStart = null;
19537 this.sliding = false;
19538 this.$glow = $( '<span>' );
19539 this.$grip = $( '<span>' );
19540
19541 // Events
19542 this.$element.on( {
19543 click: this.onClick.bind( this ),
19544 keypress: this.onKeyPress.bind( this )
19545 } );
19546
19547 // Initialization
19548 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19549 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19550 this.$element
19551 .addClass( 'oo-ui-toggleSwitchWidget' )
19552 .attr( 'role', 'checkbox' )
19553 .append( this.$glow, this.$grip );
19554 };
19555
19556 /* Setup */
19557
19558 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19559 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19560
19561 /* Methods */
19562
19563 /**
19564 * Handle mouse click events.
19565 *
19566 * @private
19567 * @param {jQuery.Event} e Mouse click event
19568 */
19569 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19570 if ( !this.isDisabled() && e.which === 1 ) {
19571 this.setValue( !this.value );
19572 }
19573 return false;
19574 };
19575
19576 /**
19577 * Handle key press events.
19578 *
19579 * @private
19580 * @param {jQuery.Event} e Key press event
19581 */
19582 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19583 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19584 this.setValue( !this.value );
19585 return false;
19586 }
19587 };
19588
19589 /*!
19590 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19591 */
19592
19593 /**
19594 * @inheritdoc OO.ui.mixin.ButtonElement
19595 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19596 */
19597 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19598
19599 /**
19600 * @inheritdoc OO.ui.mixin.ClippableElement
19601 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19602 */
19603 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19604
19605 /**
19606 * @inheritdoc OO.ui.mixin.DraggableElement
19607 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19608 */
19609 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19610
19611 /**
19612 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19613 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19614 */
19615 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19616
19617 /**
19618 * @inheritdoc OO.ui.mixin.FlaggedElement
19619 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19620 */
19621 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19622
19623 /**
19624 * @inheritdoc OO.ui.mixin.GroupElement
19625 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19626 */
19627 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19628
19629 /**
19630 * @inheritdoc OO.ui.mixin.GroupWidget
19631 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19632 */
19633 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19634
19635 /**
19636 * @inheritdoc OO.ui.mixin.IconElement
19637 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19638 */
19639 OO.ui.IconElement = OO.ui.mixin.IconElement;
19640
19641 /**
19642 * @inheritdoc OO.ui.mixin.IndicatorElement
19643 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19644 */
19645 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19646
19647 /**
19648 * @inheritdoc OO.ui.mixin.ItemWidget
19649 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19650 */
19651 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19652
19653 /**
19654 * @inheritdoc OO.ui.mixin.LabelElement
19655 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19656 */
19657 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19658
19659 /**
19660 * @inheritdoc OO.ui.mixin.LookupElement
19661 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19662 */
19663 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19664
19665 /**
19666 * @inheritdoc OO.ui.mixin.PendingElement
19667 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19668 */
19669 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19670
19671 /**
19672 * @inheritdoc OO.ui.mixin.PopupElement
19673 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19674 */
19675 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19676
19677 /**
19678 * @inheritdoc OO.ui.mixin.TabIndexedElement
19679 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19680 */
19681 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19682
19683 /**
19684 * @inheritdoc OO.ui.mixin.TitledElement
19685 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19686 */
19687 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19688
19689 }( OO ) );