Merge "[search] Fix method call on null value"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.13.0
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-27T17:52:51Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * @property {Number}
49 */
50 OO.ui.elementId = 0;
51
52 /**
53 * Generate a unique ID for element
54 *
55 * @return {String} [id]
56 */
57 OO.ui.generateElementId = function () {
58 OO.ui.elementId += 1;
59 return 'oojsui-' + OO.ui.elementId;
60 };
61
62 /**
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
65 *
66 * @param {jQuery} element Element to test
67 * @return {boolean}
68 */
69 OO.ui.isFocusableElement = function ( $element ) {
70 var nodeName,
71 element = $element[ 0 ];
72
73 // Anything disabled is not focusable
74 if ( element.disabled ) {
75 return false;
76 }
77
78 // Check if the element is visible
79 if ( !(
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr.filters.visible( element ) &&
82 // Check that all parents are visible
83 !$element.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
85 } ).length
86 ) ) {
87 return false;
88 }
89
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element.contentEditable === 'true' ) {
92 return true;
93 }
94
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element.prop( 'tabIndex' ) >= 0 ) {
98 return true;
99 }
100
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName = element.nodeName.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) {
106 return true;
107 }
108
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) {
111 return true;
112 }
113
114 return false;
115 };
116
117 /**
118 * Find a focusable child
119 *
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
123 */
124 OO.ui.findFocusable = function ( $container, backwards ) {
125 var $focusable = $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates = $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
130
131 if ( backwards ) {
132 $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates );
133 }
134
135 $focusableCandidates.each( function () {
136 var $this = $( this );
137 if ( OO.ui.isFocusableElement( $this ) ) {
138 $focusable = $this;
139 return false;
140 }
141 } );
142 return $focusable;
143 };
144
145 /**
146 * Get the user's language and any fallback languages.
147 *
148 * These language codes are used to localize user interface elements in the user's language.
149 *
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
152 *
153 * @return {string[]} Language codes, in descending order of priority
154 */
155 OO.ui.getUserLanguages = function () {
156 return [ 'en' ];
157 };
158
159 /**
160 * Get a value in an object keyed by language code.
161 *
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
166 */
167 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
168 var i, len, langs;
169
170 // Requested language
171 if ( obj[ lang ] ) {
172 return obj[ lang ];
173 }
174 // Known user language
175 langs = OO.ui.getUserLanguages();
176 for ( i = 0, len = langs.length; i < len; i++ ) {
177 lang = langs[ i ];
178 if ( obj[ lang ] ) {
179 return obj[ lang ];
180 }
181 }
182 // Fallback language
183 if ( obj[ fallback ] ) {
184 return obj[ fallback ];
185 }
186 // First existing language
187 for ( lang in obj ) {
188 return obj[ lang ];
189 }
190
191 return undefined;
192 };
193
194 /**
195 * Check if a node is contained within another node
196 *
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
199 *
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
204 */
205 OO.ui.contains = function ( containers, contained, matchContainers ) {
206 var i;
207 if ( !Array.isArray( containers ) ) {
208 containers = [ containers ];
209 }
210 for ( i = containers.length - 1; i >= 0; i-- ) {
211 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
212 return true;
213 }
214 }
215 return false;
216 };
217
218 /**
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
223 *
224 * Ported from: http://underscorejs.org/underscore.js
225 *
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
229 * @return {Function}
230 */
231 OO.ui.debounce = function ( func, wait, immediate ) {
232 var timeout;
233 return function () {
234 var context = this,
235 args = arguments,
236 later = function () {
237 timeout = null;
238 if ( !immediate ) {
239 func.apply( context, args );
240 }
241 };
242 if ( immediate && !timeout ) {
243 func.apply( context, args );
244 }
245 clearTimeout( timeout );
246 timeout = setTimeout( later, wait );
247 };
248 };
249
250 /**
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
253 *
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
257 */
258 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
259 if ( node.addEventListener ) {
260 node.addEventListener( eventName, handler, true );
261 } else {
262 node.attachEvent( 'on' + eventName, handler );
263 }
264 };
265
266 /**
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
269 *
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
273 */
274 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
275 if ( node.addEventListener ) {
276 node.removeEventListener( eventName, handler, true );
277 } else {
278 node.detachEvent( 'on' + eventName, handler );
279 }
280 };
281
282 /**
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
285 *
286 * This is an alias for `OO.ui.Element.static.infuse()`.
287 *
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
292 */
293 OO.ui.infuse = function ( idOrNode ) {
294 return OO.ui.Element.static.infuse( idOrNode );
295 };
296
297 ( function () {
298 /**
299 * Message store for the default implementation of OO.ui.msg
300 *
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
303 *
304 * @private
305 */
306 var messages = {
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
339 };
340
341 /**
342 * Get a localized message.
343 *
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
346 * English messages.
347 *
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
352 *
353 * @abstract
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
357 */
358 OO.ui.msg = function ( key ) {
359 var message = messages[ key ],
360 params = Array.prototype.slice.call( arguments, 1 );
361 if ( typeof message === 'string' ) {
362 // Perform $1 substitution
363 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
364 var i = parseInt( n, 10 );
365 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
366 } );
367 } else {
368 // Return placeholder if message not found
369 message = '[' + key + ']';
370 }
371 return message;
372 };
373
374 /**
375 * Package a message and arguments for deferred resolution.
376 *
377 * Use this when you are statically specifying a message and the message may not yet be present.
378 *
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
382 */
383 OO.ui.deferMsg = function () {
384 var args = arguments;
385 return function () {
386 return OO.ui.msg.apply( OO.ui, args );
387 };
388 };
389
390 /**
391 * Resolve a message.
392 *
393 * If the message is a function it will be executed, otherwise it will pass through directly.
394 *
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
397 */
398 OO.ui.resolveMsg = function ( msg ) {
399 if ( $.isFunction( msg ) ) {
400 return msg();
401 }
402 return msg;
403 };
404
405 /**
406 * @param {string} url
407 * @return {boolean}
408 */
409 OO.ui.isSafeUrl = function ( url ) {
410 var protocol,
411 // Keep in sync with php/Tag.php
412 whitelist = [
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
416 ];
417
418 if ( url.indexOf( ':' ) === -1 ) {
419 // No protocol, safe
420 return true;
421 }
422
423 protocol = url.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
426 return true;
427 }
428
429 // Safe if in the whitelist
430 return whitelist.indexOf( protocol ) !== -1;
431 };
432
433 } )();
434
435 /*!
436 * Mixin namespace.
437 */
438
439 /**
440 * Namespace for OOjs UI mixins.
441 *
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
446 *
447 * @class
448 * @singleton
449 */
450 OO.ui.mixin = {};
451
452 /**
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
457 *
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
461 *
462 * @example
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
465 * }
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
467 *
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
471 * ];
472 *
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
477 * this.$body.append( this.content.$element );
478 * };
479 * MessageDialog.prototype.getBodyHeight = function () {
480 * return 100;
481 * }
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
483 * var dialog = this;
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
487 * .next( 1000 )
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
490 * } );
491 * }
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
493 * };
494 *
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
497 *
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
501 *
502 * @abstract
503 * @class
504 *
505 * @constructor
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
508 */
509 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
510 // Configuration initialization
511 config = config || {};
512
513 // Properties
514 this.pending = 0;
515 this.$pending = null;
516
517 // Initialisation
518 this.setPendingElement( config.$pending || this.$element );
519 };
520
521 /* Setup */
522
523 OO.initClass( OO.ui.mixin.PendingElement );
524
525 /* Methods */
526
527 /**
528 * Set the pending element (and clean up any existing one).
529 *
530 * @param {jQuery} $pending The element to set to pending.
531 */
532 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
533 if ( this.$pending ) {
534 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
535 }
536
537 this.$pending = $pending;
538 if ( this.pending > 0 ) {
539 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
540 }
541 };
542
543 /**
544 * Check if an element is pending.
545 *
546 * @return {boolean} Element is pending
547 */
548 OO.ui.mixin.PendingElement.prototype.isPending = function () {
549 return !!this.pending;
550 };
551
552 /**
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
555 *
556 * @chainable
557 */
558 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
559 if ( this.pending === 0 ) {
560 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
562 }
563 this.pending++;
564
565 return this;
566 };
567
568 /**
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
571 *
572 * @chainable
573 */
574 OO.ui.mixin.PendingElement.prototype.popPending = function () {
575 if ( this.pending === 1 ) {
576 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
578 }
579 this.pending = Math.max( 0, this.pending - 1 );
580
581 return this;
582 };
583
584 /**
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
588 *
589 * ActionSets contain two types of actions:
590 *
591 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
592 * - Other: Other actions include all non-special visible actions.
593 *
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
595 *
596 * @example
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
600 * }
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
609 * ];
610 *
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
619 * } );
620 * this.$body.append( this.stackLayout.$element );
621 * };
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
626 * }, this );
627 * };
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
636 * var dialog = this;
637 * return new OO.ui.Process( function () {
638 * dialog.close();
639 * } );
640 * }
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
642 * };
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
645 * };
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
649 * size: 'medium'
650 * } );
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
653 *
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
655 *
656 * @abstract
657 * @class
658 * @mixins OO.EventEmitter
659 *
660 * @constructor
661 * @param {Object} [config] Configuration options
662 */
663 OO.ui.ActionSet = function OoUiActionSet( config ) {
664 // Configuration initialization
665 config = config || {};
666
667 // Mixin constructors
668 OO.EventEmitter.call( this );
669
670 // Properties
671 this.list = [];
672 this.categories = {
673 actions: 'getAction',
674 flags: 'getFlags',
675 modes: 'getModes'
676 };
677 this.categorized = {};
678 this.special = {};
679 this.others = [];
680 this.organized = false;
681 this.changing = false;
682 this.changed = false;
683 };
684
685 /* Setup */
686
687 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
688
689 /* Static Properties */
690
691 /**
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
695 *
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
697 *
698 * @abstract
699 * @static
700 * @inheritable
701 * @property {string}
702 */
703 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
704
705 /* Events */
706
707 /**
708 * @event click
709 *
710 * A 'click' event is emitted when an action is clicked.
711 *
712 * @param {OO.ui.ActionWidget} action Action that was clicked
713 */
714
715 /**
716 * @event resize
717 *
718 * A 'resize' event is emitted when an action widget is resized.
719 *
720 * @param {OO.ui.ActionWidget} action Action that was resized
721 */
722
723 /**
724 * @event add
725 *
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
727 *
728 * @param {OO.ui.ActionWidget[]} added Actions added
729 */
730
731 /**
732 * @event remove
733 *
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
736 *
737 * @param {OO.ui.ActionWidget[]} added Actions removed
738 */
739
740 /**
741 * @event change
742 *
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
745 *
746 */
747
748 /* Methods */
749
750 /**
751 * Handle action change events.
752 *
753 * @private
754 * @fires change
755 */
756 OO.ui.ActionSet.prototype.onActionChange = function () {
757 this.organized = false;
758 if ( this.changing ) {
759 this.changed = true;
760 } else {
761 this.emit( 'change' );
762 }
763 };
764
765 /**
766 * Check if an action is one of the special actions.
767 *
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
770 */
771 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
772 var flag;
773
774 for ( flag in this.special ) {
775 if ( action === this.special[ flag ] ) {
776 return true;
777 }
778 }
779
780 return false;
781 };
782
783 /**
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
785 * or ‘disabled’.
786 *
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
794 */
795 OO.ui.ActionSet.prototype.get = function ( filters ) {
796 var i, len, list, category, actions, index, match, matches;
797
798 if ( filters ) {
799 this.organize();
800
801 // Collect category candidates
802 matches = [];
803 for ( category in this.categorized ) {
804 list = filters[ category ];
805 if ( list ) {
806 if ( !Array.isArray( list ) ) {
807 list = [ list ];
808 }
809 for ( i = 0, len = list.length; i < len; i++ ) {
810 actions = this.categorized[ category ][ list[ i ] ];
811 if ( Array.isArray( actions ) ) {
812 matches.push.apply( matches, actions );
813 }
814 }
815 }
816 }
817 // Remove by boolean filters
818 for ( i = 0, len = matches.length; i < len; i++ ) {
819 match = matches[ i ];
820 if (
821 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
822 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
823 ) {
824 matches.splice( i, 1 );
825 len--;
826 i--;
827 }
828 }
829 // Remove duplicates
830 for ( i = 0, len = matches.length; i < len; i++ ) {
831 match = matches[ i ];
832 index = matches.lastIndexOf( match );
833 while ( index !== i ) {
834 matches.splice( index, 1 );
835 len--;
836 index = matches.lastIndexOf( match );
837 }
838 }
839 return matches;
840 }
841 return this.list.slice();
842 };
843
844 /**
845 * Get 'special' actions.
846 *
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
849 *
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
851 */
852 OO.ui.ActionSet.prototype.getSpecial = function () {
853 this.organize();
854 return $.extend( {}, this.special );
855 };
856
857 /**
858 * Get 'other' actions.
859 *
860 * Other actions include all non-special visible action widgets.
861 *
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
863 */
864 OO.ui.ActionSet.prototype.getOthers = function () {
865 this.organize();
866 return this.others.slice();
867 };
868
869 /**
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
872 *
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
875 * @chainable
876 * @fires toggle
877 * @fires change
878 */
879 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
880 var i, len, action;
881
882 this.changing = true;
883 for ( i = 0, len = this.list.length; i < len; i++ ) {
884 action = this.list[ i ];
885 action.toggle( action.hasMode( mode ) );
886 }
887
888 this.organized = false;
889 this.changing = false;
890 this.emit( 'change' );
891
892 return this;
893 };
894
895 /**
896 * Set the abilities of the specified actions.
897 *
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
900 * parameter.
901 *
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
904 * @chainable
905 */
906 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
907 var i, len, action, item;
908
909 for ( i = 0, len = this.list.length; i < len; i++ ) {
910 item = this.list[ i ];
911 action = item.getAction();
912 if ( actions[ action ] !== undefined ) {
913 item.setDisabled( !actions[ action ] );
914 }
915 }
916
917 return this;
918 };
919
920 /**
921 * Executes a function once per action.
922 *
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
925 *
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
929 * @chainable
930 */
931 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
932 this.changed = false;
933 this.changing = true;
934 this.get( filter ).forEach( callback );
935 this.changing = false;
936 if ( this.changed ) {
937 this.emit( 'change' );
938 }
939
940 return this;
941 };
942
943 /**
944 * Add action widgets to the action set.
945 *
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
947 * @chainable
948 * @fires add
949 * @fires change
950 */
951 OO.ui.ActionSet.prototype.add = function ( actions ) {
952 var i, len, action;
953
954 this.changing = true;
955 for ( i = 0, len = actions.length; i < len; i++ ) {
956 action = actions[ i ];
957 action.connect( this, {
958 click: [ 'emit', 'click', action ],
959 resize: [ 'emit', 'resize', action ],
960 toggle: [ 'onActionChange' ]
961 } );
962 this.list.push( action );
963 }
964 this.organized = false;
965 this.emit( 'add', actions );
966 this.changing = false;
967 this.emit( 'change' );
968
969 return this;
970 };
971
972 /**
973 * Remove action widgets from the set.
974 *
975 * To remove all actions, you may wish to use the #clear method instead.
976 *
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
978 * @chainable
979 * @fires remove
980 * @fires change
981 */
982 OO.ui.ActionSet.prototype.remove = function ( actions ) {
983 var i, len, index, action;
984
985 this.changing = true;
986 for ( i = 0, len = actions.length; i < len; i++ ) {
987 action = actions[ i ];
988 index = this.list.indexOf( action );
989 if ( index !== -1 ) {
990 action.disconnect( this );
991 this.list.splice( index, 1 );
992 }
993 }
994 this.organized = false;
995 this.emit( 'remove', actions );
996 this.changing = false;
997 this.emit( 'change' );
998
999 return this;
1000 };
1001
1002 /**
1003 * Remove all action widets from the set.
1004 *
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1006 *
1007 * @chainable
1008 * @fires remove
1009 * @fires change
1010 */
1011 OO.ui.ActionSet.prototype.clear = function () {
1012 var i, len, action,
1013 removed = this.list.slice();
1014
1015 this.changing = true;
1016 for ( i = 0, len = this.list.length; i < len; i++ ) {
1017 action = this.list[ i ];
1018 action.disconnect( this );
1019 }
1020
1021 this.list = [];
1022
1023 this.organized = false;
1024 this.emit( 'remove', removed );
1025 this.changing = false;
1026 this.emit( 'change' );
1027
1028 return this;
1029 };
1030
1031 /**
1032 * Organize actions.
1033 *
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1036 *
1037 * @private
1038 * @chainable
1039 */
1040 OO.ui.ActionSet.prototype.organize = function () {
1041 var i, iLen, j, jLen, flag, action, category, list, item, special,
1042 specialFlags = this.constructor.static.specialFlags;
1043
1044 if ( !this.organized ) {
1045 this.categorized = {};
1046 this.special = {};
1047 this.others = [];
1048 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1049 action = this.list[ i ];
1050 if ( action.isVisible() ) {
1051 // Populate categories
1052 for ( category in this.categories ) {
1053 if ( !this.categorized[ category ] ) {
1054 this.categorized[ category ] = {};
1055 }
1056 list = action[ this.categories[ category ] ]();
1057 if ( !Array.isArray( list ) ) {
1058 list = [ list ];
1059 }
1060 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1061 item = list[ j ];
1062 if ( !this.categorized[ category ][ item ] ) {
1063 this.categorized[ category ][ item ] = [];
1064 }
1065 this.categorized[ category ][ item ].push( action );
1066 }
1067 }
1068 // Populate special/others
1069 special = false;
1070 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1071 flag = specialFlags[ j ];
1072 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1073 this.special[ flag ] = action;
1074 special = true;
1075 break;
1076 }
1077 }
1078 if ( !special ) {
1079 this.others.push( action );
1080 }
1081 }
1082 }
1083 this.organized = true;
1084 }
1085
1086 return this;
1087 };
1088
1089 /**
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1093 *
1094 * @abstract
1095 * @class
1096 *
1097 * @constructor
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1101 * for an example.
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text).
1109 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1110 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1111 * Data can also be specified with the #setData method.
1112 */
1113 OO.ui.Element = function OoUiElement( config ) {
1114 // Configuration initialization
1115 config = config || {};
1116
1117 // Properties
1118 this.$ = $;
1119 this.visible = true;
1120 this.data = config.data;
1121 this.$element = config.$element ||
1122 $( document.createElement( this.getTagName() ) );
1123 this.elementGroup = null;
1124 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1125
1126 // Initialization
1127 if ( Array.isArray( config.classes ) ) {
1128 this.$element.addClass( config.classes.join( ' ' ) );
1129 }
1130 if ( config.id ) {
1131 this.$element.attr( 'id', config.id );
1132 }
1133 if ( config.text ) {
1134 this.$element.text( config.text );
1135 }
1136 if ( config.content ) {
1137 // The `content` property treats plain strings as text; use an
1138 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1139 // appropriate $element appended.
1140 this.$element.append( config.content.map( function ( v ) {
1141 if ( typeof v === 'string' ) {
1142 // Escape string so it is properly represented in HTML.
1143 return document.createTextNode( v );
1144 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1145 // Bypass escaping.
1146 return v.toString();
1147 } else if ( v instanceof OO.ui.Element ) {
1148 return v.$element;
1149 }
1150 return v;
1151 } ) );
1152 }
1153 if ( config.$content ) {
1154 // The `$content` property treats plain strings as HTML.
1155 this.$element.append( config.$content );
1156 }
1157 };
1158
1159 /* Setup */
1160
1161 OO.initClass( OO.ui.Element );
1162
1163 /* Static Properties */
1164
1165 /**
1166 * The name of the HTML tag used by the element.
1167 *
1168 * The static value may be ignored if the #getTagName method is overridden.
1169 *
1170 * @static
1171 * @inheritable
1172 * @property {string}
1173 */
1174 OO.ui.Element.static.tagName = 'div';
1175
1176 /* Static Methods */
1177
1178 /**
1179 * Reconstitute a JavaScript object corresponding to a widget created
1180 * by the PHP implementation.
1181 *
1182 * @param {string|HTMLElement|jQuery} idOrNode
1183 * A DOM id (if a string) or node for the widget to infuse.
1184 * @return {OO.ui.Element}
1185 * The `OO.ui.Element` corresponding to this (infusable) document node.
1186 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1187 * the value returned is a newly-created Element wrapping around the existing
1188 * DOM node.
1189 */
1190 OO.ui.Element.static.infuse = function ( idOrNode ) {
1191 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1192 // Verify that the type matches up.
1193 // FIXME: uncomment after T89721 is fixed (see T90929)
1194 /*
1195 if ( !( obj instanceof this['class'] ) ) {
1196 throw new Error( 'Infusion type mismatch!' );
1197 }
1198 */
1199 return obj;
1200 };
1201
1202 /**
1203 * Implementation helper for `infuse`; skips the type check and has an
1204 * extra property so that only the top-level invocation touches the DOM.
1205 * @private
1206 * @param {string|HTMLElement|jQuery} idOrNode
1207 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1208 * when the top-level widget of this infusion is inserted into DOM,
1209 * replacing the original node; or false for top-level invocation.
1210 * @return {OO.ui.Element}
1211 */
1212 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1213 // look for a cached result of a previous infusion.
1214 var id, $elem, data, cls, parts, parent, obj, top, state;
1215 if ( typeof idOrNode === 'string' ) {
1216 id = idOrNode;
1217 $elem = $( document.getElementById( id ) );
1218 } else {
1219 $elem = $( idOrNode );
1220 id = $elem.attr( 'id' );
1221 }
1222 if ( !$elem.length ) {
1223 throw new Error( 'Widget not found: ' + id );
1224 }
1225 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1226 if ( data ) {
1227 // cached!
1228 if ( data === true ) {
1229 throw new Error( 'Circular dependency! ' + id );
1230 }
1231 return data;
1232 }
1233 data = $elem.attr( 'data-ooui' );
1234 if ( !data ) {
1235 throw new Error( 'No infusion data found: ' + id );
1236 }
1237 try {
1238 data = $.parseJSON( data );
1239 } catch ( _ ) {
1240 data = null;
1241 }
1242 if ( !( data && data._ ) ) {
1243 throw new Error( 'No valid infusion data found: ' + id );
1244 }
1245 if ( data._ === 'Tag' ) {
1246 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1247 return new OO.ui.Element( { $element: $elem } );
1248 }
1249 parts = data._.split( '.' );
1250 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1251 if ( cls === undefined ) {
1252 // The PHP output might be old and not including the "OO.ui" prefix
1253 // TODO: Remove this back-compat after next major release
1254 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1255 if ( cls === undefined ) {
1256 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1257 }
1258 }
1259
1260 // Verify that we're creating an OO.ui.Element instance
1261 parent = cls.parent;
1262
1263 while ( parent !== undefined ) {
1264 if ( parent === OO.ui.Element ) {
1265 // Safe
1266 break;
1267 }
1268
1269 parent = parent.parent;
1270 }
1271
1272 if ( parent !== OO.ui.Element ) {
1273 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1274 }
1275
1276 if ( domPromise === false ) {
1277 top = $.Deferred();
1278 domPromise = top.promise();
1279 }
1280 $elem.data( 'ooui-infused', true ); // prevent loops
1281 data.id = id; // implicit
1282 data = OO.copy( data, null, function deserialize( value ) {
1283 if ( OO.isPlainObject( value ) ) {
1284 if ( value.tag ) {
1285 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1286 }
1287 if ( value.html ) {
1288 return new OO.ui.HtmlSnippet( value.html );
1289 }
1290 }
1291 } );
1292 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1293 state = cls.static.gatherPreInfuseState( $elem, data );
1294 // jscs:disable requireCapitalizedConstructors
1295 obj = new cls( data ); // rebuild widget
1296 // now replace old DOM with this new DOM.
1297 if ( top ) {
1298 $elem.replaceWith( obj.$element );
1299 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1300 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1301 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1302 $elem[ 0 ].oouiInfused = obj;
1303 top.resolve();
1304 }
1305 obj.$element.data( 'ooui-infused', obj );
1306 // set the 'data-ooui' attribute so we can identify infused widgets
1307 obj.$element.attr( 'data-ooui', '' );
1308 // restore dynamic state after the new element is inserted into DOM
1309 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1310 return obj;
1311 };
1312
1313 /**
1314 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1315 * (and its children) that represent an Element of the same class and the given configuration,
1316 * generated by the PHP implementation.
1317 *
1318 * This method is called just before `node` is detached from the DOM. The return value of this
1319 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1320 * is inserted into DOM to replace `node`.
1321 *
1322 * @protected
1323 * @param {HTMLElement} node
1324 * @param {Object} config
1325 * @return {Object}
1326 */
1327 OO.ui.Element.static.gatherPreInfuseState = function () {
1328 return {};
1329 };
1330
1331 /**
1332 * Get a jQuery function within a specific document.
1333 *
1334 * @static
1335 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1336 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1337 * not in an iframe
1338 * @return {Function} Bound jQuery function
1339 */
1340 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1341 function wrapper( selector ) {
1342 return $( selector, wrapper.context );
1343 }
1344
1345 wrapper.context = this.getDocument( context );
1346
1347 if ( $iframe ) {
1348 wrapper.$iframe = $iframe;
1349 }
1350
1351 return wrapper;
1352 };
1353
1354 /**
1355 * Get the document of an element.
1356 *
1357 * @static
1358 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1359 * @return {HTMLDocument|null} Document object
1360 */
1361 OO.ui.Element.static.getDocument = function ( obj ) {
1362 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1363 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1364 // Empty jQuery selections might have a context
1365 obj.context ||
1366 // HTMLElement
1367 obj.ownerDocument ||
1368 // Window
1369 obj.document ||
1370 // HTMLDocument
1371 ( obj.nodeType === 9 && obj ) ||
1372 null;
1373 };
1374
1375 /**
1376 * Get the window of an element or document.
1377 *
1378 * @static
1379 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1380 * @return {Window} Window object
1381 */
1382 OO.ui.Element.static.getWindow = function ( obj ) {
1383 var doc = this.getDocument( obj );
1384 // Support: IE 8
1385 // Standard Document.defaultView is IE9+
1386 return doc.parentWindow || doc.defaultView;
1387 };
1388
1389 /**
1390 * Get the direction of an element or document.
1391 *
1392 * @static
1393 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1394 * @return {string} Text direction, either 'ltr' or 'rtl'
1395 */
1396 OO.ui.Element.static.getDir = function ( obj ) {
1397 var isDoc, isWin;
1398
1399 if ( obj instanceof jQuery ) {
1400 obj = obj[ 0 ];
1401 }
1402 isDoc = obj.nodeType === 9;
1403 isWin = obj.document !== undefined;
1404 if ( isDoc || isWin ) {
1405 if ( isWin ) {
1406 obj = obj.document;
1407 }
1408 obj = obj.body;
1409 }
1410 return $( obj ).css( 'direction' );
1411 };
1412
1413 /**
1414 * Get the offset between two frames.
1415 *
1416 * TODO: Make this function not use recursion.
1417 *
1418 * @static
1419 * @param {Window} from Window of the child frame
1420 * @param {Window} [to=window] Window of the parent frame
1421 * @param {Object} [offset] Offset to start with, used internally
1422 * @return {Object} Offset object, containing left and top properties
1423 */
1424 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1425 var i, len, frames, frame, rect;
1426
1427 if ( !to ) {
1428 to = window;
1429 }
1430 if ( !offset ) {
1431 offset = { top: 0, left: 0 };
1432 }
1433 if ( from.parent === from ) {
1434 return offset;
1435 }
1436
1437 // Get iframe element
1438 frames = from.parent.document.getElementsByTagName( 'iframe' );
1439 for ( i = 0, len = frames.length; i < len; i++ ) {
1440 if ( frames[ i ].contentWindow === from ) {
1441 frame = frames[ i ];
1442 break;
1443 }
1444 }
1445
1446 // Recursively accumulate offset values
1447 if ( frame ) {
1448 rect = frame.getBoundingClientRect();
1449 offset.left += rect.left;
1450 offset.top += rect.top;
1451 if ( from !== to ) {
1452 this.getFrameOffset( from.parent, offset );
1453 }
1454 }
1455 return offset;
1456 };
1457
1458 /**
1459 * Get the offset between two elements.
1460 *
1461 * The two elements may be in a different frame, but in that case the frame $element is in must
1462 * be contained in the frame $anchor is in.
1463 *
1464 * @static
1465 * @param {jQuery} $element Element whose position to get
1466 * @param {jQuery} $anchor Element to get $element's position relative to
1467 * @return {Object} Translated position coordinates, containing top and left properties
1468 */
1469 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1470 var iframe, iframePos,
1471 pos = $element.offset(),
1472 anchorPos = $anchor.offset(),
1473 elementDocument = this.getDocument( $element ),
1474 anchorDocument = this.getDocument( $anchor );
1475
1476 // If $element isn't in the same document as $anchor, traverse up
1477 while ( elementDocument !== anchorDocument ) {
1478 iframe = elementDocument.defaultView.frameElement;
1479 if ( !iframe ) {
1480 throw new Error( '$element frame is not contained in $anchor frame' );
1481 }
1482 iframePos = $( iframe ).offset();
1483 pos.left += iframePos.left;
1484 pos.top += iframePos.top;
1485 elementDocument = iframe.ownerDocument;
1486 }
1487 pos.left -= anchorPos.left;
1488 pos.top -= anchorPos.top;
1489 return pos;
1490 };
1491
1492 /**
1493 * Get element border sizes.
1494 *
1495 * @static
1496 * @param {HTMLElement} el Element to measure
1497 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1498 */
1499 OO.ui.Element.static.getBorders = function ( el ) {
1500 var doc = el.ownerDocument,
1501 // Support: IE 8
1502 // Standard Document.defaultView is IE9+
1503 win = doc.parentWindow || doc.defaultView,
1504 style = win && win.getComputedStyle ?
1505 win.getComputedStyle( el, null ) :
1506 // Support: IE 8
1507 // Standard getComputedStyle() is IE9+
1508 el.currentStyle,
1509 $el = $( el ),
1510 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1511 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1512 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1513 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1514
1515 return {
1516 top: top,
1517 left: left,
1518 bottom: bottom,
1519 right: right
1520 };
1521 };
1522
1523 /**
1524 * Get dimensions of an element or window.
1525 *
1526 * @static
1527 * @param {HTMLElement|Window} el Element to measure
1528 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1529 */
1530 OO.ui.Element.static.getDimensions = function ( el ) {
1531 var $el, $win,
1532 doc = el.ownerDocument || el.document,
1533 // Support: IE 8
1534 // Standard Document.defaultView is IE9+
1535 win = doc.parentWindow || doc.defaultView;
1536
1537 if ( win === el || el === doc.documentElement ) {
1538 $win = $( win );
1539 return {
1540 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1541 scroll: {
1542 top: $win.scrollTop(),
1543 left: $win.scrollLeft()
1544 },
1545 scrollbar: { right: 0, bottom: 0 },
1546 rect: {
1547 top: 0,
1548 left: 0,
1549 bottom: $win.innerHeight(),
1550 right: $win.innerWidth()
1551 }
1552 };
1553 } else {
1554 $el = $( el );
1555 return {
1556 borders: this.getBorders( el ),
1557 scroll: {
1558 top: $el.scrollTop(),
1559 left: $el.scrollLeft()
1560 },
1561 scrollbar: {
1562 right: $el.innerWidth() - el.clientWidth,
1563 bottom: $el.innerHeight() - el.clientHeight
1564 },
1565 rect: el.getBoundingClientRect()
1566 };
1567 }
1568 };
1569
1570 /**
1571 * Get scrollable object parent
1572 *
1573 * documentElement can't be used to get or set the scrollTop
1574 * property on Blink. Changing and testing its value lets us
1575 * use 'body' or 'documentElement' based on what is working.
1576 *
1577 * https://code.google.com/p/chromium/issues/detail?id=303131
1578 *
1579 * @static
1580 * @param {HTMLElement} el Element to find scrollable parent for
1581 * @return {HTMLElement} Scrollable parent
1582 */
1583 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1584 var scrollTop, body;
1585
1586 if ( OO.ui.scrollableElement === undefined ) {
1587 body = el.ownerDocument.body;
1588 scrollTop = body.scrollTop;
1589 body.scrollTop = 1;
1590
1591 if ( body.scrollTop === 1 ) {
1592 body.scrollTop = scrollTop;
1593 OO.ui.scrollableElement = 'body';
1594 } else {
1595 OO.ui.scrollableElement = 'documentElement';
1596 }
1597 }
1598
1599 return el.ownerDocument[ OO.ui.scrollableElement ];
1600 };
1601
1602 /**
1603 * Get closest scrollable container.
1604 *
1605 * Traverses up until either a scrollable element or the root is reached, in which case the window
1606 * will be returned.
1607 *
1608 * @static
1609 * @param {HTMLElement} el Element to find scrollable container for
1610 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1611 * @return {HTMLElement} Closest scrollable container
1612 */
1613 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1614 var i, val,
1615 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1616 props = [ 'overflow-x', 'overflow-y' ],
1617 $parent = $( el ).parent();
1618
1619 if ( dimension === 'x' || dimension === 'y' ) {
1620 props = [ 'overflow-' + dimension ];
1621 }
1622
1623 while ( $parent.length ) {
1624 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1625 return $parent[ 0 ];
1626 }
1627 i = props.length;
1628 while ( i-- ) {
1629 val = $parent.css( props[ i ] );
1630 if ( val === 'auto' || val === 'scroll' ) {
1631 return $parent[ 0 ];
1632 }
1633 }
1634 $parent = $parent.parent();
1635 }
1636 return this.getDocument( el ).body;
1637 };
1638
1639 /**
1640 * Scroll element into view.
1641 *
1642 * @static
1643 * @param {HTMLElement} el Element to scroll into view
1644 * @param {Object} [config] Configuration options
1645 * @param {string} [config.duration] jQuery animation duration value
1646 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1647 * to scroll in both directions
1648 * @param {Function} [config.complete] Function to call when scrolling completes
1649 */
1650 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1651 var rel, anim, callback, sc, $sc, eld, scd, $win;
1652
1653 // Configuration initialization
1654 config = config || {};
1655
1656 anim = {};
1657 callback = typeof config.complete === 'function' && config.complete;
1658 sc = this.getClosestScrollableContainer( el, config.direction );
1659 $sc = $( sc );
1660 eld = this.getDimensions( el );
1661 scd = this.getDimensions( sc );
1662 $win = $( this.getWindow( el ) );
1663
1664 // Compute the distances between the edges of el and the edges of the scroll viewport
1665 if ( $sc.is( 'html, body' ) ) {
1666 // If the scrollable container is the root, this is easy
1667 rel = {
1668 top: eld.rect.top,
1669 bottom: $win.innerHeight() - eld.rect.bottom,
1670 left: eld.rect.left,
1671 right: $win.innerWidth() - eld.rect.right
1672 };
1673 } else {
1674 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1675 rel = {
1676 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1677 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1678 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1679 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1680 };
1681 }
1682
1683 if ( !config.direction || config.direction === 'y' ) {
1684 if ( rel.top < 0 ) {
1685 anim.scrollTop = scd.scroll.top + rel.top;
1686 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1687 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1688 }
1689 }
1690 if ( !config.direction || config.direction === 'x' ) {
1691 if ( rel.left < 0 ) {
1692 anim.scrollLeft = scd.scroll.left + rel.left;
1693 } else if ( rel.left > 0 && rel.right < 0 ) {
1694 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1695 }
1696 }
1697 if ( !$.isEmptyObject( anim ) ) {
1698 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1699 if ( callback ) {
1700 $sc.queue( function ( next ) {
1701 callback();
1702 next();
1703 } );
1704 }
1705 } else {
1706 if ( callback ) {
1707 callback();
1708 }
1709 }
1710 };
1711
1712 /**
1713 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1714 * and reserve space for them, because it probably doesn't.
1715 *
1716 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1717 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1718 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1719 * and then reattach (or show) them back.
1720 *
1721 * @static
1722 * @param {HTMLElement} el Element to reconsider the scrollbars on
1723 */
1724 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1725 var i, len, scrollLeft, scrollTop, nodes = [];
1726 // Save scroll position
1727 scrollLeft = el.scrollLeft;
1728 scrollTop = el.scrollTop;
1729 // Detach all children
1730 while ( el.firstChild ) {
1731 nodes.push( el.firstChild );
1732 el.removeChild( el.firstChild );
1733 }
1734 // Force reflow
1735 void el.offsetHeight;
1736 // Reattach all children
1737 for ( i = 0, len = nodes.length; i < len; i++ ) {
1738 el.appendChild( nodes[ i ] );
1739 }
1740 // Restore scroll position (no-op if scrollbars disappeared)
1741 el.scrollLeft = scrollLeft;
1742 el.scrollTop = scrollTop;
1743 };
1744
1745 /* Methods */
1746
1747 /**
1748 * Toggle visibility of an element.
1749 *
1750 * @param {boolean} [show] Make element visible, omit to toggle visibility
1751 * @fires visible
1752 * @chainable
1753 */
1754 OO.ui.Element.prototype.toggle = function ( show ) {
1755 show = show === undefined ? !this.visible : !!show;
1756
1757 if ( show !== this.isVisible() ) {
1758 this.visible = show;
1759 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1760 this.emit( 'toggle', show );
1761 }
1762
1763 return this;
1764 };
1765
1766 /**
1767 * Check if element is visible.
1768 *
1769 * @return {boolean} element is visible
1770 */
1771 OO.ui.Element.prototype.isVisible = function () {
1772 return this.visible;
1773 };
1774
1775 /**
1776 * Get element data.
1777 *
1778 * @return {Mixed} Element data
1779 */
1780 OO.ui.Element.prototype.getData = function () {
1781 return this.data;
1782 };
1783
1784 /**
1785 * Set element data.
1786 *
1787 * @param {Mixed} Element data
1788 * @chainable
1789 */
1790 OO.ui.Element.prototype.setData = function ( data ) {
1791 this.data = data;
1792 return this;
1793 };
1794
1795 /**
1796 * Check if element supports one or more methods.
1797 *
1798 * @param {string|string[]} methods Method or list of methods to check
1799 * @return {boolean} All methods are supported
1800 */
1801 OO.ui.Element.prototype.supports = function ( methods ) {
1802 var i, len,
1803 support = 0;
1804
1805 methods = Array.isArray( methods ) ? methods : [ methods ];
1806 for ( i = 0, len = methods.length; i < len; i++ ) {
1807 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1808 support++;
1809 }
1810 }
1811
1812 return methods.length === support;
1813 };
1814
1815 /**
1816 * Update the theme-provided classes.
1817 *
1818 * @localdoc This is called in element mixins and widget classes any time state changes.
1819 * Updating is debounced, minimizing overhead of changing multiple attributes and
1820 * guaranteeing that theme updates do not occur within an element's constructor
1821 */
1822 OO.ui.Element.prototype.updateThemeClasses = function () {
1823 this.debouncedUpdateThemeClassesHandler();
1824 };
1825
1826 /**
1827 * @private
1828 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1829 * make them synchronous.
1830 */
1831 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1832 OO.ui.theme.updateElementClasses( this );
1833 };
1834
1835 /**
1836 * Get the HTML tag name.
1837 *
1838 * Override this method to base the result on instance information.
1839 *
1840 * @return {string} HTML tag name
1841 */
1842 OO.ui.Element.prototype.getTagName = function () {
1843 return this.constructor.static.tagName;
1844 };
1845
1846 /**
1847 * Check if the element is attached to the DOM
1848 * @return {boolean} The element is attached to the DOM
1849 */
1850 OO.ui.Element.prototype.isElementAttached = function () {
1851 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1852 };
1853
1854 /**
1855 * Get the DOM document.
1856 *
1857 * @return {HTMLDocument} Document object
1858 */
1859 OO.ui.Element.prototype.getElementDocument = function () {
1860 // Don't cache this in other ways either because subclasses could can change this.$element
1861 return OO.ui.Element.static.getDocument( this.$element );
1862 };
1863
1864 /**
1865 * Get the DOM window.
1866 *
1867 * @return {Window} Window object
1868 */
1869 OO.ui.Element.prototype.getElementWindow = function () {
1870 return OO.ui.Element.static.getWindow( this.$element );
1871 };
1872
1873 /**
1874 * Get closest scrollable container.
1875 */
1876 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1877 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1878 };
1879
1880 /**
1881 * Get group element is in.
1882 *
1883 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1884 */
1885 OO.ui.Element.prototype.getElementGroup = function () {
1886 return this.elementGroup;
1887 };
1888
1889 /**
1890 * Set group element is in.
1891 *
1892 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1893 * @chainable
1894 */
1895 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1896 this.elementGroup = group;
1897 return this;
1898 };
1899
1900 /**
1901 * Scroll element into view.
1902 *
1903 * @param {Object} [config] Configuration options
1904 */
1905 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1906 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1907 };
1908
1909 /**
1910 * Restore the pre-infusion dynamic state for this widget.
1911 *
1912 * This method is called after #$element has been inserted into DOM. The parameter is the return
1913 * value of #gatherPreInfuseState.
1914 *
1915 * @protected
1916 * @param {Object} state
1917 */
1918 OO.ui.Element.prototype.restorePreInfuseState = function () {
1919 };
1920
1921 /**
1922 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1923 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1924 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1925 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1926 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1927 *
1928 * @abstract
1929 * @class
1930 * @extends OO.ui.Element
1931 * @mixins OO.EventEmitter
1932 *
1933 * @constructor
1934 * @param {Object} [config] Configuration options
1935 */
1936 OO.ui.Layout = function OoUiLayout( config ) {
1937 // Configuration initialization
1938 config = config || {};
1939
1940 // Parent constructor
1941 OO.ui.Layout.parent.call( this, config );
1942
1943 // Mixin constructors
1944 OO.EventEmitter.call( this );
1945
1946 // Initialization
1947 this.$element.addClass( 'oo-ui-layout' );
1948 };
1949
1950 /* Setup */
1951
1952 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1953 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1954
1955 /**
1956 * Widgets are compositions of one or more OOjs UI elements that users can both view
1957 * and interact with. All widgets can be configured and modified via a standard API,
1958 * and their state can change dynamically according to a model.
1959 *
1960 * @abstract
1961 * @class
1962 * @extends OO.ui.Element
1963 * @mixins OO.EventEmitter
1964 *
1965 * @constructor
1966 * @param {Object} [config] Configuration options
1967 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1968 * appearance reflects this state.
1969 */
1970 OO.ui.Widget = function OoUiWidget( config ) {
1971 // Initialize config
1972 config = $.extend( { disabled: false }, config );
1973
1974 // Parent constructor
1975 OO.ui.Widget.parent.call( this, config );
1976
1977 // Mixin constructors
1978 OO.EventEmitter.call( this );
1979
1980 // Properties
1981 this.disabled = null;
1982 this.wasDisabled = null;
1983
1984 // Initialization
1985 this.$element.addClass( 'oo-ui-widget' );
1986 this.setDisabled( !!config.disabled );
1987 };
1988
1989 /* Setup */
1990
1991 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1992 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1993
1994 /* Static Properties */
1995
1996 /**
1997 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1998 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1999 * handling.
2000 *
2001 * @static
2002 * @inheritable
2003 * @property {boolean}
2004 */
2005 OO.ui.Widget.static.supportsSimpleLabel = false;
2006
2007 /* Events */
2008
2009 /**
2010 * @event disable
2011 *
2012 * A 'disable' event is emitted when the disabled state of the widget changes
2013 * (i.e. on disable **and** enable).
2014 *
2015 * @param {boolean} disabled Widget is disabled
2016 */
2017
2018 /**
2019 * @event toggle
2020 *
2021 * A 'toggle' event is emitted when the visibility of the widget changes.
2022 *
2023 * @param {boolean} visible Widget is visible
2024 */
2025
2026 /* Methods */
2027
2028 /**
2029 * Check if the widget is disabled.
2030 *
2031 * @return {boolean} Widget is disabled
2032 */
2033 OO.ui.Widget.prototype.isDisabled = function () {
2034 return this.disabled;
2035 };
2036
2037 /**
2038 * Set the 'disabled' state of the widget.
2039 *
2040 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2041 *
2042 * @param {boolean} disabled Disable widget
2043 * @chainable
2044 */
2045 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2046 var isDisabled;
2047
2048 this.disabled = !!disabled;
2049 isDisabled = this.isDisabled();
2050 if ( isDisabled !== this.wasDisabled ) {
2051 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2052 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2053 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2054 this.emit( 'disable', isDisabled );
2055 this.updateThemeClasses();
2056 }
2057 this.wasDisabled = isDisabled;
2058
2059 return this;
2060 };
2061
2062 /**
2063 * Update the disabled state, in case of changes in parent widget.
2064 *
2065 * @chainable
2066 */
2067 OO.ui.Widget.prototype.updateDisabled = function () {
2068 this.setDisabled( this.disabled );
2069 return this;
2070 };
2071
2072 /**
2073 * A window is a container for elements that are in a child frame. They are used with
2074 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2075 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2076 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2077 * the window manager will choose a sensible fallback.
2078 *
2079 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2080 * different processes are executed:
2081 *
2082 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2083 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2084 * the window.
2085 *
2086 * - {@link #getSetupProcess} method is called and its result executed
2087 * - {@link #getReadyProcess} method is called and its result executed
2088 *
2089 * **opened**: The window is now open
2090 *
2091 * **closing**: The closing stage begins when the window manager's
2092 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2093 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2094 *
2095 * - {@link #getHoldProcess} method is called and its result executed
2096 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2097 *
2098 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2099 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2100 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2101 * processing can complete. Always assume window processes are executed asynchronously.
2102 *
2103 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2104 *
2105 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2106 *
2107 * @abstract
2108 * @class
2109 * @extends OO.ui.Element
2110 * @mixins OO.EventEmitter
2111 *
2112 * @constructor
2113 * @param {Object} [config] Configuration options
2114 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2115 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2116 */
2117 OO.ui.Window = function OoUiWindow( config ) {
2118 // Configuration initialization
2119 config = config || {};
2120
2121 // Parent constructor
2122 OO.ui.Window.parent.call( this, config );
2123
2124 // Mixin constructors
2125 OO.EventEmitter.call( this );
2126
2127 // Properties
2128 this.manager = null;
2129 this.size = config.size || this.constructor.static.size;
2130 this.$frame = $( '<div>' );
2131 this.$overlay = $( '<div>' );
2132 this.$content = $( '<div>' );
2133
2134 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2135 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2136 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2137
2138 // Initialization
2139 this.$overlay.addClass( 'oo-ui-window-overlay' );
2140 this.$content
2141 .addClass( 'oo-ui-window-content' )
2142 .attr( 'tabindex', 0 );
2143 this.$frame
2144 .addClass( 'oo-ui-window-frame' )
2145 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2146
2147 this.$element
2148 .addClass( 'oo-ui-window' )
2149 .append( this.$frame, this.$overlay );
2150
2151 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2152 // that reference properties not initialized at that time of parent class construction
2153 // TODO: Find a better way to handle post-constructor setup
2154 this.visible = false;
2155 this.$element.addClass( 'oo-ui-element-hidden' );
2156 };
2157
2158 /* Setup */
2159
2160 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2161 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2162
2163 /* Static Properties */
2164
2165 /**
2166 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2167 *
2168 * The static size is used if no #size is configured during construction.
2169 *
2170 * @static
2171 * @inheritable
2172 * @property {string}
2173 */
2174 OO.ui.Window.static.size = 'medium';
2175
2176 /* Methods */
2177
2178 /**
2179 * Handle mouse down events.
2180 *
2181 * @private
2182 * @param {jQuery.Event} e Mouse down event
2183 */
2184 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2185 // Prevent clicking on the click-block from stealing focus
2186 if ( e.target === this.$element[ 0 ] ) {
2187 return false;
2188 }
2189 };
2190
2191 /**
2192 * Check if the window has been initialized.
2193 *
2194 * Initialization occurs when a window is added to a manager.
2195 *
2196 * @return {boolean} Window has been initialized
2197 */
2198 OO.ui.Window.prototype.isInitialized = function () {
2199 return !!this.manager;
2200 };
2201
2202 /**
2203 * Check if the window is visible.
2204 *
2205 * @return {boolean} Window is visible
2206 */
2207 OO.ui.Window.prototype.isVisible = function () {
2208 return this.visible;
2209 };
2210
2211 /**
2212 * Check if the window is opening.
2213 *
2214 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2215 * method.
2216 *
2217 * @return {boolean} Window is opening
2218 */
2219 OO.ui.Window.prototype.isOpening = function () {
2220 return this.manager.isOpening( this );
2221 };
2222
2223 /**
2224 * Check if the window is closing.
2225 *
2226 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2227 *
2228 * @return {boolean} Window is closing
2229 */
2230 OO.ui.Window.prototype.isClosing = function () {
2231 return this.manager.isClosing( this );
2232 };
2233
2234 /**
2235 * Check if the window is opened.
2236 *
2237 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2238 *
2239 * @return {boolean} Window is opened
2240 */
2241 OO.ui.Window.prototype.isOpened = function () {
2242 return this.manager.isOpened( this );
2243 };
2244
2245 /**
2246 * Get the window manager.
2247 *
2248 * All windows must be attached to a window manager, which is used to open
2249 * and close the window and control its presentation.
2250 *
2251 * @return {OO.ui.WindowManager} Manager of window
2252 */
2253 OO.ui.Window.prototype.getManager = function () {
2254 return this.manager;
2255 };
2256
2257 /**
2258 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2259 *
2260 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2261 */
2262 OO.ui.Window.prototype.getSize = function () {
2263 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2264 sizes = this.manager.constructor.static.sizes,
2265 size = this.size;
2266
2267 if ( !sizes[ size ] ) {
2268 size = this.manager.constructor.static.defaultSize;
2269 }
2270 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2271 size = 'full';
2272 }
2273
2274 return size;
2275 };
2276
2277 /**
2278 * Get the size properties associated with the current window size
2279 *
2280 * @return {Object} Size properties
2281 */
2282 OO.ui.Window.prototype.getSizeProperties = function () {
2283 return this.manager.constructor.static.sizes[ this.getSize() ];
2284 };
2285
2286 /**
2287 * Disable transitions on window's frame for the duration of the callback function, then enable them
2288 * back.
2289 *
2290 * @private
2291 * @param {Function} callback Function to call while transitions are disabled
2292 */
2293 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2294 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2295 // Disable transitions first, otherwise we'll get values from when the window was animating.
2296 var oldTransition,
2297 styleObj = this.$frame[ 0 ].style;
2298 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2299 styleObj.MozTransition || styleObj.WebkitTransition;
2300 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2301 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2302 callback();
2303 // Force reflow to make sure the style changes done inside callback really are not transitioned
2304 this.$frame.height();
2305 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2306 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2307 };
2308
2309 /**
2310 * Get the height of the full window contents (i.e., the window head, body and foot together).
2311 *
2312 * What consistitutes the head, body, and foot varies depending on the window type.
2313 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2314 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2315 * and special actions in the head, and dialog content in the body.
2316 *
2317 * To get just the height of the dialog body, use the #getBodyHeight method.
2318 *
2319 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2320 */
2321 OO.ui.Window.prototype.getContentHeight = function () {
2322 var bodyHeight,
2323 win = this,
2324 bodyStyleObj = this.$body[ 0 ].style,
2325 frameStyleObj = this.$frame[ 0 ].style;
2326
2327 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2328 // Disable transitions first, otherwise we'll get values from when the window was animating.
2329 this.withoutSizeTransitions( function () {
2330 var oldHeight = frameStyleObj.height,
2331 oldPosition = bodyStyleObj.position;
2332 frameStyleObj.height = '1px';
2333 // Force body to resize to new width
2334 bodyStyleObj.position = 'relative';
2335 bodyHeight = win.getBodyHeight();
2336 frameStyleObj.height = oldHeight;
2337 bodyStyleObj.position = oldPosition;
2338 } );
2339
2340 return (
2341 // Add buffer for border
2342 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2343 // Use combined heights of children
2344 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2345 );
2346 };
2347
2348 /**
2349 * Get the height of the window body.
2350 *
2351 * To get the height of the full window contents (the window body, head, and foot together),
2352 * use #getContentHeight.
2353 *
2354 * When this function is called, the window will temporarily have been resized
2355 * to height=1px, so .scrollHeight measurements can be taken accurately.
2356 *
2357 * @return {number} Height of the window body in pixels
2358 */
2359 OO.ui.Window.prototype.getBodyHeight = function () {
2360 return this.$body[ 0 ].scrollHeight;
2361 };
2362
2363 /**
2364 * Get the directionality of the frame (right-to-left or left-to-right).
2365 *
2366 * @return {string} Directionality: `'ltr'` or `'rtl'`
2367 */
2368 OO.ui.Window.prototype.getDir = function () {
2369 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2370 };
2371
2372 /**
2373 * Get the 'setup' process.
2374 *
2375 * The setup process is used to set up a window for use in a particular context,
2376 * based on the `data` argument. This method is called during the opening phase of the window’s
2377 * lifecycle.
2378 *
2379 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2380 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2381 * of OO.ui.Process.
2382 *
2383 * To add window content that persists between openings, you may wish to use the #initialize method
2384 * instead.
2385 *
2386 * @abstract
2387 * @param {Object} [data] Window opening data
2388 * @return {OO.ui.Process} Setup process
2389 */
2390 OO.ui.Window.prototype.getSetupProcess = function () {
2391 return new OO.ui.Process();
2392 };
2393
2394 /**
2395 * Get the ‘ready’ process.
2396 *
2397 * The ready process is used to ready a window for use in a particular
2398 * context, based on the `data` argument. This method is called during the opening phase of
2399 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2400 *
2401 * Override this method to add additional steps to the ‘ready’ process the parent method
2402 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2403 * methods of OO.ui.Process.
2404 *
2405 * @abstract
2406 * @param {Object} [data] Window opening data
2407 * @return {OO.ui.Process} Ready process
2408 */
2409 OO.ui.Window.prototype.getReadyProcess = function () {
2410 return new OO.ui.Process();
2411 };
2412
2413 /**
2414 * Get the 'hold' process.
2415 *
2416 * The hold proccess is used to keep a window from being used in a particular context,
2417 * based on the `data` argument. This method is called during the closing phase of the window’s
2418 * lifecycle.
2419 *
2420 * Override this method to add additional steps to the 'hold' process the parent method provides
2421 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2422 * of OO.ui.Process.
2423 *
2424 * @abstract
2425 * @param {Object} [data] Window closing data
2426 * @return {OO.ui.Process} Hold process
2427 */
2428 OO.ui.Window.prototype.getHoldProcess = function () {
2429 return new OO.ui.Process();
2430 };
2431
2432 /**
2433 * Get the ‘teardown’ process.
2434 *
2435 * The teardown process is used to teardown a window after use. During teardown,
2436 * user interactions within the window are conveyed and the window is closed, based on the `data`
2437 * argument. This method is called during the closing phase of the window’s lifecycle.
2438 *
2439 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2440 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2441 * of OO.ui.Process.
2442 *
2443 * @abstract
2444 * @param {Object} [data] Window closing data
2445 * @return {OO.ui.Process} Teardown process
2446 */
2447 OO.ui.Window.prototype.getTeardownProcess = function () {
2448 return new OO.ui.Process();
2449 };
2450
2451 /**
2452 * Set the window manager.
2453 *
2454 * This will cause the window to initialize. Calling it more than once will cause an error.
2455 *
2456 * @param {OO.ui.WindowManager} manager Manager for this window
2457 * @throws {Error} An error is thrown if the method is called more than once
2458 * @chainable
2459 */
2460 OO.ui.Window.prototype.setManager = function ( manager ) {
2461 if ( this.manager ) {
2462 throw new Error( 'Cannot set window manager, window already has a manager' );
2463 }
2464
2465 this.manager = manager;
2466 this.initialize();
2467
2468 return this;
2469 };
2470
2471 /**
2472 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2473 *
2474 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2475 * `full`
2476 * @chainable
2477 */
2478 OO.ui.Window.prototype.setSize = function ( size ) {
2479 this.size = size;
2480 this.updateSize();
2481 return this;
2482 };
2483
2484 /**
2485 * Update the window size.
2486 *
2487 * @throws {Error} An error is thrown if the window is not attached to a window manager
2488 * @chainable
2489 */
2490 OO.ui.Window.prototype.updateSize = function () {
2491 if ( !this.manager ) {
2492 throw new Error( 'Cannot update window size, must be attached to a manager' );
2493 }
2494
2495 this.manager.updateWindowSize( this );
2496
2497 return this;
2498 };
2499
2500 /**
2501 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2502 * when the window is opening. In general, setDimensions should not be called directly.
2503 *
2504 * To set the size of the window, use the #setSize method.
2505 *
2506 * @param {Object} dim CSS dimension properties
2507 * @param {string|number} [dim.width] Width
2508 * @param {string|number} [dim.minWidth] Minimum width
2509 * @param {string|number} [dim.maxWidth] Maximum width
2510 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2511 * @param {string|number} [dim.minWidth] Minimum height
2512 * @param {string|number} [dim.maxWidth] Maximum height
2513 * @chainable
2514 */
2515 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2516 var height,
2517 win = this,
2518 styleObj = this.$frame[ 0 ].style;
2519
2520 // Calculate the height we need to set using the correct width
2521 if ( dim.height === undefined ) {
2522 this.withoutSizeTransitions( function () {
2523 var oldWidth = styleObj.width;
2524 win.$frame.css( 'width', dim.width || '' );
2525 height = win.getContentHeight();
2526 styleObj.width = oldWidth;
2527 } );
2528 } else {
2529 height = dim.height;
2530 }
2531
2532 this.$frame.css( {
2533 width: dim.width || '',
2534 minWidth: dim.minWidth || '',
2535 maxWidth: dim.maxWidth || '',
2536 height: height || '',
2537 minHeight: dim.minHeight || '',
2538 maxHeight: dim.maxHeight || ''
2539 } );
2540
2541 return this;
2542 };
2543
2544 /**
2545 * Initialize window contents.
2546 *
2547 * Before the window is opened for the first time, #initialize is called so that content that
2548 * persists between openings can be added to the window.
2549 *
2550 * To set up a window with new content each time the window opens, use #getSetupProcess.
2551 *
2552 * @throws {Error} An error is thrown if the window is not attached to a window manager
2553 * @chainable
2554 */
2555 OO.ui.Window.prototype.initialize = function () {
2556 if ( !this.manager ) {
2557 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2558 }
2559
2560 // Properties
2561 this.$head = $( '<div>' );
2562 this.$body = $( '<div>' );
2563 this.$foot = $( '<div>' );
2564 this.$document = $( this.getElementDocument() );
2565
2566 // Events
2567 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2568
2569 // Initialization
2570 this.$head.addClass( 'oo-ui-window-head' );
2571 this.$body.addClass( 'oo-ui-window-body' );
2572 this.$foot.addClass( 'oo-ui-window-foot' );
2573 this.$content.append( this.$head, this.$body, this.$foot );
2574
2575 return this;
2576 };
2577
2578 /**
2579 * Called when someone tries to focus the hidden element at the end of the dialog.
2580 * Sends focus back to the start of the dialog.
2581 *
2582 * @param {jQuery.Event} event Focus event
2583 */
2584 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2585 if ( this.$focusTrapBefore.is( event.target ) ) {
2586 OO.ui.findFocusable( this.$content, true ).focus();
2587 } else {
2588 // this.$content is the part of the focus cycle, and is the first focusable element
2589 this.$content.focus();
2590 }
2591 };
2592
2593 /**
2594 * Open the window.
2595 *
2596 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2597 * method, which returns a promise resolved when the window is done opening.
2598 *
2599 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2600 *
2601 * @param {Object} [data] Window opening data
2602 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2603 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2604 * value is a new promise, which is resolved when the window begins closing.
2605 * @throws {Error} An error is thrown if the window is not attached to a window manager
2606 */
2607 OO.ui.Window.prototype.open = function ( data ) {
2608 if ( !this.manager ) {
2609 throw new Error( 'Cannot open window, must be attached to a manager' );
2610 }
2611
2612 return this.manager.openWindow( this, data );
2613 };
2614
2615 /**
2616 * Close the window.
2617 *
2618 * This method is a wrapper around a call to the window
2619 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2620 * which returns a closing promise resolved when the window is done closing.
2621 *
2622 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2623 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2624 * the window closes.
2625 *
2626 * @param {Object} [data] Window closing data
2627 * @return {jQuery.Promise} Promise resolved when window is closed
2628 * @throws {Error} An error is thrown if the window is not attached to a window manager
2629 */
2630 OO.ui.Window.prototype.close = function ( data ) {
2631 if ( !this.manager ) {
2632 throw new Error( 'Cannot close window, must be attached to a manager' );
2633 }
2634
2635 return this.manager.closeWindow( this, data );
2636 };
2637
2638 /**
2639 * Setup window.
2640 *
2641 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2642 * by other systems.
2643 *
2644 * @param {Object} [data] Window opening data
2645 * @return {jQuery.Promise} Promise resolved when window is setup
2646 */
2647 OO.ui.Window.prototype.setup = function ( data ) {
2648 var win = this,
2649 deferred = $.Deferred();
2650
2651 this.toggle( true );
2652
2653 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2654 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2655
2656 this.getSetupProcess( data ).execute().done( function () {
2657 // Force redraw by asking the browser to measure the elements' widths
2658 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2659 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2660 deferred.resolve();
2661 } );
2662
2663 return deferred.promise();
2664 };
2665
2666 /**
2667 * Ready window.
2668 *
2669 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2670 * by other systems.
2671 *
2672 * @param {Object} [data] Window opening data
2673 * @return {jQuery.Promise} Promise resolved when window is ready
2674 */
2675 OO.ui.Window.prototype.ready = function ( data ) {
2676 var win = this,
2677 deferred = $.Deferred();
2678
2679 this.$content.focus();
2680 this.getReadyProcess( data ).execute().done( function () {
2681 // Force redraw by asking the browser to measure the elements' widths
2682 win.$element.addClass( 'oo-ui-window-ready' ).width();
2683 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2684 deferred.resolve();
2685 } );
2686
2687 return deferred.promise();
2688 };
2689
2690 /**
2691 * Hold window.
2692 *
2693 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2694 * by other systems.
2695 *
2696 * @param {Object} [data] Window closing data
2697 * @return {jQuery.Promise} Promise resolved when window is held
2698 */
2699 OO.ui.Window.prototype.hold = function ( data ) {
2700 var win = this,
2701 deferred = $.Deferred();
2702
2703 this.getHoldProcess( data ).execute().done( function () {
2704 // Get the focused element within the window's content
2705 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2706
2707 // Blur the focused element
2708 if ( $focus.length ) {
2709 $focus[ 0 ].blur();
2710 }
2711
2712 // Force redraw by asking the browser to measure the elements' widths
2713 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2714 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2715 deferred.resolve();
2716 } );
2717
2718 return deferred.promise();
2719 };
2720
2721 /**
2722 * Teardown window.
2723 *
2724 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2725 * by other systems.
2726 *
2727 * @param {Object} [data] Window closing data
2728 * @return {jQuery.Promise} Promise resolved when window is torn down
2729 */
2730 OO.ui.Window.prototype.teardown = function ( data ) {
2731 var win = this;
2732
2733 return this.getTeardownProcess( data ).execute()
2734 .done( function () {
2735 // Force redraw by asking the browser to measure the elements' widths
2736 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2737 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2738 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2739 win.toggle( false );
2740 } );
2741 };
2742
2743 /**
2744 * The Dialog class serves as the base class for the other types of dialogs.
2745 * Unless extended to include controls, the rendered dialog box is a simple window
2746 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2747 * which opens, closes, and controls the presentation of the window. See the
2748 * [OOjs UI documentation on MediaWiki] [1] for more information.
2749 *
2750 * @example
2751 * // A simple dialog window.
2752 * function MyDialog( config ) {
2753 * MyDialog.parent.call( this, config );
2754 * }
2755 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2756 * MyDialog.prototype.initialize = function () {
2757 * MyDialog.parent.prototype.initialize.call( this );
2758 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2759 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2760 * this.$body.append( this.content.$element );
2761 * };
2762 * MyDialog.prototype.getBodyHeight = function () {
2763 * return this.content.$element.outerHeight( true );
2764 * };
2765 * var myDialog = new MyDialog( {
2766 * size: 'medium'
2767 * } );
2768 * // Create and append a window manager, which opens and closes the window.
2769 * var windowManager = new OO.ui.WindowManager();
2770 * $( 'body' ).append( windowManager.$element );
2771 * windowManager.addWindows( [ myDialog ] );
2772 * // Open the window!
2773 * windowManager.openWindow( myDialog );
2774 *
2775 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2776 *
2777 * @abstract
2778 * @class
2779 * @extends OO.ui.Window
2780 * @mixins OO.ui.mixin.PendingElement
2781 *
2782 * @constructor
2783 * @param {Object} [config] Configuration options
2784 */
2785 OO.ui.Dialog = function OoUiDialog( config ) {
2786 // Parent constructor
2787 OO.ui.Dialog.parent.call( this, config );
2788
2789 // Mixin constructors
2790 OO.ui.mixin.PendingElement.call( this );
2791
2792 // Properties
2793 this.actions = new OO.ui.ActionSet();
2794 this.attachedActions = [];
2795 this.currentAction = null;
2796 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2797
2798 // Events
2799 this.actions.connect( this, {
2800 click: 'onActionClick',
2801 resize: 'onActionResize',
2802 change: 'onActionsChange'
2803 } );
2804
2805 // Initialization
2806 this.$element
2807 .addClass( 'oo-ui-dialog' )
2808 .attr( 'role', 'dialog' );
2809 };
2810
2811 /* Setup */
2812
2813 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2814 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2815
2816 /* Static Properties */
2817
2818 /**
2819 * Symbolic name of dialog.
2820 *
2821 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2822 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2823 *
2824 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2825 *
2826 * @abstract
2827 * @static
2828 * @inheritable
2829 * @property {string}
2830 */
2831 OO.ui.Dialog.static.name = '';
2832
2833 /**
2834 * The dialog title.
2835 *
2836 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2837 * that will produce a Label node or string. The title can also be specified with data passed to the
2838 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2839 *
2840 * @abstract
2841 * @static
2842 * @inheritable
2843 * @property {jQuery|string|Function}
2844 */
2845 OO.ui.Dialog.static.title = '';
2846
2847 /**
2848 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2849 *
2850 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2851 * value will be overriden.
2852 *
2853 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2854 *
2855 * @static
2856 * @inheritable
2857 * @property {Object[]}
2858 */
2859 OO.ui.Dialog.static.actions = [];
2860
2861 /**
2862 * Close the dialog when the 'Esc' key is pressed.
2863 *
2864 * @static
2865 * @abstract
2866 * @inheritable
2867 * @property {boolean}
2868 */
2869 OO.ui.Dialog.static.escapable = true;
2870
2871 /* Methods */
2872
2873 /**
2874 * Handle frame document key down events.
2875 *
2876 * @private
2877 * @param {jQuery.Event} e Key down event
2878 */
2879 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2880 if ( e.which === OO.ui.Keys.ESCAPE ) {
2881 this.close();
2882 e.preventDefault();
2883 e.stopPropagation();
2884 }
2885 };
2886
2887 /**
2888 * Handle action resized events.
2889 *
2890 * @private
2891 * @param {OO.ui.ActionWidget} action Action that was resized
2892 */
2893 OO.ui.Dialog.prototype.onActionResize = function () {
2894 // Override in subclass
2895 };
2896
2897 /**
2898 * Handle action click events.
2899 *
2900 * @private
2901 * @param {OO.ui.ActionWidget} action Action that was clicked
2902 */
2903 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2904 if ( !this.isPending() ) {
2905 this.executeAction( action.getAction() );
2906 }
2907 };
2908
2909 /**
2910 * Handle actions change event.
2911 *
2912 * @private
2913 */
2914 OO.ui.Dialog.prototype.onActionsChange = function () {
2915 this.detachActions();
2916 if ( !this.isClosing() ) {
2917 this.attachActions();
2918 }
2919 };
2920
2921 /**
2922 * Get the set of actions used by the dialog.
2923 *
2924 * @return {OO.ui.ActionSet}
2925 */
2926 OO.ui.Dialog.prototype.getActions = function () {
2927 return this.actions;
2928 };
2929
2930 /**
2931 * Get a process for taking action.
2932 *
2933 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2934 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2935 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2936 *
2937 * @abstract
2938 * @param {string} [action] Symbolic name of action
2939 * @return {OO.ui.Process} Action process
2940 */
2941 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2942 return new OO.ui.Process()
2943 .next( function () {
2944 if ( !action ) {
2945 // An empty action always closes the dialog without data, which should always be
2946 // safe and make no changes
2947 this.close();
2948 }
2949 }, this );
2950 };
2951
2952 /**
2953 * @inheritdoc
2954 *
2955 * @param {Object} [data] Dialog opening data
2956 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2957 * the {@link #static-title static title}
2958 * @param {Object[]} [data.actions] List of configuration options for each
2959 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2960 */
2961 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2962 data = data || {};
2963
2964 // Parent method
2965 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2966 .next( function () {
2967 var config = this.constructor.static,
2968 actions = data.actions !== undefined ? data.actions : config.actions;
2969
2970 this.title.setLabel(
2971 data.title !== undefined ? data.title : this.constructor.static.title
2972 );
2973 this.actions.add( this.getActionWidgets( actions ) );
2974
2975 if ( this.constructor.static.escapable ) {
2976 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2977 }
2978 }, this );
2979 };
2980
2981 /**
2982 * @inheritdoc
2983 */
2984 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2985 // Parent method
2986 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2987 .first( function () {
2988 if ( this.constructor.static.escapable ) {
2989 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2990 }
2991
2992 this.actions.clear();
2993 this.currentAction = null;
2994 }, this );
2995 };
2996
2997 /**
2998 * @inheritdoc
2999 */
3000 OO.ui.Dialog.prototype.initialize = function () {
3001 var titleId;
3002
3003 // Parent method
3004 OO.ui.Dialog.parent.prototype.initialize.call( this );
3005
3006 titleId = OO.ui.generateElementId();
3007
3008 // Properties
3009 this.title = new OO.ui.LabelWidget( {
3010 id: titleId
3011 } );
3012
3013 // Initialization
3014 this.$content.addClass( 'oo-ui-dialog-content' );
3015 this.$element.attr( 'aria-labelledby', titleId );
3016 this.setPendingElement( this.$head );
3017 };
3018
3019 /**
3020 * Get action widgets from a list of configs
3021 *
3022 * @param {Object[]} actions Action widget configs
3023 * @return {OO.ui.ActionWidget[]} Action widgets
3024 */
3025 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3026 var i, len, widgets = [];
3027 for ( i = 0, len = actions.length; i < len; i++ ) {
3028 widgets.push(
3029 new OO.ui.ActionWidget( actions[ i ] )
3030 );
3031 }
3032 return widgets;
3033 };
3034
3035 /**
3036 * Attach action actions.
3037 *
3038 * @protected
3039 */
3040 OO.ui.Dialog.prototype.attachActions = function () {
3041 // Remember the list of potentially attached actions
3042 this.attachedActions = this.actions.get();
3043 };
3044
3045 /**
3046 * Detach action actions.
3047 *
3048 * @protected
3049 * @chainable
3050 */
3051 OO.ui.Dialog.prototype.detachActions = function () {
3052 var i, len;
3053
3054 // Detach all actions that may have been previously attached
3055 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3056 this.attachedActions[ i ].$element.detach();
3057 }
3058 this.attachedActions = [];
3059 };
3060
3061 /**
3062 * Execute an action.
3063 *
3064 * @param {string} action Symbolic name of action to execute
3065 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3066 */
3067 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3068 this.pushPending();
3069 this.currentAction = action;
3070 return this.getActionProcess( action ).execute()
3071 .always( this.popPending.bind( this ) );
3072 };
3073
3074 /**
3075 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3076 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3077 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3078 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3079 * pertinent data and reused.
3080 *
3081 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3082 * `opened`, and `closing`, which represent the primary stages of the cycle:
3083 *
3084 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3085 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3086 *
3087 * - an `opening` event is emitted with an `opening` promise
3088 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3089 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3090 * window and its result executed
3091 * - a `setup` progress notification is emitted from the `opening` promise
3092 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3093 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3094 * window and its result executed
3095 * - a `ready` progress notification is emitted from the `opening` promise
3096 * - the `opening` promise is resolved with an `opened` promise
3097 *
3098 * **Opened**: the window is now open.
3099 *
3100 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3101 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3102 * to close the window.
3103 *
3104 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3105 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3106 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3107 * window and its result executed
3108 * - a `hold` progress notification is emitted from the `closing` promise
3109 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3110 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3111 * window and its result executed
3112 * - a `teardown` progress notification is emitted from the `closing` promise
3113 * - the `closing` promise is resolved. The window is now closed
3114 *
3115 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3116 *
3117 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3118 *
3119 * @class
3120 * @extends OO.ui.Element
3121 * @mixins OO.EventEmitter
3122 *
3123 * @constructor
3124 * @param {Object} [config] Configuration options
3125 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3126 * Note that window classes that are instantiated with a factory must have
3127 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3128 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3129 */
3130 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3131 // Configuration initialization
3132 config = config || {};
3133
3134 // Parent constructor
3135 OO.ui.WindowManager.parent.call( this, config );
3136
3137 // Mixin constructors
3138 OO.EventEmitter.call( this );
3139
3140 // Properties
3141 this.factory = config.factory;
3142 this.modal = config.modal === undefined || !!config.modal;
3143 this.windows = {};
3144 this.opening = null;
3145 this.opened = null;
3146 this.closing = null;
3147 this.preparingToOpen = null;
3148 this.preparingToClose = null;
3149 this.currentWindow = null;
3150 this.globalEvents = false;
3151 this.$ariaHidden = null;
3152 this.onWindowResizeTimeout = null;
3153 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3154 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3155
3156 // Initialization
3157 this.$element
3158 .addClass( 'oo-ui-windowManager' )
3159 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3160 };
3161
3162 /* Setup */
3163
3164 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3165 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3166
3167 /* Events */
3168
3169 /**
3170 * An 'opening' event is emitted when the window begins to be opened.
3171 *
3172 * @event opening
3173 * @param {OO.ui.Window} win Window that's being opened
3174 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3175 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3176 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3177 * @param {Object} data Window opening data
3178 */
3179
3180 /**
3181 * A 'closing' event is emitted when the window begins to be closed.
3182 *
3183 * @event closing
3184 * @param {OO.ui.Window} win Window that's being closed
3185 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3186 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3187 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3188 * is the closing data.
3189 * @param {Object} data Window closing data
3190 */
3191
3192 /**
3193 * A 'resize' event is emitted when a window is resized.
3194 *
3195 * @event resize
3196 * @param {OO.ui.Window} win Window that was resized
3197 */
3198
3199 /* Static Properties */
3200
3201 /**
3202 * Map of the symbolic name of each window size and its CSS properties.
3203 *
3204 * @static
3205 * @inheritable
3206 * @property {Object}
3207 */
3208 OO.ui.WindowManager.static.sizes = {
3209 small: {
3210 width: 300
3211 },
3212 medium: {
3213 width: 500
3214 },
3215 large: {
3216 width: 700
3217 },
3218 larger: {
3219 width: 900
3220 },
3221 full: {
3222 // These can be non-numeric because they are never used in calculations
3223 width: '100%',
3224 height: '100%'
3225 }
3226 };
3227
3228 /**
3229 * Symbolic name of the default window size.
3230 *
3231 * The default size is used if the window's requested size is not recognized.
3232 *
3233 * @static
3234 * @inheritable
3235 * @property {string}
3236 */
3237 OO.ui.WindowManager.static.defaultSize = 'medium';
3238
3239 /* Methods */
3240
3241 /**
3242 * Handle window resize events.
3243 *
3244 * @private
3245 * @param {jQuery.Event} e Window resize event
3246 */
3247 OO.ui.WindowManager.prototype.onWindowResize = function () {
3248 clearTimeout( this.onWindowResizeTimeout );
3249 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3250 };
3251
3252 /**
3253 * Handle window resize events.
3254 *
3255 * @private
3256 * @param {jQuery.Event} e Window resize event
3257 */
3258 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3259 if ( this.currentWindow ) {
3260 this.updateWindowSize( this.currentWindow );
3261 }
3262 };
3263
3264 /**
3265 * Check if window is opening.
3266 *
3267 * @return {boolean} Window is opening
3268 */
3269 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3270 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3271 };
3272
3273 /**
3274 * Check if window is closing.
3275 *
3276 * @return {boolean} Window is closing
3277 */
3278 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3279 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3280 };
3281
3282 /**
3283 * Check if window is opened.
3284 *
3285 * @return {boolean} Window is opened
3286 */
3287 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3288 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3289 };
3290
3291 /**
3292 * Check if a window is being managed.
3293 *
3294 * @param {OO.ui.Window} win Window to check
3295 * @return {boolean} Window is being managed
3296 */
3297 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3298 var name;
3299
3300 for ( name in this.windows ) {
3301 if ( this.windows[ name ] === win ) {
3302 return true;
3303 }
3304 }
3305
3306 return false;
3307 };
3308
3309 /**
3310 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3311 *
3312 * @param {OO.ui.Window} win Window being opened
3313 * @param {Object} [data] Window opening data
3314 * @return {number} Milliseconds to wait
3315 */
3316 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3317 return 0;
3318 };
3319
3320 /**
3321 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3322 *
3323 * @param {OO.ui.Window} win Window being opened
3324 * @param {Object} [data] Window opening data
3325 * @return {number} Milliseconds to wait
3326 */
3327 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3328 return 0;
3329 };
3330
3331 /**
3332 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3333 *
3334 * @param {OO.ui.Window} win Window being closed
3335 * @param {Object} [data] Window closing data
3336 * @return {number} Milliseconds to wait
3337 */
3338 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3339 return 0;
3340 };
3341
3342 /**
3343 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3344 * executing the ‘teardown’ process.
3345 *
3346 * @param {OO.ui.Window} win Window being closed
3347 * @param {Object} [data] Window closing data
3348 * @return {number} Milliseconds to wait
3349 */
3350 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3351 return this.modal ? 250 : 0;
3352 };
3353
3354 /**
3355 * Get a window by its symbolic name.
3356 *
3357 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3358 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3359 * for more information about using factories.
3360 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3361 *
3362 * @param {string} name Symbolic name of the window
3363 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3364 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3365 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3366 */
3367 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3368 var deferred = $.Deferred(),
3369 win = this.windows[ name ];
3370
3371 if ( !( win instanceof OO.ui.Window ) ) {
3372 if ( this.factory ) {
3373 if ( !this.factory.lookup( name ) ) {
3374 deferred.reject( new OO.ui.Error(
3375 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3376 ) );
3377 } else {
3378 win = this.factory.create( name );
3379 this.addWindows( [ win ] );
3380 deferred.resolve( win );
3381 }
3382 } else {
3383 deferred.reject( new OO.ui.Error(
3384 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3385 ) );
3386 }
3387 } else {
3388 deferred.resolve( win );
3389 }
3390
3391 return deferred.promise();
3392 };
3393
3394 /**
3395 * Get current window.
3396 *
3397 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3398 */
3399 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3400 return this.currentWindow;
3401 };
3402
3403 /**
3404 * Open a window.
3405 *
3406 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3407 * @param {Object} [data] Window opening data
3408 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3409 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3410 * @fires opening
3411 */
3412 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3413 var manager = this,
3414 opening = $.Deferred();
3415
3416 // Argument handling
3417 if ( typeof win === 'string' ) {
3418 return this.getWindow( win ).then( function ( win ) {
3419 return manager.openWindow( win, data );
3420 } );
3421 }
3422
3423 // Error handling
3424 if ( !this.hasWindow( win ) ) {
3425 opening.reject( new OO.ui.Error(
3426 'Cannot open window: window is not attached to manager'
3427 ) );
3428 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3429 opening.reject( new OO.ui.Error(
3430 'Cannot open window: another window is opening or open'
3431 ) );
3432 }
3433
3434 // Window opening
3435 if ( opening.state() !== 'rejected' ) {
3436 // If a window is currently closing, wait for it to complete
3437 this.preparingToOpen = $.when( this.closing );
3438 // Ensure handlers get called after preparingToOpen is set
3439 this.preparingToOpen.done( function () {
3440 if ( manager.modal ) {
3441 manager.toggleGlobalEvents( true );
3442 manager.toggleAriaIsolation( true );
3443 }
3444 manager.currentWindow = win;
3445 manager.opening = opening;
3446 manager.preparingToOpen = null;
3447 manager.emit( 'opening', win, opening, data );
3448 setTimeout( function () {
3449 win.setup( data ).then( function () {
3450 manager.updateWindowSize( win );
3451 manager.opening.notify( { state: 'setup' } );
3452 setTimeout( function () {
3453 win.ready( data ).then( function () {
3454 manager.opening.notify( { state: 'ready' } );
3455 manager.opening = null;
3456 manager.opened = $.Deferred();
3457 opening.resolve( manager.opened.promise(), data );
3458 } );
3459 }, manager.getReadyDelay() );
3460 } );
3461 }, manager.getSetupDelay() );
3462 } );
3463 }
3464
3465 return opening.promise();
3466 };
3467
3468 /**
3469 * Close a window.
3470 *
3471 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3472 * @param {Object} [data] Window closing data
3473 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3474 * See {@link #event-closing 'closing' event} for more information about closing promises.
3475 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3476 * @fires closing
3477 */
3478 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3479 var manager = this,
3480 closing = $.Deferred(),
3481 opened;
3482
3483 // Argument handling
3484 if ( typeof win === 'string' ) {
3485 win = this.windows[ win ];
3486 } else if ( !this.hasWindow( win ) ) {
3487 win = null;
3488 }
3489
3490 // Error handling
3491 if ( !win ) {
3492 closing.reject( new OO.ui.Error(
3493 'Cannot close window: window is not attached to manager'
3494 ) );
3495 } else if ( win !== this.currentWindow ) {
3496 closing.reject( new OO.ui.Error(
3497 'Cannot close window: window already closed with different data'
3498 ) );
3499 } else if ( this.preparingToClose || this.closing ) {
3500 closing.reject( new OO.ui.Error(
3501 'Cannot close window: window already closing with different data'
3502 ) );
3503 }
3504
3505 // Window closing
3506 if ( closing.state() !== 'rejected' ) {
3507 // If the window is currently opening, close it when it's done
3508 this.preparingToClose = $.when( this.opening );
3509 // Ensure handlers get called after preparingToClose is set
3510 this.preparingToClose.done( function () {
3511 manager.closing = closing;
3512 manager.preparingToClose = null;
3513 manager.emit( 'closing', win, closing, data );
3514 opened = manager.opened;
3515 manager.opened = null;
3516 opened.resolve( closing.promise(), data );
3517 setTimeout( function () {
3518 win.hold( data ).then( function () {
3519 closing.notify( { state: 'hold' } );
3520 setTimeout( function () {
3521 win.teardown( data ).then( function () {
3522 closing.notify( { state: 'teardown' } );
3523 if ( manager.modal ) {
3524 manager.toggleGlobalEvents( false );
3525 manager.toggleAriaIsolation( false );
3526 }
3527 manager.closing = null;
3528 manager.currentWindow = null;
3529 closing.resolve( data );
3530 } );
3531 }, manager.getTeardownDelay() );
3532 } );
3533 }, manager.getHoldDelay() );
3534 } );
3535 }
3536
3537 return closing.promise();
3538 };
3539
3540 /**
3541 * Add windows to the window manager.
3542 *
3543 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3544 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3545 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3546 *
3547 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3548 * by reference, symbolic name, or explicitly defined symbolic names.
3549 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3550 * explicit nor a statically configured symbolic name.
3551 */
3552 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3553 var i, len, win, name, list;
3554
3555 if ( Array.isArray( windows ) ) {
3556 // Convert to map of windows by looking up symbolic names from static configuration
3557 list = {};
3558 for ( i = 0, len = windows.length; i < len; i++ ) {
3559 name = windows[ i ].constructor.static.name;
3560 if ( typeof name !== 'string' ) {
3561 throw new Error( 'Cannot add window' );
3562 }
3563 list[ name ] = windows[ i ];
3564 }
3565 } else if ( OO.isPlainObject( windows ) ) {
3566 list = windows;
3567 }
3568
3569 // Add windows
3570 for ( name in list ) {
3571 win = list[ name ];
3572 this.windows[ name ] = win.toggle( false );
3573 this.$element.append( win.$element );
3574 win.setManager( this );
3575 }
3576 };
3577
3578 /**
3579 * Remove the specified windows from the windows manager.
3580 *
3581 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3582 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3583 * longer listens to events, use the #destroy method.
3584 *
3585 * @param {string[]} names Symbolic names of windows to remove
3586 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3587 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3588 */
3589 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3590 var i, len, win, name, cleanupWindow,
3591 manager = this,
3592 promises = [],
3593 cleanup = function ( name, win ) {
3594 delete manager.windows[ name ];
3595 win.$element.detach();
3596 };
3597
3598 for ( i = 0, len = names.length; i < len; i++ ) {
3599 name = names[ i ];
3600 win = this.windows[ name ];
3601 if ( !win ) {
3602 throw new Error( 'Cannot remove window' );
3603 }
3604 cleanupWindow = cleanup.bind( null, name, win );
3605 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3606 }
3607
3608 return $.when.apply( $, promises );
3609 };
3610
3611 /**
3612 * Remove all windows from the window manager.
3613 *
3614 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3615 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3616 * To remove just a subset of windows, use the #removeWindows method.
3617 *
3618 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3619 */
3620 OO.ui.WindowManager.prototype.clearWindows = function () {
3621 return this.removeWindows( Object.keys( this.windows ) );
3622 };
3623
3624 /**
3625 * Set dialog size. In general, this method should not be called directly.
3626 *
3627 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3628 *
3629 * @chainable
3630 */
3631 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3632 var isFullscreen;
3633
3634 // Bypass for non-current, and thus invisible, windows
3635 if ( win !== this.currentWindow ) {
3636 return;
3637 }
3638
3639 isFullscreen = win.getSize() === 'full';
3640
3641 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3642 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3643 win.setDimensions( win.getSizeProperties() );
3644
3645 this.emit( 'resize', win );
3646
3647 return this;
3648 };
3649
3650 /**
3651 * Bind or unbind global events for scrolling.
3652 *
3653 * @private
3654 * @param {boolean} [on] Bind global events
3655 * @chainable
3656 */
3657 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3658 var scrollWidth, bodyMargin,
3659 $body = $( this.getElementDocument().body ),
3660 // We could have multiple window managers open so only modify
3661 // the body css at the bottom of the stack
3662 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3663
3664 on = on === undefined ? !!this.globalEvents : !!on;
3665
3666 if ( on ) {
3667 if ( !this.globalEvents ) {
3668 $( this.getElementWindow() ).on( {
3669 // Start listening for top-level window dimension changes
3670 'orientationchange resize': this.onWindowResizeHandler
3671 } );
3672 if ( stackDepth === 0 ) {
3673 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3674 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3675 $body.css( {
3676 overflow: 'hidden',
3677 'margin-right': bodyMargin + scrollWidth
3678 } );
3679 }
3680 stackDepth++;
3681 this.globalEvents = true;
3682 }
3683 } else if ( this.globalEvents ) {
3684 $( this.getElementWindow() ).off( {
3685 // Stop listening for top-level window dimension changes
3686 'orientationchange resize': this.onWindowResizeHandler
3687 } );
3688 stackDepth--;
3689 if ( stackDepth === 0 ) {
3690 $body.css( {
3691 overflow: '',
3692 'margin-right': ''
3693 } );
3694 }
3695 this.globalEvents = false;
3696 }
3697 $body.data( 'windowManagerGlobalEvents', stackDepth );
3698
3699 return this;
3700 };
3701
3702 /**
3703 * Toggle screen reader visibility of content other than the window manager.
3704 *
3705 * @private
3706 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3707 * @chainable
3708 */
3709 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3710 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3711
3712 if ( isolate ) {
3713 if ( !this.$ariaHidden ) {
3714 // Hide everything other than the window manager from screen readers
3715 this.$ariaHidden = $( 'body' )
3716 .children()
3717 .not( this.$element.parentsUntil( 'body' ).last() )
3718 .attr( 'aria-hidden', '' );
3719 }
3720 } else if ( this.$ariaHidden ) {
3721 // Restore screen reader visibility
3722 this.$ariaHidden.removeAttr( 'aria-hidden' );
3723 this.$ariaHidden = null;
3724 }
3725
3726 return this;
3727 };
3728
3729 /**
3730 * Destroy the window manager.
3731 *
3732 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3733 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3734 * instead.
3735 */
3736 OO.ui.WindowManager.prototype.destroy = function () {
3737 this.toggleGlobalEvents( false );
3738 this.toggleAriaIsolation( false );
3739 this.clearWindows();
3740 this.$element.remove();
3741 };
3742
3743 /**
3744 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3745 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3746 * appearance and functionality of the error interface.
3747 *
3748 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3749 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3750 * that initiated the failed process will be disabled.
3751 *
3752 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3753 * process again.
3754 *
3755 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3756 *
3757 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3758 *
3759 * @class
3760 *
3761 * @constructor
3762 * @param {string|jQuery} message Description of error
3763 * @param {Object} [config] Configuration options
3764 * @cfg {boolean} [recoverable=true] Error is recoverable.
3765 * By default, errors are recoverable, and users can try the process again.
3766 * @cfg {boolean} [warning=false] Error is a warning.
3767 * If the error is a warning, the error interface will include a
3768 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3769 * is not triggered a second time if the user chooses to continue.
3770 */
3771 OO.ui.Error = function OoUiError( message, config ) {
3772 // Allow passing positional parameters inside the config object
3773 if ( OO.isPlainObject( message ) && config === undefined ) {
3774 config = message;
3775 message = config.message;
3776 }
3777
3778 // Configuration initialization
3779 config = config || {};
3780
3781 // Properties
3782 this.message = message instanceof jQuery ? message : String( message );
3783 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3784 this.warning = !!config.warning;
3785 };
3786
3787 /* Setup */
3788
3789 OO.initClass( OO.ui.Error );
3790
3791 /* Methods */
3792
3793 /**
3794 * Check if the error is recoverable.
3795 *
3796 * If the error is recoverable, users are able to try the process again.
3797 *
3798 * @return {boolean} Error is recoverable
3799 */
3800 OO.ui.Error.prototype.isRecoverable = function () {
3801 return this.recoverable;
3802 };
3803
3804 /**
3805 * Check if the error is a warning.
3806 *
3807 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3808 *
3809 * @return {boolean} Error is warning
3810 */
3811 OO.ui.Error.prototype.isWarning = function () {
3812 return this.warning;
3813 };
3814
3815 /**
3816 * Get error message as DOM nodes.
3817 *
3818 * @return {jQuery} Error message in DOM nodes
3819 */
3820 OO.ui.Error.prototype.getMessage = function () {
3821 return this.message instanceof jQuery ?
3822 this.message.clone() :
3823 $( '<div>' ).text( this.message ).contents();
3824 };
3825
3826 /**
3827 * Get the error message text.
3828 *
3829 * @return {string} Error message
3830 */
3831 OO.ui.Error.prototype.getMessageText = function () {
3832 return this.message instanceof jQuery ? this.message.text() : this.message;
3833 };
3834
3835 /**
3836 * Wraps an HTML snippet for use with configuration values which default
3837 * to strings. This bypasses the default html-escaping done to string
3838 * values.
3839 *
3840 * @class
3841 *
3842 * @constructor
3843 * @param {string} [content] HTML content
3844 */
3845 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3846 // Properties
3847 this.content = content;
3848 };
3849
3850 /* Setup */
3851
3852 OO.initClass( OO.ui.HtmlSnippet );
3853
3854 /* Methods */
3855
3856 /**
3857 * Render into HTML.
3858 *
3859 * @return {string} Unchanged HTML snippet.
3860 */
3861 OO.ui.HtmlSnippet.prototype.toString = function () {
3862 return this.content;
3863 };
3864
3865 /**
3866 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3867 * or a function:
3868 *
3869 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3870 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3871 * or stop if the promise is rejected.
3872 * - **function**: the process will execute the function. The process will stop if the function returns
3873 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3874 * will wait for that number of milliseconds before proceeding.
3875 *
3876 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3877 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3878 * its remaining steps will not be performed.
3879 *
3880 * @class
3881 *
3882 * @constructor
3883 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3884 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3885 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3886 * a number or promise.
3887 * @return {Object} Step object, with `callback` and `context` properties
3888 */
3889 OO.ui.Process = function ( step, context ) {
3890 // Properties
3891 this.steps = [];
3892
3893 // Initialization
3894 if ( step !== undefined ) {
3895 this.next( step, context );
3896 }
3897 };
3898
3899 /* Setup */
3900
3901 OO.initClass( OO.ui.Process );
3902
3903 /* Methods */
3904
3905 /**
3906 * Start the process.
3907 *
3908 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3909 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3910 * and any remaining steps are not performed.
3911 */
3912 OO.ui.Process.prototype.execute = function () {
3913 var i, len, promise;
3914
3915 /**
3916 * Continue execution.
3917 *
3918 * @ignore
3919 * @param {Array} step A function and the context it should be called in
3920 * @return {Function} Function that continues the process
3921 */
3922 function proceed( step ) {
3923 return function () {
3924 // Execute step in the correct context
3925 var deferred,
3926 result = step.callback.call( step.context );
3927
3928 if ( result === false ) {
3929 // Use rejected promise for boolean false results
3930 return $.Deferred().reject( [] ).promise();
3931 }
3932 if ( typeof result === 'number' ) {
3933 if ( result < 0 ) {
3934 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3935 }
3936 // Use a delayed promise for numbers, expecting them to be in milliseconds
3937 deferred = $.Deferred();
3938 setTimeout( deferred.resolve, result );
3939 return deferred.promise();
3940 }
3941 if ( result instanceof OO.ui.Error ) {
3942 // Use rejected promise for error
3943 return $.Deferred().reject( [ result ] ).promise();
3944 }
3945 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3946 // Use rejected promise for list of errors
3947 return $.Deferred().reject( result ).promise();
3948 }
3949 // Duck-type the object to see if it can produce a promise
3950 if ( result && $.isFunction( result.promise ) ) {
3951 // Use a promise generated from the result
3952 return result.promise();
3953 }
3954 // Use resolved promise for other results
3955 return $.Deferred().resolve().promise();
3956 };
3957 }
3958
3959 if ( this.steps.length ) {
3960 // Generate a chain reaction of promises
3961 promise = proceed( this.steps[ 0 ] )();
3962 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3963 promise = promise.then( proceed( this.steps[ i ] ) );
3964 }
3965 } else {
3966 promise = $.Deferred().resolve().promise();
3967 }
3968
3969 return promise;
3970 };
3971
3972 /**
3973 * Create a process step.
3974 *
3975 * @private
3976 * @param {number|jQuery.Promise|Function} step
3977 *
3978 * - Number of milliseconds to wait before proceeding
3979 * - Promise that must be resolved before proceeding
3980 * - Function to execute
3981 * - If the function returns a boolean false the process will stop
3982 * - If the function returns a promise, the process will continue to the next
3983 * step when the promise is resolved or stop if the promise is rejected
3984 * - If the function returns a number, the process will wait for that number of
3985 * milliseconds before proceeding
3986 * @param {Object} [context=null] Execution context of the function. The context is
3987 * ignored if the step is a number or promise.
3988 * @return {Object} Step object, with `callback` and `context` properties
3989 */
3990 OO.ui.Process.prototype.createStep = function ( step, context ) {
3991 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3992 return {
3993 callback: function () {
3994 return step;
3995 },
3996 context: null
3997 };
3998 }
3999 if ( $.isFunction( step ) ) {
4000 return {
4001 callback: step,
4002 context: context
4003 };
4004 }
4005 throw new Error( 'Cannot create process step: number, promise or function expected' );
4006 };
4007
4008 /**
4009 * Add step to the beginning of the process.
4010 *
4011 * @inheritdoc #createStep
4012 * @return {OO.ui.Process} this
4013 * @chainable
4014 */
4015 OO.ui.Process.prototype.first = function ( step, context ) {
4016 this.steps.unshift( this.createStep( step, context ) );
4017 return this;
4018 };
4019
4020 /**
4021 * Add step to the end of the process.
4022 *
4023 * @inheritdoc #createStep
4024 * @return {OO.ui.Process} this
4025 * @chainable
4026 */
4027 OO.ui.Process.prototype.next = function ( step, context ) {
4028 this.steps.push( this.createStep( step, context ) );
4029 return this;
4030 };
4031
4032 /**
4033 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4034 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4035 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4036 *
4037 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4038 *
4039 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4040 *
4041 * @class
4042 * @extends OO.Factory
4043 * @constructor
4044 */
4045 OO.ui.ToolFactory = function OoUiToolFactory() {
4046 // Parent constructor
4047 OO.ui.ToolFactory.parent.call( this );
4048 };
4049
4050 /* Setup */
4051
4052 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4053
4054 /* Methods */
4055
4056 /**
4057 * Get tools from the factory
4058 *
4059 * @param {Array} include Included tools
4060 * @param {Array} exclude Excluded tools
4061 * @param {Array} promote Promoted tools
4062 * @param {Array} demote Demoted tools
4063 * @return {string[]} List of tools
4064 */
4065 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4066 var i, len, included, promoted, demoted,
4067 auto = [],
4068 used = {};
4069
4070 // Collect included and not excluded tools
4071 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4072
4073 // Promotion
4074 promoted = this.extract( promote, used );
4075 demoted = this.extract( demote, used );
4076
4077 // Auto
4078 for ( i = 0, len = included.length; i < len; i++ ) {
4079 if ( !used[ included[ i ] ] ) {
4080 auto.push( included[ i ] );
4081 }
4082 }
4083
4084 return promoted.concat( auto ).concat( demoted );
4085 };
4086
4087 /**
4088 * Get a flat list of names from a list of names or groups.
4089 *
4090 * Tools can be specified in the following ways:
4091 *
4092 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4093 * - All tools in a group: `{ group: 'group-name' }`
4094 * - All tools: `'*'`
4095 *
4096 * @private
4097 * @param {Array|string} collection List of tools
4098 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4099 * names will be added as properties
4100 * @return {string[]} List of extracted names
4101 */
4102 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4103 var i, len, item, name, tool,
4104 names = [];
4105
4106 if ( collection === '*' ) {
4107 for ( name in this.registry ) {
4108 tool = this.registry[ name ];
4109 if (
4110 // Only add tools by group name when auto-add is enabled
4111 tool.static.autoAddToCatchall &&
4112 // Exclude already used tools
4113 ( !used || !used[ name ] )
4114 ) {
4115 names.push( name );
4116 if ( used ) {
4117 used[ name ] = true;
4118 }
4119 }
4120 }
4121 } else if ( Array.isArray( collection ) ) {
4122 for ( i = 0, len = collection.length; i < len; i++ ) {
4123 item = collection[ i ];
4124 // Allow plain strings as shorthand for named tools
4125 if ( typeof item === 'string' ) {
4126 item = { name: item };
4127 }
4128 if ( OO.isPlainObject( item ) ) {
4129 if ( item.group ) {
4130 for ( name in this.registry ) {
4131 tool = this.registry[ name ];
4132 if (
4133 // Include tools with matching group
4134 tool.static.group === item.group &&
4135 // Only add tools by group name when auto-add is enabled
4136 tool.static.autoAddToGroup &&
4137 // Exclude already used tools
4138 ( !used || !used[ name ] )
4139 ) {
4140 names.push( name );
4141 if ( used ) {
4142 used[ name ] = true;
4143 }
4144 }
4145 }
4146 // Include tools with matching name and exclude already used tools
4147 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4148 names.push( item.name );
4149 if ( used ) {
4150 used[ item.name ] = true;
4151 }
4152 }
4153 }
4154 }
4155 }
4156 return names;
4157 };
4158
4159 /**
4160 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4161 * specify a symbolic name and be registered with the factory. The following classes are registered by
4162 * default:
4163 *
4164 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4165 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4166 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4167 *
4168 * See {@link OO.ui.Toolbar toolbars} for an example.
4169 *
4170 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4171 *
4172 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4173 * @class
4174 * @extends OO.Factory
4175 * @constructor
4176 */
4177 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4178 var i, l, defaultClasses;
4179 // Parent constructor
4180 OO.Factory.call( this );
4181
4182 defaultClasses = this.constructor.static.getDefaultClasses();
4183
4184 // Register default toolgroups
4185 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4186 this.register( defaultClasses[ i ] );
4187 }
4188 };
4189
4190 /* Setup */
4191
4192 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4193
4194 /* Static Methods */
4195
4196 /**
4197 * Get a default set of classes to be registered on construction.
4198 *
4199 * @return {Function[]} Default classes
4200 */
4201 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4202 return [
4203 OO.ui.BarToolGroup,
4204 OO.ui.ListToolGroup,
4205 OO.ui.MenuToolGroup
4206 ];
4207 };
4208
4209 /**
4210 * Theme logic.
4211 *
4212 * @abstract
4213 * @class
4214 *
4215 * @constructor
4216 * @param {Object} [config] Configuration options
4217 */
4218 OO.ui.Theme = function OoUiTheme( config ) {
4219 // Configuration initialization
4220 config = config || {};
4221 };
4222
4223 /* Setup */
4224
4225 OO.initClass( OO.ui.Theme );
4226
4227 /* Methods */
4228
4229 /**
4230 * Get a list of classes to be applied to a widget.
4231 *
4232 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4233 * otherwise state transitions will not work properly.
4234 *
4235 * @param {OO.ui.Element} element Element for which to get classes
4236 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4237 */
4238 OO.ui.Theme.prototype.getElementClasses = function () {
4239 return { on: [], off: [] };
4240 };
4241
4242 /**
4243 * Update CSS classes provided by the theme.
4244 *
4245 * For elements with theme logic hooks, this should be called any time there's a state change.
4246 *
4247 * @param {OO.ui.Element} element Element for which to update classes
4248 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4249 */
4250 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4251 var $elements = $( [] ),
4252 classes = this.getElementClasses( element );
4253
4254 if ( element.$icon ) {
4255 $elements = $elements.add( element.$icon );
4256 }
4257 if ( element.$indicator ) {
4258 $elements = $elements.add( element.$indicator );
4259 }
4260
4261 $elements
4262 .removeClass( classes.off.join( ' ' ) )
4263 .addClass( classes.on.join( ' ' ) );
4264 };
4265
4266 /**
4267 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4268 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4269 * order in which users will navigate through the focusable elements via the "tab" key.
4270 *
4271 * @example
4272 * // TabIndexedElement is mixed into the ButtonWidget class
4273 * // to provide a tabIndex property.
4274 * var button1 = new OO.ui.ButtonWidget( {
4275 * label: 'fourth',
4276 * tabIndex: 4
4277 * } );
4278 * var button2 = new OO.ui.ButtonWidget( {
4279 * label: 'second',
4280 * tabIndex: 2
4281 * } );
4282 * var button3 = new OO.ui.ButtonWidget( {
4283 * label: 'third',
4284 * tabIndex: 3
4285 * } );
4286 * var button4 = new OO.ui.ButtonWidget( {
4287 * label: 'first',
4288 * tabIndex: 1
4289 * } );
4290 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4291 *
4292 * @abstract
4293 * @class
4294 *
4295 * @constructor
4296 * @param {Object} [config] Configuration options
4297 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4298 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4299 * functionality will be applied to it instead.
4300 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4301 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4302 * to remove the element from the tab-navigation flow.
4303 */
4304 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4305 // Configuration initialization
4306 config = $.extend( { tabIndex: 0 }, config );
4307
4308 // Properties
4309 this.$tabIndexed = null;
4310 this.tabIndex = null;
4311
4312 // Events
4313 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4314
4315 // Initialization
4316 this.setTabIndex( config.tabIndex );
4317 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4318 };
4319
4320 /* Setup */
4321
4322 OO.initClass( OO.ui.mixin.TabIndexedElement );
4323
4324 /* Methods */
4325
4326 /**
4327 * Set the element that should use the tabindex functionality.
4328 *
4329 * This method is used to retarget a tabindex mixin so that its functionality applies
4330 * to the specified element. If an element is currently using the functionality, the mixin’s
4331 * effect on that element is removed before the new element is set up.
4332 *
4333 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4334 * @chainable
4335 */
4336 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4337 var tabIndex = this.tabIndex;
4338 // Remove attributes from old $tabIndexed
4339 this.setTabIndex( null );
4340 // Force update of new $tabIndexed
4341 this.$tabIndexed = $tabIndexed;
4342 this.tabIndex = tabIndex;
4343 return this.updateTabIndex();
4344 };
4345
4346 /**
4347 * Set the value of the tabindex.
4348 *
4349 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4350 * @chainable
4351 */
4352 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4353 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4354
4355 if ( this.tabIndex !== tabIndex ) {
4356 this.tabIndex = tabIndex;
4357 this.updateTabIndex();
4358 }
4359
4360 return this;
4361 };
4362
4363 /**
4364 * Update the `tabindex` attribute, in case of changes to tab index or
4365 * disabled state.
4366 *
4367 * @private
4368 * @chainable
4369 */
4370 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4371 if ( this.$tabIndexed ) {
4372 if ( this.tabIndex !== null ) {
4373 // Do not index over disabled elements
4374 this.$tabIndexed.attr( {
4375 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4376 // Support: ChromeVox and NVDA
4377 // These do not seem to inherit aria-disabled from parent elements
4378 'aria-disabled': this.isDisabled().toString()
4379 } );
4380 } else {
4381 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4382 }
4383 }
4384 return this;
4385 };
4386
4387 /**
4388 * Handle disable events.
4389 *
4390 * @private
4391 * @param {boolean} disabled Element is disabled
4392 */
4393 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4394 this.updateTabIndex();
4395 };
4396
4397 /**
4398 * Get the value of the tabindex.
4399 *
4400 * @return {number|null} Tabindex value
4401 */
4402 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4403 return this.tabIndex;
4404 };
4405
4406 /**
4407 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4408 * interface element that can be configured with access keys for accessibility.
4409 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4410 *
4411 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4412 * @abstract
4413 * @class
4414 *
4415 * @constructor
4416 * @param {Object} [config] Configuration options
4417 * @cfg {jQuery} [$button] The button element created by the class.
4418 * If this configuration is omitted, the button element will use a generated `<a>`.
4419 * @cfg {boolean} [framed=true] Render the button with a frame
4420 */
4421 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4422 // Configuration initialization
4423 config = config || {};
4424
4425 // Properties
4426 this.$button = null;
4427 this.framed = null;
4428 this.active = false;
4429 this.onMouseUpHandler = this.onMouseUp.bind( this );
4430 this.onMouseDownHandler = this.onMouseDown.bind( this );
4431 this.onKeyDownHandler = this.onKeyDown.bind( this );
4432 this.onKeyUpHandler = this.onKeyUp.bind( this );
4433 this.onClickHandler = this.onClick.bind( this );
4434 this.onKeyPressHandler = this.onKeyPress.bind( this );
4435
4436 // Initialization
4437 this.$element.addClass( 'oo-ui-buttonElement' );
4438 this.toggleFramed( config.framed === undefined || config.framed );
4439 this.setButtonElement( config.$button || $( '<a>' ) );
4440 };
4441
4442 /* Setup */
4443
4444 OO.initClass( OO.ui.mixin.ButtonElement );
4445
4446 /* Static Properties */
4447
4448 /**
4449 * Cancel mouse down events.
4450 *
4451 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4452 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4453 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4454 * parent widget.
4455 *
4456 * @static
4457 * @inheritable
4458 * @property {boolean}
4459 */
4460 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4461
4462 /* Events */
4463
4464 /**
4465 * A 'click' event is emitted when the button element is clicked.
4466 *
4467 * @event click
4468 */
4469
4470 /* Methods */
4471
4472 /**
4473 * Set the button element.
4474 *
4475 * This method is used to retarget a button mixin so that its functionality applies to
4476 * the specified button element instead of the one created by the class. If a button element
4477 * is already set, the method will remove the mixin’s effect on that element.
4478 *
4479 * @param {jQuery} $button Element to use as button
4480 */
4481 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4482 if ( this.$button ) {
4483 this.$button
4484 .removeClass( 'oo-ui-buttonElement-button' )
4485 .removeAttr( 'role accesskey' )
4486 .off( {
4487 mousedown: this.onMouseDownHandler,
4488 keydown: this.onKeyDownHandler,
4489 click: this.onClickHandler,
4490 keypress: this.onKeyPressHandler
4491 } );
4492 }
4493
4494 this.$button = $button
4495 .addClass( 'oo-ui-buttonElement-button' )
4496 .attr( { role: 'button' } )
4497 .on( {
4498 mousedown: this.onMouseDownHandler,
4499 keydown: this.onKeyDownHandler,
4500 click: this.onClickHandler,
4501 keypress: this.onKeyPressHandler
4502 } );
4503 };
4504
4505 /**
4506 * Handles mouse down events.
4507 *
4508 * @protected
4509 * @param {jQuery.Event} e Mouse down event
4510 */
4511 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4512 if ( this.isDisabled() || e.which !== 1 ) {
4513 return;
4514 }
4515 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4516 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4517 // reliably remove the pressed class
4518 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4519 // Prevent change of focus unless specifically configured otherwise
4520 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4521 return false;
4522 }
4523 };
4524
4525 /**
4526 * Handles mouse up events.
4527 *
4528 * @protected
4529 * @param {jQuery.Event} e Mouse up event
4530 */
4531 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4532 if ( this.isDisabled() || e.which !== 1 ) {
4533 return;
4534 }
4535 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4536 // Stop listening for mouseup, since we only needed this once
4537 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4538 };
4539
4540 /**
4541 * Handles mouse click events.
4542 *
4543 * @protected
4544 * @param {jQuery.Event} e Mouse click event
4545 * @fires click
4546 */
4547 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4548 if ( !this.isDisabled() && e.which === 1 ) {
4549 if ( this.emit( 'click' ) ) {
4550 return false;
4551 }
4552 }
4553 };
4554
4555 /**
4556 * Handles key down events.
4557 *
4558 * @protected
4559 * @param {jQuery.Event} e Key down event
4560 */
4561 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4562 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4563 return;
4564 }
4565 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4566 // Run the keyup handler no matter where the key is when the button is let go, so we can
4567 // reliably remove the pressed class
4568 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4569 };
4570
4571 /**
4572 * Handles key up events.
4573 *
4574 * @protected
4575 * @param {jQuery.Event} e Key up event
4576 */
4577 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4578 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4579 return;
4580 }
4581 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4582 // Stop listening for keyup, since we only needed this once
4583 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4584 };
4585
4586 /**
4587 * Handles key press events.
4588 *
4589 * @protected
4590 * @param {jQuery.Event} e Key press event
4591 * @fires click
4592 */
4593 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4594 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4595 if ( this.emit( 'click' ) ) {
4596 return false;
4597 }
4598 }
4599 };
4600
4601 /**
4602 * Check if button has a frame.
4603 *
4604 * @return {boolean} Button is framed
4605 */
4606 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4607 return this.framed;
4608 };
4609
4610 /**
4611 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4612 *
4613 * @param {boolean} [framed] Make button framed, omit to toggle
4614 * @chainable
4615 */
4616 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4617 framed = framed === undefined ? !this.framed : !!framed;
4618 if ( framed !== this.framed ) {
4619 this.framed = framed;
4620 this.$element
4621 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4622 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4623 this.updateThemeClasses();
4624 }
4625
4626 return this;
4627 };
4628
4629 /**
4630 * Set the button's active state.
4631 *
4632 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4633 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4634 * for other button types.
4635 *
4636 * @param {boolean} value Make button active
4637 * @chainable
4638 */
4639 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4640 this.active = !!value;
4641 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4642 return this;
4643 };
4644
4645 /**
4646 * Check if the button is active
4647 *
4648 * @return {boolean} The button is active
4649 */
4650 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4651 return this.active;
4652 };
4653
4654 /**
4655 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4656 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4657 * items from the group is done through the interface the class provides.
4658 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4659 *
4660 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4661 *
4662 * @abstract
4663 * @class
4664 *
4665 * @constructor
4666 * @param {Object} [config] Configuration options
4667 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4668 * is omitted, the group element will use a generated `<div>`.
4669 */
4670 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4671 // Configuration initialization
4672 config = config || {};
4673
4674 // Properties
4675 this.$group = null;
4676 this.items = [];
4677 this.aggregateItemEvents = {};
4678
4679 // Initialization
4680 this.setGroupElement( config.$group || $( '<div>' ) );
4681 };
4682
4683 /* Methods */
4684
4685 /**
4686 * Set the group element.
4687 *
4688 * If an element is already set, items will be moved to the new element.
4689 *
4690 * @param {jQuery} $group Element to use as group
4691 */
4692 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4693 var i, len;
4694
4695 this.$group = $group;
4696 for ( i = 0, len = this.items.length; i < len; i++ ) {
4697 this.$group.append( this.items[ i ].$element );
4698 }
4699 };
4700
4701 /**
4702 * Check if a group contains no items.
4703 *
4704 * @return {boolean} Group is empty
4705 */
4706 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4707 return !this.items.length;
4708 };
4709
4710 /**
4711 * Get all items in the group.
4712 *
4713 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4714 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4715 * from a group).
4716 *
4717 * @return {OO.ui.Element[]} An array of items.
4718 */
4719 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4720 return this.items.slice( 0 );
4721 };
4722
4723 /**
4724 * Get an item by its data.
4725 *
4726 * Only the first item with matching data will be returned. To return all matching items,
4727 * use the #getItemsFromData method.
4728 *
4729 * @param {Object} data Item data to search for
4730 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4731 */
4732 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4733 var i, len, item,
4734 hash = OO.getHash( data );
4735
4736 for ( i = 0, len = this.items.length; i < len; i++ ) {
4737 item = this.items[ i ];
4738 if ( hash === OO.getHash( item.getData() ) ) {
4739 return item;
4740 }
4741 }
4742
4743 return null;
4744 };
4745
4746 /**
4747 * Get items by their data.
4748 *
4749 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4750 *
4751 * @param {Object} data Item data to search for
4752 * @return {OO.ui.Element[]} Items with equivalent data
4753 */
4754 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4755 var i, len, item,
4756 hash = OO.getHash( data ),
4757 items = [];
4758
4759 for ( i = 0, len = this.items.length; i < len; i++ ) {
4760 item = this.items[ i ];
4761 if ( hash === OO.getHash( item.getData() ) ) {
4762 items.push( item );
4763 }
4764 }
4765
4766 return items;
4767 };
4768
4769 /**
4770 * Aggregate the events emitted by the group.
4771 *
4772 * When events are aggregated, the group will listen to all contained items for the event,
4773 * and then emit the event under a new name. The new event will contain an additional leading
4774 * parameter containing the item that emitted the original event. Other arguments emitted from
4775 * the original event are passed through.
4776 *
4777 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4778 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4779 * A `null` value will remove aggregated events.
4780
4781 * @throws {Error} An error is thrown if aggregation already exists.
4782 */
4783 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4784 var i, len, item, add, remove, itemEvent, groupEvent;
4785
4786 for ( itemEvent in events ) {
4787 groupEvent = events[ itemEvent ];
4788
4789 // Remove existing aggregated event
4790 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4791 // Don't allow duplicate aggregations
4792 if ( groupEvent ) {
4793 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4794 }
4795 // Remove event aggregation from existing items
4796 for ( i = 0, len = this.items.length; i < len; i++ ) {
4797 item = this.items[ i ];
4798 if ( item.connect && item.disconnect ) {
4799 remove = {};
4800 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4801 item.disconnect( this, remove );
4802 }
4803 }
4804 // Prevent future items from aggregating event
4805 delete this.aggregateItemEvents[ itemEvent ];
4806 }
4807
4808 // Add new aggregate event
4809 if ( groupEvent ) {
4810 // Make future items aggregate event
4811 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4812 // Add event aggregation to existing items
4813 for ( i = 0, len = this.items.length; i < len; i++ ) {
4814 item = this.items[ i ];
4815 if ( item.connect && item.disconnect ) {
4816 add = {};
4817 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4818 item.connect( this, add );
4819 }
4820 }
4821 }
4822 }
4823 };
4824
4825 /**
4826 * Add items to the group.
4827 *
4828 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4829 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4830 *
4831 * @param {OO.ui.Element[]} items An array of items to add to the group
4832 * @param {number} [index] Index of the insertion point
4833 * @chainable
4834 */
4835 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4836 var i, len, item, event, events, currentIndex,
4837 itemElements = [];
4838
4839 for ( i = 0, len = items.length; i < len; i++ ) {
4840 item = items[ i ];
4841
4842 // Check if item exists then remove it first, effectively "moving" it
4843 currentIndex = this.items.indexOf( item );
4844 if ( currentIndex >= 0 ) {
4845 this.removeItems( [ item ] );
4846 // Adjust index to compensate for removal
4847 if ( currentIndex < index ) {
4848 index--;
4849 }
4850 }
4851 // Add the item
4852 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4853 events = {};
4854 for ( event in this.aggregateItemEvents ) {
4855 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4856 }
4857 item.connect( this, events );
4858 }
4859 item.setElementGroup( this );
4860 itemElements.push( item.$element.get( 0 ) );
4861 }
4862
4863 if ( index === undefined || index < 0 || index >= this.items.length ) {
4864 this.$group.append( itemElements );
4865 this.items.push.apply( this.items, items );
4866 } else if ( index === 0 ) {
4867 this.$group.prepend( itemElements );
4868 this.items.unshift.apply( this.items, items );
4869 } else {
4870 this.items[ index ].$element.before( itemElements );
4871 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4872 }
4873
4874 return this;
4875 };
4876
4877 /**
4878 * Remove the specified items from a group.
4879 *
4880 * Removed items are detached (not removed) from the DOM so that they may be reused.
4881 * To remove all items from a group, you may wish to use the #clearItems method instead.
4882 *
4883 * @param {OO.ui.Element[]} items An array of items to remove
4884 * @chainable
4885 */
4886 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4887 var i, len, item, index, remove, itemEvent;
4888
4889 // Remove specific items
4890 for ( i = 0, len = items.length; i < len; i++ ) {
4891 item = items[ i ];
4892 index = this.items.indexOf( item );
4893 if ( index !== -1 ) {
4894 if (
4895 item.connect && item.disconnect &&
4896 !$.isEmptyObject( this.aggregateItemEvents )
4897 ) {
4898 remove = {};
4899 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4900 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4901 }
4902 item.disconnect( this, remove );
4903 }
4904 item.setElementGroup( null );
4905 this.items.splice( index, 1 );
4906 item.$element.detach();
4907 }
4908 }
4909
4910 return this;
4911 };
4912
4913 /**
4914 * Clear all items from the group.
4915 *
4916 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4917 * To remove only a subset of items from a group, use the #removeItems method.
4918 *
4919 * @chainable
4920 */
4921 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4922 var i, len, item, remove, itemEvent;
4923
4924 // Remove all items
4925 for ( i = 0, len = this.items.length; i < len; i++ ) {
4926 item = this.items[ i ];
4927 if (
4928 item.connect && item.disconnect &&
4929 !$.isEmptyObject( this.aggregateItemEvents )
4930 ) {
4931 remove = {};
4932 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4933 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4934 }
4935 item.disconnect( this, remove );
4936 }
4937 item.setElementGroup( null );
4938 item.$element.detach();
4939 }
4940
4941 this.items = [];
4942 return this;
4943 };
4944
4945 /**
4946 * DraggableElement is a mixin class used to create elements that can be clicked
4947 * and dragged by a mouse to a new position within a group. This class must be used
4948 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4949 * the draggable elements.
4950 *
4951 * @abstract
4952 * @class
4953 *
4954 * @constructor
4955 */
4956 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4957 // Properties
4958 this.index = null;
4959
4960 // Initialize and events
4961 this.$element
4962 .attr( 'draggable', true )
4963 .addClass( 'oo-ui-draggableElement' )
4964 .on( {
4965 dragstart: this.onDragStart.bind( this ),
4966 dragover: this.onDragOver.bind( this ),
4967 dragend: this.onDragEnd.bind( this ),
4968 drop: this.onDrop.bind( this )
4969 } );
4970 };
4971
4972 OO.initClass( OO.ui.mixin.DraggableElement );
4973
4974 /* Events */
4975
4976 /**
4977 * @event dragstart
4978 *
4979 * A dragstart event is emitted when the user clicks and begins dragging an item.
4980 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4981 */
4982
4983 /**
4984 * @event dragend
4985 * A dragend event is emitted when the user drags an item and releases the mouse,
4986 * thus terminating the drag operation.
4987 */
4988
4989 /**
4990 * @event drop
4991 * A drop event is emitted when the user drags an item and then releases the mouse button
4992 * over a valid target.
4993 */
4994
4995 /* Static Properties */
4996
4997 /**
4998 * @inheritdoc OO.ui.mixin.ButtonElement
4999 */
5000 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5001
5002 /* Methods */
5003
5004 /**
5005 * Respond to dragstart event.
5006 *
5007 * @private
5008 * @param {jQuery.Event} event jQuery event
5009 * @fires dragstart
5010 */
5011 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5012 var dataTransfer = e.originalEvent.dataTransfer;
5013 // Define drop effect
5014 dataTransfer.dropEffect = 'none';
5015 dataTransfer.effectAllowed = 'move';
5016 // Support: Firefox
5017 // We must set up a dataTransfer data property or Firefox seems to
5018 // ignore the fact the element is draggable.
5019 try {
5020 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5021 } catch ( err ) {
5022 // The above is only for Firefox. Move on if it fails.
5023 }
5024 // Add dragging class
5025 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5026 // Emit event
5027 this.emit( 'dragstart', this );
5028 return true;
5029 };
5030
5031 /**
5032 * Respond to dragend event.
5033 *
5034 * @private
5035 * @fires dragend
5036 */
5037 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5038 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5039 this.emit( 'dragend' );
5040 };
5041
5042 /**
5043 * Handle drop event.
5044 *
5045 * @private
5046 * @param {jQuery.Event} event jQuery event
5047 * @fires drop
5048 */
5049 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5050 e.preventDefault();
5051 this.emit( 'drop', e );
5052 };
5053
5054 /**
5055 * In order for drag/drop to work, the dragover event must
5056 * return false and stop propogation.
5057 *
5058 * @private
5059 */
5060 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5061 e.preventDefault();
5062 };
5063
5064 /**
5065 * Set item index.
5066 * Store it in the DOM so we can access from the widget drag event
5067 *
5068 * @private
5069 * @param {number} Item index
5070 */
5071 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5072 if ( this.index !== index ) {
5073 this.index = index;
5074 this.$element.data( 'index', index );
5075 }
5076 };
5077
5078 /**
5079 * Get item index
5080 *
5081 * @private
5082 * @return {number} Item index
5083 */
5084 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5085 return this.index;
5086 };
5087
5088 /**
5089 * DraggableGroupElement is a mixin class used to create a group element to
5090 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5091 * The class is used with OO.ui.mixin.DraggableElement.
5092 *
5093 * @abstract
5094 * @class
5095 * @mixins OO.ui.mixin.GroupElement
5096 *
5097 * @constructor
5098 * @param {Object} [config] Configuration options
5099 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5100 * should match the layout of the items. Items displayed in a single row
5101 * or in several rows should use horizontal orientation. The vertical orientation should only be
5102 * used when the items are displayed in a single column. Defaults to 'vertical'
5103 */
5104 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5105 // Configuration initialization
5106 config = config || {};
5107
5108 // Parent constructor
5109 OO.ui.mixin.GroupElement.call( this, config );
5110
5111 // Properties
5112 this.orientation = config.orientation || 'vertical';
5113 this.dragItem = null;
5114 this.itemDragOver = null;
5115 this.itemKeys = {};
5116 this.sideInsertion = '';
5117
5118 // Events
5119 this.aggregate( {
5120 dragstart: 'itemDragStart',
5121 dragend: 'itemDragEnd',
5122 drop: 'itemDrop'
5123 } );
5124 this.connect( this, {
5125 itemDragStart: 'onItemDragStart',
5126 itemDrop: 'onItemDrop',
5127 itemDragEnd: 'onItemDragEnd'
5128 } );
5129 this.$element.on( {
5130 dragover: this.onDragOver.bind( this ),
5131 dragleave: this.onDragLeave.bind( this )
5132 } );
5133
5134 // Initialize
5135 if ( Array.isArray( config.items ) ) {
5136 this.addItems( config.items );
5137 }
5138 this.$placeholder = $( '<div>' )
5139 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5140 this.$element
5141 .addClass( 'oo-ui-draggableGroupElement' )
5142 .append( this.$status )
5143 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5144 .prepend( this.$placeholder );
5145 };
5146
5147 /* Setup */
5148 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5149
5150 /* Events */
5151
5152 /**
5153 * A 'reorder' event is emitted when the order of items in the group changes.
5154 *
5155 * @event reorder
5156 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5157 * @param {number} [newIndex] New index for the item
5158 */
5159
5160 /* Methods */
5161
5162 /**
5163 * Respond to item drag start event
5164 *
5165 * @private
5166 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5167 */
5168 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5169 var i, len;
5170
5171 // Map the index of each object
5172 for ( i = 0, len = this.items.length; i < len; i++ ) {
5173 this.items[ i ].setIndex( i );
5174 }
5175
5176 if ( this.orientation === 'horizontal' ) {
5177 // Set the height of the indicator
5178 this.$placeholder.css( {
5179 height: item.$element.outerHeight(),
5180 width: 2
5181 } );
5182 } else {
5183 // Set the width of the indicator
5184 this.$placeholder.css( {
5185 height: 2,
5186 width: item.$element.outerWidth()
5187 } );
5188 }
5189 this.setDragItem( item );
5190 };
5191
5192 /**
5193 * Respond to item drag end event
5194 *
5195 * @private
5196 */
5197 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5198 this.unsetDragItem();
5199 return false;
5200 };
5201
5202 /**
5203 * Handle drop event and switch the order of the items accordingly
5204 *
5205 * @private
5206 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5207 * @fires reorder
5208 */
5209 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5210 var toIndex = item.getIndex();
5211 // Check if the dropped item is from the current group
5212 // TODO: Figure out a way to configure a list of legally droppable
5213 // elements even if they are not yet in the list
5214 if ( this.getDragItem() ) {
5215 // If the insertion point is 'after', the insertion index
5216 // is shifted to the right (or to the left in RTL, hence 'after')
5217 if ( this.sideInsertion === 'after' ) {
5218 toIndex++;
5219 }
5220 // Emit change event
5221 this.emit( 'reorder', this.getDragItem(), toIndex );
5222 }
5223 this.unsetDragItem();
5224 // Return false to prevent propogation
5225 return false;
5226 };
5227
5228 /**
5229 * Handle dragleave event.
5230 *
5231 * @private
5232 */
5233 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5234 // This means the item was dragged outside the widget
5235 this.$placeholder
5236 .css( 'left', 0 )
5237 .addClass( 'oo-ui-element-hidden' );
5238 };
5239
5240 /**
5241 * Respond to dragover event
5242 *
5243 * @private
5244 * @param {jQuery.Event} event Event details
5245 */
5246 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5247 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5248 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5249 clientX = e.originalEvent.clientX,
5250 clientY = e.originalEvent.clientY;
5251
5252 // Get the OptionWidget item we are dragging over
5253 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5254 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5255 if ( $optionWidget[ 0 ] ) {
5256 itemOffset = $optionWidget.offset();
5257 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5258 itemPosition = $optionWidget.position();
5259 itemIndex = $optionWidget.data( 'index' );
5260 }
5261
5262 if (
5263 itemOffset &&
5264 this.isDragging() &&
5265 itemIndex !== this.getDragItem().getIndex()
5266 ) {
5267 if ( this.orientation === 'horizontal' ) {
5268 // Calculate where the mouse is relative to the item width
5269 itemSize = itemBoundingRect.width;
5270 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5271 dragPosition = clientX;
5272 // Which side of the item we hover over will dictate
5273 // where the placeholder will appear, on the left or
5274 // on the right
5275 cssOutput = {
5276 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5277 top: itemPosition.top
5278 };
5279 } else {
5280 // Calculate where the mouse is relative to the item height
5281 itemSize = itemBoundingRect.height;
5282 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5283 dragPosition = clientY;
5284 // Which side of the item we hover over will dictate
5285 // where the placeholder will appear, on the top or
5286 // on the bottom
5287 cssOutput = {
5288 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5289 left: itemPosition.left
5290 };
5291 }
5292 // Store whether we are before or after an item to rearrange
5293 // For horizontal layout, we need to account for RTL, as this is flipped
5294 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5295 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5296 } else {
5297 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5298 }
5299 // Add drop indicator between objects
5300 this.$placeholder
5301 .css( cssOutput )
5302 .removeClass( 'oo-ui-element-hidden' );
5303 } else {
5304 // This means the item was dragged outside the widget
5305 this.$placeholder
5306 .css( 'left', 0 )
5307 .addClass( 'oo-ui-element-hidden' );
5308 }
5309 // Prevent default
5310 e.preventDefault();
5311 };
5312
5313 /**
5314 * Set a dragged item
5315 *
5316 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5317 */
5318 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5319 this.dragItem = item;
5320 };
5321
5322 /**
5323 * Unset the current dragged item
5324 */
5325 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5326 this.dragItem = null;
5327 this.itemDragOver = null;
5328 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5329 this.sideInsertion = '';
5330 };
5331
5332 /**
5333 * Get the item that is currently being dragged.
5334 *
5335 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5336 */
5337 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5338 return this.dragItem;
5339 };
5340
5341 /**
5342 * Check if an item in the group is currently being dragged.
5343 *
5344 * @return {Boolean} Item is being dragged
5345 */
5346 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5347 return this.getDragItem() !== null;
5348 };
5349
5350 /**
5351 * IconElement is often mixed into other classes to generate an icon.
5352 * Icons are graphics, about the size of normal text. They are used to aid the user
5353 * in locating a control or to convey information in a space-efficient way. See the
5354 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5355 * included in the library.
5356 *
5357 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5358 *
5359 * @abstract
5360 * @class
5361 *
5362 * @constructor
5363 * @param {Object} [config] Configuration options
5364 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5365 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5366 * the icon element be set to an existing icon instead of the one generated by this class, set a
5367 * value using a jQuery selection. For example:
5368 *
5369 * // Use a <div> tag instead of a <span>
5370 * $icon: $("<div>")
5371 * // Use an existing icon element instead of the one generated by the class
5372 * $icon: this.$element
5373 * // Use an icon element from a child widget
5374 * $icon: this.childwidget.$element
5375 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5376 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5377 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5378 * by the user's language.
5379 *
5380 * Example of an i18n map:
5381 *
5382 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5383 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5384 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5385 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5386 * text. The icon title is displayed when users move the mouse over the icon.
5387 */
5388 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5389 // Configuration initialization
5390 config = config || {};
5391
5392 // Properties
5393 this.$icon = null;
5394 this.icon = null;
5395 this.iconTitle = null;
5396
5397 // Initialization
5398 this.setIcon( config.icon || this.constructor.static.icon );
5399 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5400 this.setIconElement( config.$icon || $( '<span>' ) );
5401 };
5402
5403 /* Setup */
5404
5405 OO.initClass( OO.ui.mixin.IconElement );
5406
5407 /* Static Properties */
5408
5409 /**
5410 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5411 * for i18n purposes and contains a `default` icon name and additional names keyed by
5412 * language code. The `default` name is used when no icon is keyed by the user's language.
5413 *
5414 * Example of an i18n map:
5415 *
5416 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5417 *
5418 * Note: the static property will be overridden if the #icon configuration is used.
5419 *
5420 * @static
5421 * @inheritable
5422 * @property {Object|string}
5423 */
5424 OO.ui.mixin.IconElement.static.icon = null;
5425
5426 /**
5427 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5428 * function that returns title text, or `null` for no title.
5429 *
5430 * The static property will be overridden if the #iconTitle configuration is used.
5431 *
5432 * @static
5433 * @inheritable
5434 * @property {string|Function|null}
5435 */
5436 OO.ui.mixin.IconElement.static.iconTitle = null;
5437
5438 /* Methods */
5439
5440 /**
5441 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5442 * applies to the specified icon element instead of the one created by the class. If an icon
5443 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5444 * and mixin methods will no longer affect the element.
5445 *
5446 * @param {jQuery} $icon Element to use as icon
5447 */
5448 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5449 if ( this.$icon ) {
5450 this.$icon
5451 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5452 .removeAttr( 'title' );
5453 }
5454
5455 this.$icon = $icon
5456 .addClass( 'oo-ui-iconElement-icon' )
5457 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5458 if ( this.iconTitle !== null ) {
5459 this.$icon.attr( 'title', this.iconTitle );
5460 }
5461
5462 this.updateThemeClasses();
5463 };
5464
5465 /**
5466 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5467 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5468 * for an example.
5469 *
5470 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5471 * by language code, or `null` to remove the icon.
5472 * @chainable
5473 */
5474 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5475 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5476 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5477
5478 if ( this.icon !== icon ) {
5479 if ( this.$icon ) {
5480 if ( this.icon !== null ) {
5481 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5482 }
5483 if ( icon !== null ) {
5484 this.$icon.addClass( 'oo-ui-icon-' + icon );
5485 }
5486 }
5487 this.icon = icon;
5488 }
5489
5490 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5491 this.updateThemeClasses();
5492
5493 return this;
5494 };
5495
5496 /**
5497 * Set the icon title. Use `null` to remove the title.
5498 *
5499 * @param {string|Function|null} iconTitle A text string used as the icon title,
5500 * a function that returns title text, or `null` for no title.
5501 * @chainable
5502 */
5503 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5504 iconTitle = typeof iconTitle === 'function' ||
5505 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5506 OO.ui.resolveMsg( iconTitle ) : null;
5507
5508 if ( this.iconTitle !== iconTitle ) {
5509 this.iconTitle = iconTitle;
5510 if ( this.$icon ) {
5511 if ( this.iconTitle !== null ) {
5512 this.$icon.attr( 'title', iconTitle );
5513 } else {
5514 this.$icon.removeAttr( 'title' );
5515 }
5516 }
5517 }
5518
5519 return this;
5520 };
5521
5522 /**
5523 * Get the symbolic name of the icon.
5524 *
5525 * @return {string} Icon name
5526 */
5527 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5528 return this.icon;
5529 };
5530
5531 /**
5532 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5533 *
5534 * @return {string} Icon title text
5535 */
5536 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5537 return this.iconTitle;
5538 };
5539
5540 /**
5541 * IndicatorElement is often mixed into other classes to generate an indicator.
5542 * Indicators are small graphics that are generally used in two ways:
5543 *
5544 * - To draw attention to the status of an item. For example, an indicator might be
5545 * used to show that an item in a list has errors that need to be resolved.
5546 * - To clarify the function of a control that acts in an exceptional way (a button
5547 * that opens a menu instead of performing an action directly, for example).
5548 *
5549 * For a list of indicators included in the library, please see the
5550 * [OOjs UI documentation on MediaWiki] [1].
5551 *
5552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5553 *
5554 * @abstract
5555 * @class
5556 *
5557 * @constructor
5558 * @param {Object} [config] Configuration options
5559 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5560 * configuration is omitted, the indicator element will use a generated `<span>`.
5561 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5562 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5563 * in the library.
5564 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5565 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5566 * or a function that returns title text. The indicator title is displayed when users move
5567 * the mouse over the indicator.
5568 */
5569 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5570 // Configuration initialization
5571 config = config || {};
5572
5573 // Properties
5574 this.$indicator = null;
5575 this.indicator = null;
5576 this.indicatorTitle = null;
5577
5578 // Initialization
5579 this.setIndicator( config.indicator || this.constructor.static.indicator );
5580 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5581 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5582 };
5583
5584 /* Setup */
5585
5586 OO.initClass( OO.ui.mixin.IndicatorElement );
5587
5588 /* Static Properties */
5589
5590 /**
5591 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5592 * The static property will be overridden if the #indicator configuration is used.
5593 *
5594 * @static
5595 * @inheritable
5596 * @property {string|null}
5597 */
5598 OO.ui.mixin.IndicatorElement.static.indicator = null;
5599
5600 /**
5601 * A text string used as the indicator title, a function that returns title text, or `null`
5602 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5603 *
5604 * @static
5605 * @inheritable
5606 * @property {string|Function|null}
5607 */
5608 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5609
5610 /* Methods */
5611
5612 /**
5613 * Set the indicator element.
5614 *
5615 * If an element is already set, it will be cleaned up before setting up the new element.
5616 *
5617 * @param {jQuery} $indicator Element to use as indicator
5618 */
5619 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5620 if ( this.$indicator ) {
5621 this.$indicator
5622 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5623 .removeAttr( 'title' );
5624 }
5625
5626 this.$indicator = $indicator
5627 .addClass( 'oo-ui-indicatorElement-indicator' )
5628 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5629 if ( this.indicatorTitle !== null ) {
5630 this.$indicator.attr( 'title', this.indicatorTitle );
5631 }
5632
5633 this.updateThemeClasses();
5634 };
5635
5636 /**
5637 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5638 *
5639 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5640 * @chainable
5641 */
5642 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5643 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5644
5645 if ( this.indicator !== indicator ) {
5646 if ( this.$indicator ) {
5647 if ( this.indicator !== null ) {
5648 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5649 }
5650 if ( indicator !== null ) {
5651 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5652 }
5653 }
5654 this.indicator = indicator;
5655 }
5656
5657 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5658 this.updateThemeClasses();
5659
5660 return this;
5661 };
5662
5663 /**
5664 * Set the indicator title.
5665 *
5666 * The title is displayed when a user moves the mouse over the indicator.
5667 *
5668 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5669 * `null` for no indicator title
5670 * @chainable
5671 */
5672 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5673 indicatorTitle = typeof indicatorTitle === 'function' ||
5674 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5675 OO.ui.resolveMsg( indicatorTitle ) : null;
5676
5677 if ( this.indicatorTitle !== indicatorTitle ) {
5678 this.indicatorTitle = indicatorTitle;
5679 if ( this.$indicator ) {
5680 if ( this.indicatorTitle !== null ) {
5681 this.$indicator.attr( 'title', indicatorTitle );
5682 } else {
5683 this.$indicator.removeAttr( 'title' );
5684 }
5685 }
5686 }
5687
5688 return this;
5689 };
5690
5691 /**
5692 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5693 *
5694 * @return {string} Symbolic name of indicator
5695 */
5696 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5697 return this.indicator;
5698 };
5699
5700 /**
5701 * Get the indicator title.
5702 *
5703 * The title is displayed when a user moves the mouse over the indicator.
5704 *
5705 * @return {string} Indicator title text
5706 */
5707 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5708 return this.indicatorTitle;
5709 };
5710
5711 /**
5712 * LabelElement is often mixed into other classes to generate a label, which
5713 * helps identify the function of an interface element.
5714 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5715 *
5716 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5717 *
5718 * @abstract
5719 * @class
5720 *
5721 * @constructor
5722 * @param {Object} [config] Configuration options
5723 * @cfg {jQuery} [$label] The label element created by the class. If this
5724 * configuration is omitted, the label element will use a generated `<span>`.
5725 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5726 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5727 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5728 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5729 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5730 * The label will be truncated to fit if necessary.
5731 */
5732 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5733 // Configuration initialization
5734 config = config || {};
5735
5736 // Properties
5737 this.$label = null;
5738 this.label = null;
5739 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5740
5741 // Initialization
5742 this.setLabel( config.label || this.constructor.static.label );
5743 this.setLabelElement( config.$label || $( '<span>' ) );
5744 };
5745
5746 /* Setup */
5747
5748 OO.initClass( OO.ui.mixin.LabelElement );
5749
5750 /* Events */
5751
5752 /**
5753 * @event labelChange
5754 * @param {string} value
5755 */
5756
5757 /* Static Properties */
5758
5759 /**
5760 * The label text. The label can be specified as a plaintext string, a function that will
5761 * produce a string in the future, or `null` for no label. The static value will
5762 * be overridden if a label is specified with the #label config option.
5763 *
5764 * @static
5765 * @inheritable
5766 * @property {string|Function|null}
5767 */
5768 OO.ui.mixin.LabelElement.static.label = null;
5769
5770 /* Methods */
5771
5772 /**
5773 * Set the label element.
5774 *
5775 * If an element is already set, it will be cleaned up before setting up the new element.
5776 *
5777 * @param {jQuery} $label Element to use as label
5778 */
5779 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5780 if ( this.$label ) {
5781 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5782 }
5783
5784 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5785 this.setLabelContent( this.label );
5786 };
5787
5788 /**
5789 * Set the label.
5790 *
5791 * An empty string will result in the label being hidden. A string containing only whitespace will
5792 * be converted to a single `&nbsp;`.
5793 *
5794 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5795 * text; or null for no label
5796 * @chainable
5797 */
5798 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5799 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5800 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5801
5802 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5803
5804 if ( this.label !== label ) {
5805 if ( this.$label ) {
5806 this.setLabelContent( label );
5807 }
5808 this.label = label;
5809 this.emit( 'labelChange' );
5810 }
5811
5812 return this;
5813 };
5814
5815 /**
5816 * Get the label.
5817 *
5818 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5819 * text; or null for no label
5820 */
5821 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5822 return this.label;
5823 };
5824
5825 /**
5826 * Fit the label.
5827 *
5828 * @chainable
5829 */
5830 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5831 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5832 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5833 }
5834
5835 return this;
5836 };
5837
5838 /**
5839 * Set the content of the label.
5840 *
5841 * Do not call this method until after the label element has been set by #setLabelElement.
5842 *
5843 * @private
5844 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5845 * text; or null for no label
5846 */
5847 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5848 if ( typeof label === 'string' ) {
5849 if ( label.match( /^\s*$/ ) ) {
5850 // Convert whitespace only string to a single non-breaking space
5851 this.$label.html( '&nbsp;' );
5852 } else {
5853 this.$label.text( label );
5854 }
5855 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5856 this.$label.html( label.toString() );
5857 } else if ( label instanceof jQuery ) {
5858 this.$label.empty().append( label );
5859 } else {
5860 this.$label.empty();
5861 }
5862 };
5863
5864 /**
5865 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5866 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5867 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5868 * from the lookup menu, that value becomes the value of the input field.
5869 *
5870 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5871 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5872 * re-enable lookups.
5873 *
5874 * See the [OOjs UI demos][1] for an example.
5875 *
5876 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5877 *
5878 * @class
5879 * @abstract
5880 *
5881 * @constructor
5882 * @param {Object} [config] Configuration options
5883 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5884 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5885 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5886 * By default, the lookup menu is not generated and displayed until the user begins to type.
5887 */
5888 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5889 // Configuration initialization
5890 config = config || {};
5891
5892 // Properties
5893 this.$overlay = config.$overlay || this.$element;
5894 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5895 widget: this,
5896 input: this,
5897 $container: config.$container || this.$element
5898 } );
5899
5900 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5901
5902 this.lookupCache = {};
5903 this.lookupQuery = null;
5904 this.lookupRequest = null;
5905 this.lookupsDisabled = false;
5906 this.lookupInputFocused = false;
5907
5908 // Events
5909 this.$input.on( {
5910 focus: this.onLookupInputFocus.bind( this ),
5911 blur: this.onLookupInputBlur.bind( this ),
5912 mousedown: this.onLookupInputMouseDown.bind( this )
5913 } );
5914 this.connect( this, { change: 'onLookupInputChange' } );
5915 this.lookupMenu.connect( this, {
5916 toggle: 'onLookupMenuToggle',
5917 choose: 'onLookupMenuItemChoose'
5918 } );
5919
5920 // Initialization
5921 this.$element.addClass( 'oo-ui-lookupElement' );
5922 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5923 this.$overlay.append( this.lookupMenu.$element );
5924 };
5925
5926 /* Methods */
5927
5928 /**
5929 * Handle input focus event.
5930 *
5931 * @protected
5932 * @param {jQuery.Event} e Input focus event
5933 */
5934 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5935 this.lookupInputFocused = true;
5936 this.populateLookupMenu();
5937 };
5938
5939 /**
5940 * Handle input blur event.
5941 *
5942 * @protected
5943 * @param {jQuery.Event} e Input blur event
5944 */
5945 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5946 this.closeLookupMenu();
5947 this.lookupInputFocused = false;
5948 };
5949
5950 /**
5951 * Handle input mouse down event.
5952 *
5953 * @protected
5954 * @param {jQuery.Event} e Input mouse down event
5955 */
5956 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5957 // Only open the menu if the input was already focused.
5958 // This way we allow the user to open the menu again after closing it with Esc
5959 // by clicking in the input. Opening (and populating) the menu when initially
5960 // clicking into the input is handled by the focus handler.
5961 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5962 this.populateLookupMenu();
5963 }
5964 };
5965
5966 /**
5967 * Handle input change event.
5968 *
5969 * @protected
5970 * @param {string} value New input value
5971 */
5972 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5973 if ( this.lookupInputFocused ) {
5974 this.populateLookupMenu();
5975 }
5976 };
5977
5978 /**
5979 * Handle the lookup menu being shown/hidden.
5980 *
5981 * @protected
5982 * @param {boolean} visible Whether the lookup menu is now visible.
5983 */
5984 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5985 if ( !visible ) {
5986 // When the menu is hidden, abort any active request and clear the menu.
5987 // This has to be done here in addition to closeLookupMenu(), because
5988 // MenuSelectWidget will close itself when the user presses Esc.
5989 this.abortLookupRequest();
5990 this.lookupMenu.clearItems();
5991 }
5992 };
5993
5994 /**
5995 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5996 *
5997 * @protected
5998 * @param {OO.ui.MenuOptionWidget} item Selected item
5999 */
6000 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6001 this.setValue( item.getData() );
6002 };
6003
6004 /**
6005 * Get lookup menu.
6006 *
6007 * @private
6008 * @return {OO.ui.FloatingMenuSelectWidget}
6009 */
6010 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6011 return this.lookupMenu;
6012 };
6013
6014 /**
6015 * Disable or re-enable lookups.
6016 *
6017 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6018 *
6019 * @param {boolean} disabled Disable lookups
6020 */
6021 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6022 this.lookupsDisabled = !!disabled;
6023 };
6024
6025 /**
6026 * Open the menu. If there are no entries in the menu, this does nothing.
6027 *
6028 * @private
6029 * @chainable
6030 */
6031 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6032 if ( !this.lookupMenu.isEmpty() ) {
6033 this.lookupMenu.toggle( true );
6034 }
6035 return this;
6036 };
6037
6038 /**
6039 * Close the menu, empty it, and abort any pending request.
6040 *
6041 * @private
6042 * @chainable
6043 */
6044 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6045 this.lookupMenu.toggle( false );
6046 this.abortLookupRequest();
6047 this.lookupMenu.clearItems();
6048 return this;
6049 };
6050
6051 /**
6052 * Request menu items based on the input's current value, and when they arrive,
6053 * populate the menu with these items and show the menu.
6054 *
6055 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6056 *
6057 * @private
6058 * @chainable
6059 */
6060 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6061 var widget = this,
6062 value = this.getValue();
6063
6064 if ( this.lookupsDisabled || this.isReadOnly() ) {
6065 return;
6066 }
6067
6068 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6069 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6070 this.closeLookupMenu();
6071 // Skip population if there is already a request pending for the current value
6072 } else if ( value !== this.lookupQuery ) {
6073 this.getLookupMenuItems()
6074 .done( function ( items ) {
6075 widget.lookupMenu.clearItems();
6076 if ( items.length ) {
6077 widget.lookupMenu
6078 .addItems( items )
6079 .toggle( true );
6080 widget.initializeLookupMenuSelection();
6081 } else {
6082 widget.lookupMenu.toggle( false );
6083 }
6084 } )
6085 .fail( function () {
6086 widget.lookupMenu.clearItems();
6087 } );
6088 }
6089
6090 return this;
6091 };
6092
6093 /**
6094 * Highlight the first selectable item in the menu.
6095 *
6096 * @private
6097 * @chainable
6098 */
6099 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6100 if ( !this.lookupMenu.getSelectedItem() ) {
6101 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6102 }
6103 };
6104
6105 /**
6106 * Get lookup menu items for the current query.
6107 *
6108 * @private
6109 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6110 * the done event. If the request was aborted to make way for a subsequent request, this promise
6111 * will not be rejected: it will remain pending forever.
6112 */
6113 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6114 var widget = this,
6115 value = this.getValue(),
6116 deferred = $.Deferred(),
6117 ourRequest;
6118
6119 this.abortLookupRequest();
6120 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6121 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6122 } else {
6123 this.pushPending();
6124 this.lookupQuery = value;
6125 ourRequest = this.lookupRequest = this.getLookupRequest();
6126 ourRequest
6127 .always( function () {
6128 // We need to pop pending even if this is an old request, otherwise
6129 // the widget will remain pending forever.
6130 // TODO: this assumes that an aborted request will fail or succeed soon after
6131 // being aborted, or at least eventually. It would be nice if we could popPending()
6132 // at abort time, but only if we knew that we hadn't already called popPending()
6133 // for that request.
6134 widget.popPending();
6135 } )
6136 .done( function ( response ) {
6137 // If this is an old request (and aborting it somehow caused it to still succeed),
6138 // ignore its success completely
6139 if ( ourRequest === widget.lookupRequest ) {
6140 widget.lookupQuery = null;
6141 widget.lookupRequest = null;
6142 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6143 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6144 }
6145 } )
6146 .fail( function () {
6147 // If this is an old request (or a request failing because it's being aborted),
6148 // ignore its failure completely
6149 if ( ourRequest === widget.lookupRequest ) {
6150 widget.lookupQuery = null;
6151 widget.lookupRequest = null;
6152 deferred.reject();
6153 }
6154 } );
6155 }
6156 return deferred.promise();
6157 };
6158
6159 /**
6160 * Abort the currently pending lookup request, if any.
6161 *
6162 * @private
6163 */
6164 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6165 var oldRequest = this.lookupRequest;
6166 if ( oldRequest ) {
6167 // First unset this.lookupRequest to the fail handler will notice
6168 // that the request is no longer current
6169 this.lookupRequest = null;
6170 this.lookupQuery = null;
6171 oldRequest.abort();
6172 }
6173 };
6174
6175 /**
6176 * Get a new request object of the current lookup query value.
6177 *
6178 * @protected
6179 * @abstract
6180 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6181 */
6182 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6183 // Stub, implemented in subclass
6184 return null;
6185 };
6186
6187 /**
6188 * Pre-process data returned by the request from #getLookupRequest.
6189 *
6190 * The return value of this function will be cached, and any further queries for the given value
6191 * will use the cache rather than doing API requests.
6192 *
6193 * @protected
6194 * @abstract
6195 * @param {Mixed} response Response from server
6196 * @return {Mixed} Cached result data
6197 */
6198 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6199 // Stub, implemented in subclass
6200 return [];
6201 };
6202
6203 /**
6204 * Get a list of menu option widgets from the (possibly cached) data returned by
6205 * #getLookupCacheDataFromResponse.
6206 *
6207 * @protected
6208 * @abstract
6209 * @param {Mixed} data Cached result data, usually an array
6210 * @return {OO.ui.MenuOptionWidget[]} Menu items
6211 */
6212 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6213 // Stub, implemented in subclass
6214 return [];
6215 };
6216
6217 /**
6218 * Set the read-only state of the widget.
6219 *
6220 * This will also disable/enable the lookups functionality.
6221 *
6222 * @param {boolean} readOnly Make input read-only
6223 * @chainable
6224 */
6225 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6226 // Parent method
6227 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6228 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6229
6230 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6231 if ( this.isReadOnly() && this.lookupMenu ) {
6232 this.closeLookupMenu();
6233 }
6234
6235 return this;
6236 };
6237
6238 /**
6239 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6240 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6241 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6242 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6243 *
6244 * @abstract
6245 * @class
6246 *
6247 * @constructor
6248 * @param {Object} [config] Configuration options
6249 * @cfg {Object} [popup] Configuration to pass to popup
6250 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6251 */
6252 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6253 // Configuration initialization
6254 config = config || {};
6255
6256 // Properties
6257 this.popup = new OO.ui.PopupWidget( $.extend(
6258 { autoClose: true },
6259 config.popup,
6260 { $autoCloseIgnore: this.$element }
6261 ) );
6262 };
6263
6264 /* Methods */
6265
6266 /**
6267 * Get popup.
6268 *
6269 * @return {OO.ui.PopupWidget} Popup widget
6270 */
6271 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6272 return this.popup;
6273 };
6274
6275 /**
6276 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6277 * additional functionality to an element created by another class. The class provides
6278 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6279 * which are used to customize the look and feel of a widget to better describe its
6280 * importance and functionality.
6281 *
6282 * The library currently contains the following styling flags for general use:
6283 *
6284 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6285 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6286 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6287 *
6288 * The flags affect the appearance of the buttons:
6289 *
6290 * @example
6291 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6292 * var button1 = new OO.ui.ButtonWidget( {
6293 * label: 'Constructive',
6294 * flags: 'constructive'
6295 * } );
6296 * var button2 = new OO.ui.ButtonWidget( {
6297 * label: 'Destructive',
6298 * flags: 'destructive'
6299 * } );
6300 * var button3 = new OO.ui.ButtonWidget( {
6301 * label: 'Progressive',
6302 * flags: 'progressive'
6303 * } );
6304 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6305 *
6306 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6308 *
6309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6310 *
6311 * @abstract
6312 * @class
6313 *
6314 * @constructor
6315 * @param {Object} [config] Configuration options
6316 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6317 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6318 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6319 * @cfg {jQuery} [$flagged] The flagged element. By default,
6320 * the flagged functionality is applied to the element created by the class ($element).
6321 * If a different element is specified, the flagged functionality will be applied to it instead.
6322 */
6323 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6324 // Configuration initialization
6325 config = config || {};
6326
6327 // Properties
6328 this.flags = {};
6329 this.$flagged = null;
6330
6331 // Initialization
6332 this.setFlags( config.flags );
6333 this.setFlaggedElement( config.$flagged || this.$element );
6334 };
6335
6336 /* Events */
6337
6338 /**
6339 * @event flag
6340 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6341 * parameter contains the name of each modified flag and indicates whether it was
6342 * added or removed.
6343 *
6344 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6345 * that the flag was added, `false` that the flag was removed.
6346 */
6347
6348 /* Methods */
6349
6350 /**
6351 * Set the flagged element.
6352 *
6353 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6354 * If an element is already set, the method will remove the mixin’s effect on that element.
6355 *
6356 * @param {jQuery} $flagged Element that should be flagged
6357 */
6358 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6359 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6360 return 'oo-ui-flaggedElement-' + flag;
6361 } ).join( ' ' );
6362
6363 if ( this.$flagged ) {
6364 this.$flagged.removeClass( classNames );
6365 }
6366
6367 this.$flagged = $flagged.addClass( classNames );
6368 };
6369
6370 /**
6371 * Check if the specified flag is set.
6372 *
6373 * @param {string} flag Name of flag
6374 * @return {boolean} The flag is set
6375 */
6376 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6377 // This may be called before the constructor, thus before this.flags is set
6378 return this.flags && ( flag in this.flags );
6379 };
6380
6381 /**
6382 * Get the names of all flags set.
6383 *
6384 * @return {string[]} Flag names
6385 */
6386 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6387 // This may be called before the constructor, thus before this.flags is set
6388 return Object.keys( this.flags || {} );
6389 };
6390
6391 /**
6392 * Clear all flags.
6393 *
6394 * @chainable
6395 * @fires flag
6396 */
6397 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6398 var flag, className,
6399 changes = {},
6400 remove = [],
6401 classPrefix = 'oo-ui-flaggedElement-';
6402
6403 for ( flag in this.flags ) {
6404 className = classPrefix + flag;
6405 changes[ flag ] = false;
6406 delete this.flags[ flag ];
6407 remove.push( className );
6408 }
6409
6410 if ( this.$flagged ) {
6411 this.$flagged.removeClass( remove.join( ' ' ) );
6412 }
6413
6414 this.updateThemeClasses();
6415 this.emit( 'flag', changes );
6416
6417 return this;
6418 };
6419
6420 /**
6421 * Add one or more flags.
6422 *
6423 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6424 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6425 * be added (`true`) or removed (`false`).
6426 * @chainable
6427 * @fires flag
6428 */
6429 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6430 var i, len, flag, className,
6431 changes = {},
6432 add = [],
6433 remove = [],
6434 classPrefix = 'oo-ui-flaggedElement-';
6435
6436 if ( typeof flags === 'string' ) {
6437 className = classPrefix + flags;
6438 // Set
6439 if ( !this.flags[ flags ] ) {
6440 this.flags[ flags ] = true;
6441 add.push( className );
6442 }
6443 } else if ( Array.isArray( flags ) ) {
6444 for ( i = 0, len = flags.length; i < len; i++ ) {
6445 flag = flags[ i ];
6446 className = classPrefix + flag;
6447 // Set
6448 if ( !this.flags[ flag ] ) {
6449 changes[ flag ] = true;
6450 this.flags[ flag ] = true;
6451 add.push( className );
6452 }
6453 }
6454 } else if ( OO.isPlainObject( flags ) ) {
6455 for ( flag in flags ) {
6456 className = classPrefix + flag;
6457 if ( flags[ flag ] ) {
6458 // Set
6459 if ( !this.flags[ flag ] ) {
6460 changes[ flag ] = true;
6461 this.flags[ flag ] = true;
6462 add.push( className );
6463 }
6464 } else {
6465 // Remove
6466 if ( this.flags[ flag ] ) {
6467 changes[ flag ] = false;
6468 delete this.flags[ flag ];
6469 remove.push( className );
6470 }
6471 }
6472 }
6473 }
6474
6475 if ( this.$flagged ) {
6476 this.$flagged
6477 .addClass( add.join( ' ' ) )
6478 .removeClass( remove.join( ' ' ) );
6479 }
6480
6481 this.updateThemeClasses();
6482 this.emit( 'flag', changes );
6483
6484 return this;
6485 };
6486
6487 /**
6488 * TitledElement is mixed into other classes to provide a `title` attribute.
6489 * Titles are rendered by the browser and are made visible when the user moves
6490 * the mouse over the element. Titles are not visible on touch devices.
6491 *
6492 * @example
6493 * // TitledElement provides a 'title' attribute to the
6494 * // ButtonWidget class
6495 * var button = new OO.ui.ButtonWidget( {
6496 * label: 'Button with Title',
6497 * title: 'I am a button'
6498 * } );
6499 * $( 'body' ).append( button.$element );
6500 *
6501 * @abstract
6502 * @class
6503 *
6504 * @constructor
6505 * @param {Object} [config] Configuration options
6506 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6507 * If this config is omitted, the title functionality is applied to $element, the
6508 * element created by the class.
6509 * @cfg {string|Function} [title] The title text or a function that returns text. If
6510 * this config is omitted, the value of the {@link #static-title static title} property is used.
6511 */
6512 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6513 // Configuration initialization
6514 config = config || {};
6515
6516 // Properties
6517 this.$titled = null;
6518 this.title = null;
6519
6520 // Initialization
6521 this.setTitle( config.title || this.constructor.static.title );
6522 this.setTitledElement( config.$titled || this.$element );
6523 };
6524
6525 /* Setup */
6526
6527 OO.initClass( OO.ui.mixin.TitledElement );
6528
6529 /* Static Properties */
6530
6531 /**
6532 * The title text, a function that returns text, or `null` for no title. The value of the static property
6533 * is overridden if the #title config option is used.
6534 *
6535 * @static
6536 * @inheritable
6537 * @property {string|Function|null}
6538 */
6539 OO.ui.mixin.TitledElement.static.title = null;
6540
6541 /* Methods */
6542
6543 /**
6544 * Set the titled element.
6545 *
6546 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6547 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6548 *
6549 * @param {jQuery} $titled Element that should use the 'titled' functionality
6550 */
6551 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6552 if ( this.$titled ) {
6553 this.$titled.removeAttr( 'title' );
6554 }
6555
6556 this.$titled = $titled;
6557 if ( this.title ) {
6558 this.$titled.attr( 'title', this.title );
6559 }
6560 };
6561
6562 /**
6563 * Set title.
6564 *
6565 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6566 * @chainable
6567 */
6568 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6569 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6570
6571 if ( this.title !== title ) {
6572 if ( this.$titled ) {
6573 if ( title !== null ) {
6574 this.$titled.attr( 'title', title );
6575 } else {
6576 this.$titled.removeAttr( 'title' );
6577 }
6578 }
6579 this.title = title;
6580 }
6581
6582 return this;
6583 };
6584
6585 /**
6586 * Get title.
6587 *
6588 * @return {string} Title string
6589 */
6590 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6591 return this.title;
6592 };
6593
6594 /**
6595 * Element that can be automatically clipped to visible boundaries.
6596 *
6597 * Whenever the element's natural height changes, you have to call
6598 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6599 * clipping correctly.
6600 *
6601 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6602 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6603 * then #$clippable will be given a fixed reduced height and/or width and will be made
6604 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6605 * but you can build a static footer by setting #$clippableContainer to an element that contains
6606 * #$clippable and the footer.
6607 *
6608 * @abstract
6609 * @class
6610 *
6611 * @constructor
6612 * @param {Object} [config] Configuration options
6613 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6614 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6615 * omit to use #$clippable
6616 */
6617 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6618 // Configuration initialization
6619 config = config || {};
6620
6621 // Properties
6622 this.$clippable = null;
6623 this.$clippableContainer = null;
6624 this.clipping = false;
6625 this.clippedHorizontally = false;
6626 this.clippedVertically = false;
6627 this.$clippableScrollableContainer = null;
6628 this.$clippableScroller = null;
6629 this.$clippableWindow = null;
6630 this.idealWidth = null;
6631 this.idealHeight = null;
6632 this.onClippableScrollHandler = this.clip.bind( this );
6633 this.onClippableWindowResizeHandler = this.clip.bind( this );
6634
6635 // Initialization
6636 if ( config.$clippableContainer ) {
6637 this.setClippableContainer( config.$clippableContainer );
6638 }
6639 this.setClippableElement( config.$clippable || this.$element );
6640 };
6641
6642 /* Methods */
6643
6644 /**
6645 * Set clippable element.
6646 *
6647 * If an element is already set, it will be cleaned up before setting up the new element.
6648 *
6649 * @param {jQuery} $clippable Element to make clippable
6650 */
6651 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6652 if ( this.$clippable ) {
6653 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6654 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6655 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6656 }
6657
6658 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6659 this.clip();
6660 };
6661
6662 /**
6663 * Set clippable container.
6664 *
6665 * This is the container that will be measured when deciding whether to clip. When clipping,
6666 * #$clippable will be resized in order to keep the clippable container fully visible.
6667 *
6668 * If the clippable container is unset, #$clippable will be used.
6669 *
6670 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6671 */
6672 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6673 this.$clippableContainer = $clippableContainer;
6674 if ( this.$clippable ) {
6675 this.clip();
6676 }
6677 };
6678
6679 /**
6680 * Toggle clipping.
6681 *
6682 * Do not turn clipping on until after the element is attached to the DOM and visible.
6683 *
6684 * @param {boolean} [clipping] Enable clipping, omit to toggle
6685 * @chainable
6686 */
6687 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6688 clipping = clipping === undefined ? !this.clipping : !!clipping;
6689
6690 if ( this.clipping !== clipping ) {
6691 this.clipping = clipping;
6692 if ( clipping ) {
6693 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6694 // If the clippable container is the root, we have to listen to scroll events and check
6695 // jQuery.scrollTop on the window because of browser inconsistencies
6696 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6697 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6698 this.$clippableScrollableContainer;
6699 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6700 this.$clippableWindow = $( this.getElementWindow() )
6701 .on( 'resize', this.onClippableWindowResizeHandler );
6702 // Initial clip after visible
6703 this.clip();
6704 } else {
6705 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6706 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6707
6708 this.$clippableScrollableContainer = null;
6709 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6710 this.$clippableScroller = null;
6711 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6712 this.$clippableWindow = null;
6713 }
6714 }
6715
6716 return this;
6717 };
6718
6719 /**
6720 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6721 *
6722 * @return {boolean} Element will be clipped to the visible area
6723 */
6724 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6725 return this.clipping;
6726 };
6727
6728 /**
6729 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6730 *
6731 * @return {boolean} Part of the element is being clipped
6732 */
6733 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6734 return this.clippedHorizontally || this.clippedVertically;
6735 };
6736
6737 /**
6738 * Check if the right of the element is being clipped by the nearest scrollable container.
6739 *
6740 * @return {boolean} Part of the element is being clipped
6741 */
6742 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6743 return this.clippedHorizontally;
6744 };
6745
6746 /**
6747 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6748 *
6749 * @return {boolean} Part of the element is being clipped
6750 */
6751 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6752 return this.clippedVertically;
6753 };
6754
6755 /**
6756 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6757 *
6758 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6759 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6760 */
6761 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6762 this.idealWidth = width;
6763 this.idealHeight = height;
6764
6765 if ( !this.clipping ) {
6766 // Update dimensions
6767 this.$clippable.css( { width: width, height: height } );
6768 }
6769 // While clipping, idealWidth and idealHeight are not considered
6770 };
6771
6772 /**
6773 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6774 * the element's natural height changes.
6775 *
6776 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6777 * overlapped by, the visible area of the nearest scrollable container.
6778 *
6779 * @chainable
6780 */
6781 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6782 var $container, extraHeight, extraWidth, ccOffset,
6783 $scrollableContainer, scOffset, scHeight, scWidth,
6784 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6785 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6786 naturalWidth, naturalHeight, clipWidth, clipHeight,
6787 buffer = 7; // Chosen by fair dice roll
6788
6789 if ( !this.clipping ) {
6790 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6791 return this;
6792 }
6793
6794 $container = this.$clippableContainer || this.$clippable;
6795 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6796 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6797 ccOffset = $container.offset();
6798 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6799 this.$clippableWindow : this.$clippableScrollableContainer;
6800 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6801 scHeight = $scrollableContainer.innerHeight() - buffer;
6802 scWidth = $scrollableContainer.innerWidth() - buffer;
6803 ccWidth = $container.outerWidth() + buffer;
6804 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6805 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6806 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6807 desiredWidth = ccOffset.left < 0 ?
6808 ccWidth + ccOffset.left :
6809 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6810 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6811 allotedWidth = desiredWidth - extraWidth;
6812 allotedHeight = desiredHeight - extraHeight;
6813 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6814 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6815 clipWidth = allotedWidth < naturalWidth;
6816 clipHeight = allotedHeight < naturalHeight;
6817
6818 if ( clipWidth ) {
6819 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6820 } else {
6821 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6822 }
6823 if ( clipHeight ) {
6824 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6825 } else {
6826 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6827 }
6828
6829 // If we stopped clipping in at least one of the dimensions
6830 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6831 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6832 }
6833
6834 this.clippedHorizontally = clipWidth;
6835 this.clippedVertically = clipHeight;
6836
6837 return this;
6838 };
6839
6840 /**
6841 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6842 * document (for example, in a OO.ui.Window's $overlay).
6843 *
6844 * The elements's position is automatically calculated and maintained when window is resized or the
6845 * page is scrolled. If you reposition the container manually, you have to call #position to make
6846 * sure the element is still placed correctly.
6847 *
6848 * As positioning is only possible when both the element and the container are attached to the DOM
6849 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6850 * the #toggle method to display a floating popup, for example.
6851 *
6852 * @abstract
6853 * @class
6854 *
6855 * @constructor
6856 * @param {Object} [config] Configuration options
6857 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6858 * @cfg {jQuery} [$floatableContainer] Node to position below
6859 */
6860 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6861 // Configuration initialization
6862 config = config || {};
6863
6864 // Properties
6865 this.$floatable = null;
6866 this.$floatableContainer = null;
6867 this.$floatableWindow = null;
6868 this.$floatableClosestScrollable = null;
6869 this.onFloatableScrollHandler = this.position.bind( this );
6870 this.onFloatableWindowResizeHandler = this.position.bind( this );
6871
6872 // Initialization
6873 this.setFloatableContainer( config.$floatableContainer );
6874 this.setFloatableElement( config.$floatable || this.$element );
6875 };
6876
6877 /* Methods */
6878
6879 /**
6880 * Set floatable element.
6881 *
6882 * If an element is already set, it will be cleaned up before setting up the new element.
6883 *
6884 * @param {jQuery} $floatable Element to make floatable
6885 */
6886 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
6887 if ( this.$floatable ) {
6888 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
6889 this.$floatable.css( { left: '', top: '' } );
6890 }
6891
6892 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
6893 this.position();
6894 };
6895
6896 /**
6897 * Set floatable container.
6898 *
6899 * The element will be always positioned under the specified container.
6900 *
6901 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6902 */
6903 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
6904 this.$floatableContainer = $floatableContainer;
6905 if ( this.$floatable ) {
6906 this.position();
6907 }
6908 };
6909
6910 /**
6911 * Toggle positioning.
6912 *
6913 * Do not turn positioning on until after the element is attached to the DOM and visible.
6914 *
6915 * @param {boolean} [positioning] Enable positioning, omit to toggle
6916 * @chainable
6917 */
6918 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
6919 var closestScrollableOfContainer, closestScrollableOfFloatable;
6920
6921 positioning = positioning === undefined ? !this.positioning : !!positioning;
6922
6923 if ( this.positioning !== positioning ) {
6924 this.positioning = positioning;
6925
6926 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
6927 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
6928 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6929 // If the scrollable is the root, we have to listen to scroll events
6930 // on the window because of browser inconsistencies (or do we? someone should verify this)
6931 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
6932 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
6933 }
6934 }
6935
6936 if ( positioning ) {
6937 this.$floatableWindow = $( this.getElementWindow() );
6938 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
6939
6940 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
6941 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
6942 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
6943 }
6944
6945 // Initial position after visible
6946 this.position();
6947 } else {
6948 if ( this.$floatableWindow ) {
6949 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
6950 this.$floatableWindow = null;
6951 }
6952
6953 if ( this.$floatableClosestScrollable ) {
6954 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
6955 this.$floatableClosestScrollable = null;
6956 }
6957
6958 this.$floatable.css( { left: '', top: '' } );
6959 }
6960 }
6961
6962 return this;
6963 };
6964
6965 /**
6966 * Position the floatable below its container.
6967 *
6968 * This should only be done when both of them are attached to the DOM and visible.
6969 *
6970 * @chainable
6971 */
6972 OO.ui.mixin.FloatableElement.prototype.position = function () {
6973 var pos;
6974
6975 if ( !this.positioning ) {
6976 return this;
6977 }
6978
6979 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
6980
6981 // Position under container
6982 pos.top += this.$floatableContainer.height();
6983 this.$floatable.css( pos );
6984
6985 // We updated the position, so re-evaluate the clipping state.
6986 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6987 // will not notice the need to update itself.)
6988 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6989 // it not listen to the right events in the right places?
6990 if ( this.clip ) {
6991 this.clip();
6992 }
6993
6994 return this;
6995 };
6996
6997 /**
6998 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6999 * Accesskeys allow an user to go to a specific element by using
7000 * a shortcut combination of a browser specific keys + the key
7001 * set to the field.
7002 *
7003 * @example
7004 * // AccessKeyedElement provides an 'accesskey' attribute to the
7005 * // ButtonWidget class
7006 * var button = new OO.ui.ButtonWidget( {
7007 * label: 'Button with Accesskey',
7008 * accessKey: 'k'
7009 * } );
7010 * $( 'body' ).append( button.$element );
7011 *
7012 * @abstract
7013 * @class
7014 *
7015 * @constructor
7016 * @param {Object} [config] Configuration options
7017 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7018 * If this config is omitted, the accesskey functionality is applied to $element, the
7019 * element created by the class.
7020 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7021 * this config is omitted, no accesskey will be added.
7022 */
7023 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7024 // Configuration initialization
7025 config = config || {};
7026
7027 // Properties
7028 this.$accessKeyed = null;
7029 this.accessKey = null;
7030
7031 // Initialization
7032 this.setAccessKey( config.accessKey || null );
7033 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7034 };
7035
7036 /* Setup */
7037
7038 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7039
7040 /* Static Properties */
7041
7042 /**
7043 * The access key, a function that returns a key, or `null` for no accesskey.
7044 *
7045 * @static
7046 * @inheritable
7047 * @property {string|Function|null}
7048 */
7049 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7050
7051 /* Methods */
7052
7053 /**
7054 * Set the accesskeyed element.
7055 *
7056 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7057 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7058 *
7059 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7060 */
7061 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7062 if ( this.$accessKeyed ) {
7063 this.$accessKeyed.removeAttr( 'accesskey' );
7064 }
7065
7066 this.$accessKeyed = $accessKeyed;
7067 if ( this.accessKey ) {
7068 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7069 }
7070 };
7071
7072 /**
7073 * Set accesskey.
7074 *
7075 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7076 * @chainable
7077 */
7078 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7079 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7080
7081 if ( this.accessKey !== accessKey ) {
7082 if ( this.$accessKeyed ) {
7083 if ( accessKey !== null ) {
7084 this.$accessKeyed.attr( 'accesskey', accessKey );
7085 } else {
7086 this.$accessKeyed.removeAttr( 'accesskey' );
7087 }
7088 }
7089 this.accessKey = accessKey;
7090 }
7091
7092 return this;
7093 };
7094
7095 /**
7096 * Get accesskey.
7097 *
7098 * @return {string} accessKey string
7099 */
7100 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7101 return this.accessKey;
7102 };
7103
7104 /**
7105 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7106 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7107 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7108 * which creates the tools on demand.
7109 *
7110 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7111 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7112 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7113 *
7114 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7116 *
7117 * @abstract
7118 * @class
7119 * @extends OO.ui.Widget
7120 * @mixins OO.ui.mixin.IconElement
7121 * @mixins OO.ui.mixin.FlaggedElement
7122 * @mixins OO.ui.mixin.TabIndexedElement
7123 *
7124 * @constructor
7125 * @param {OO.ui.ToolGroup} toolGroup
7126 * @param {Object} [config] Configuration options
7127 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7128 * the {@link #static-title static title} property is used.
7129 *
7130 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7131 * 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
7132 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7133 *
7134 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7135 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7136 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7137 */
7138 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7139 // Allow passing positional parameters inside the config object
7140 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7141 config = toolGroup;
7142 toolGroup = config.toolGroup;
7143 }
7144
7145 // Configuration initialization
7146 config = config || {};
7147
7148 // Parent constructor
7149 OO.ui.Tool.parent.call( this, config );
7150
7151 // Properties
7152 this.toolGroup = toolGroup;
7153 this.toolbar = this.toolGroup.getToolbar();
7154 this.active = false;
7155 this.$title = $( '<span>' );
7156 this.$accel = $( '<span>' );
7157 this.$link = $( '<a>' );
7158 this.title = null;
7159
7160 // Mixin constructors
7161 OO.ui.mixin.IconElement.call( this, config );
7162 OO.ui.mixin.FlaggedElement.call( this, config );
7163 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7164
7165 // Events
7166 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7167
7168 // Initialization
7169 this.$title.addClass( 'oo-ui-tool-title' );
7170 this.$accel
7171 .addClass( 'oo-ui-tool-accel' )
7172 .prop( {
7173 // This may need to be changed if the key names are ever localized,
7174 // but for now they are essentially written in English
7175 dir: 'ltr',
7176 lang: 'en'
7177 } );
7178 this.$link
7179 .addClass( 'oo-ui-tool-link' )
7180 .append( this.$icon, this.$title, this.$accel )
7181 .attr( 'role', 'button' );
7182 this.$element
7183 .data( 'oo-ui-tool', this )
7184 .addClass(
7185 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7186 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7187 )
7188 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7189 .append( this.$link );
7190 this.setTitle( config.title || this.constructor.static.title );
7191 };
7192
7193 /* Setup */
7194
7195 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7196 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7197 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7198 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7199
7200 /* Static Properties */
7201
7202 /**
7203 * @static
7204 * @inheritdoc
7205 */
7206 OO.ui.Tool.static.tagName = 'span';
7207
7208 /**
7209 * Symbolic name of tool.
7210 *
7211 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7212 * also be used when adding tools to toolgroups.
7213 *
7214 * @abstract
7215 * @static
7216 * @inheritable
7217 * @property {string}
7218 */
7219 OO.ui.Tool.static.name = '';
7220
7221 /**
7222 * Symbolic name of the group.
7223 *
7224 * The group name is used to associate tools with each other so that they can be selected later by
7225 * a {@link OO.ui.ToolGroup toolgroup}.
7226 *
7227 * @abstract
7228 * @static
7229 * @inheritable
7230 * @property {string}
7231 */
7232 OO.ui.Tool.static.group = '';
7233
7234 /**
7235 * 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.
7236 *
7237 * @abstract
7238 * @static
7239 * @inheritable
7240 * @property {string|Function}
7241 */
7242 OO.ui.Tool.static.title = '';
7243
7244 /**
7245 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7246 * Normally only the icon is displayed, or only the label if no icon is given.
7247 *
7248 * @static
7249 * @inheritable
7250 * @property {boolean}
7251 */
7252 OO.ui.Tool.static.displayBothIconAndLabel = false;
7253
7254 /**
7255 * Add tool to catch-all groups automatically.
7256 *
7257 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7258 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7259 *
7260 * @static
7261 * @inheritable
7262 * @property {boolean}
7263 */
7264 OO.ui.Tool.static.autoAddToCatchall = true;
7265
7266 /**
7267 * Add tool to named groups automatically.
7268 *
7269 * By default, tools that are configured with a static ‘group’ property are added
7270 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7271 * toolgroups include tools by group name).
7272 *
7273 * @static
7274 * @property {boolean}
7275 * @inheritable
7276 */
7277 OO.ui.Tool.static.autoAddToGroup = true;
7278
7279 /**
7280 * Check if this tool is compatible with given data.
7281 *
7282 * This is a stub that can be overriden to provide support for filtering tools based on an
7283 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7284 * must also call this method so that the compatibility check can be performed.
7285 *
7286 * @static
7287 * @inheritable
7288 * @param {Mixed} data Data to check
7289 * @return {boolean} Tool can be used with data
7290 */
7291 OO.ui.Tool.static.isCompatibleWith = function () {
7292 return false;
7293 };
7294
7295 /* Methods */
7296
7297 /**
7298 * Handle the toolbar state being updated.
7299 *
7300 * This is an abstract method that must be overridden in a concrete subclass.
7301 *
7302 * @protected
7303 * @abstract
7304 */
7305 OO.ui.Tool.prototype.onUpdateState = function () {
7306 throw new Error(
7307 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7308 );
7309 };
7310
7311 /**
7312 * Handle the tool being selected.
7313 *
7314 * This is an abstract method that must be overridden in a concrete subclass.
7315 *
7316 * @protected
7317 * @abstract
7318 */
7319 OO.ui.Tool.prototype.onSelect = function () {
7320 throw new Error(
7321 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7322 );
7323 };
7324
7325 /**
7326 * Check if the tool is active.
7327 *
7328 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7329 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7330 *
7331 * @return {boolean} Tool is active
7332 */
7333 OO.ui.Tool.prototype.isActive = function () {
7334 return this.active;
7335 };
7336
7337 /**
7338 * Make the tool appear active or inactive.
7339 *
7340 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7341 * appear pressed or not.
7342 *
7343 * @param {boolean} state Make tool appear active
7344 */
7345 OO.ui.Tool.prototype.setActive = function ( state ) {
7346 this.active = !!state;
7347 if ( this.active ) {
7348 this.$element.addClass( 'oo-ui-tool-active' );
7349 } else {
7350 this.$element.removeClass( 'oo-ui-tool-active' );
7351 }
7352 };
7353
7354 /**
7355 * Set the tool #title.
7356 *
7357 * @param {string|Function} title Title text or a function that returns text
7358 * @chainable
7359 */
7360 OO.ui.Tool.prototype.setTitle = function ( title ) {
7361 this.title = OO.ui.resolveMsg( title );
7362 this.updateTitle();
7363 return this;
7364 };
7365
7366 /**
7367 * Get the tool #title.
7368 *
7369 * @return {string} Title text
7370 */
7371 OO.ui.Tool.prototype.getTitle = function () {
7372 return this.title;
7373 };
7374
7375 /**
7376 * Get the tool's symbolic name.
7377 *
7378 * @return {string} Symbolic name of tool
7379 */
7380 OO.ui.Tool.prototype.getName = function () {
7381 return this.constructor.static.name;
7382 };
7383
7384 /**
7385 * Update the title.
7386 */
7387 OO.ui.Tool.prototype.updateTitle = function () {
7388 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7389 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7390 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7391 tooltipParts = [];
7392
7393 this.$title.text( this.title );
7394 this.$accel.text( accel );
7395
7396 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7397 tooltipParts.push( this.title );
7398 }
7399 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7400 tooltipParts.push( accel );
7401 }
7402 if ( tooltipParts.length ) {
7403 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7404 } else {
7405 this.$link.removeAttr( 'title' );
7406 }
7407 };
7408
7409 /**
7410 * Destroy tool.
7411 *
7412 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7413 * Call this method whenever you are done using a tool.
7414 */
7415 OO.ui.Tool.prototype.destroy = function () {
7416 this.toolbar.disconnect( this );
7417 this.$element.remove();
7418 };
7419
7420 /**
7421 * Toolbars are complex interface components that permit users to easily access a variety
7422 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7423 * part of the toolbar, but not configured as tools.
7424 *
7425 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7426 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7427 * picture’), and an icon.
7428 *
7429 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7430 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7431 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7432 * any order, but each can only appear once in the toolbar.
7433 *
7434 * The following is an example of a basic toolbar.
7435 *
7436 * @example
7437 * // Example of a toolbar
7438 * // Create the toolbar
7439 * var toolFactory = new OO.ui.ToolFactory();
7440 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7441 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7442 *
7443 * // We will be placing status text in this element when tools are used
7444 * var $area = $( '<p>' ).text( 'Toolbar example' );
7445 *
7446 * // Define the tools that we're going to place in our toolbar
7447 *
7448 * // Create a class inheriting from OO.ui.Tool
7449 * function PictureTool() {
7450 * PictureTool.parent.apply( this, arguments );
7451 * }
7452 * OO.inheritClass( PictureTool, OO.ui.Tool );
7453 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7454 * // of 'icon' and 'title' (displayed icon and text).
7455 * PictureTool.static.name = 'picture';
7456 * PictureTool.static.icon = 'picture';
7457 * PictureTool.static.title = 'Insert picture';
7458 * // Defines the action that will happen when this tool is selected (clicked).
7459 * PictureTool.prototype.onSelect = function () {
7460 * $area.text( 'Picture tool clicked!' );
7461 * // Never display this tool as "active" (selected).
7462 * this.setActive( false );
7463 * };
7464 * // Make this tool available in our toolFactory and thus our toolbar
7465 * toolFactory.register( PictureTool );
7466 *
7467 * // Register two more tools, nothing interesting here
7468 * function SettingsTool() {
7469 * SettingsTool.parent.apply( this, arguments );
7470 * }
7471 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7472 * SettingsTool.static.name = 'settings';
7473 * SettingsTool.static.icon = 'settings';
7474 * SettingsTool.static.title = 'Change settings';
7475 * SettingsTool.prototype.onSelect = function () {
7476 * $area.text( 'Settings tool clicked!' );
7477 * this.setActive( false );
7478 * };
7479 * toolFactory.register( SettingsTool );
7480 *
7481 * // Register two more tools, nothing interesting here
7482 * function StuffTool() {
7483 * StuffTool.parent.apply( this, arguments );
7484 * }
7485 * OO.inheritClass( StuffTool, OO.ui.Tool );
7486 * StuffTool.static.name = 'stuff';
7487 * StuffTool.static.icon = 'ellipsis';
7488 * StuffTool.static.title = 'More stuff';
7489 * StuffTool.prototype.onSelect = function () {
7490 * $area.text( 'More stuff tool clicked!' );
7491 * this.setActive( false );
7492 * };
7493 * toolFactory.register( StuffTool );
7494 *
7495 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7496 * // little popup window (a PopupWidget).
7497 * function HelpTool( toolGroup, config ) {
7498 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7499 * padded: true,
7500 * label: 'Help',
7501 * head: true
7502 * } }, config ) );
7503 * this.popup.$body.append( '<p>I am helpful!</p>' );
7504 * }
7505 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7506 * HelpTool.static.name = 'help';
7507 * HelpTool.static.icon = 'help';
7508 * HelpTool.static.title = 'Help';
7509 * toolFactory.register( HelpTool );
7510 *
7511 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7512 * // used once (but not all defined tools must be used).
7513 * toolbar.setup( [
7514 * {
7515 * // 'bar' tool groups display tools' icons only, side-by-side.
7516 * type: 'bar',
7517 * include: [ 'picture', 'help' ]
7518 * },
7519 * {
7520 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7521 * type: 'list',
7522 * indicator: 'down',
7523 * label: 'More',
7524 * include: [ 'settings', 'stuff' ]
7525 * }
7526 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7527 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7528 * // since it's more complicated to use. (See the next example snippet on this page.)
7529 * ] );
7530 *
7531 * // Create some UI around the toolbar and place it in the document
7532 * var frame = new OO.ui.PanelLayout( {
7533 * expanded: false,
7534 * framed: true
7535 * } );
7536 * var contentFrame = new OO.ui.PanelLayout( {
7537 * expanded: false,
7538 * padded: true
7539 * } );
7540 * frame.$element.append(
7541 * toolbar.$element,
7542 * contentFrame.$element.append( $area )
7543 * );
7544 * $( 'body' ).append( frame.$element );
7545 *
7546 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7547 * // document.
7548 * toolbar.initialize();
7549 *
7550 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7551 * 'updateState' event.
7552 *
7553 * @example
7554 * // Create the toolbar
7555 * var toolFactory = new OO.ui.ToolFactory();
7556 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7557 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7558 *
7559 * // We will be placing status text in this element when tools are used
7560 * var $area = $( '<p>' ).text( 'Toolbar example' );
7561 *
7562 * // Define the tools that we're going to place in our toolbar
7563 *
7564 * // Create a class inheriting from OO.ui.Tool
7565 * function PictureTool() {
7566 * PictureTool.parent.apply( this, arguments );
7567 * }
7568 * OO.inheritClass( PictureTool, OO.ui.Tool );
7569 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7570 * // of 'icon' and 'title' (displayed icon and text).
7571 * PictureTool.static.name = 'picture';
7572 * PictureTool.static.icon = 'picture';
7573 * PictureTool.static.title = 'Insert picture';
7574 * // Defines the action that will happen when this tool is selected (clicked).
7575 * PictureTool.prototype.onSelect = function () {
7576 * $area.text( 'Picture tool clicked!' );
7577 * // Never display this tool as "active" (selected).
7578 * this.setActive( false );
7579 * };
7580 * // The toolbar can be synchronized with the state of some external stuff, like a text
7581 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7582 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7583 * PictureTool.prototype.onUpdateState = function () {
7584 * };
7585 * // Make this tool available in our toolFactory and thus our toolbar
7586 * toolFactory.register( PictureTool );
7587 *
7588 * // Register two more tools, nothing interesting here
7589 * function SettingsTool() {
7590 * SettingsTool.parent.apply( this, arguments );
7591 * this.reallyActive = false;
7592 * }
7593 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7594 * SettingsTool.static.name = 'settings';
7595 * SettingsTool.static.icon = 'settings';
7596 * SettingsTool.static.title = 'Change settings';
7597 * SettingsTool.prototype.onSelect = function () {
7598 * $area.text( 'Settings tool clicked!' );
7599 * // Toggle the active state on each click
7600 * this.reallyActive = !this.reallyActive;
7601 * this.setActive( this.reallyActive );
7602 * // To update the menu label
7603 * this.toolbar.emit( 'updateState' );
7604 * };
7605 * SettingsTool.prototype.onUpdateState = function () {
7606 * };
7607 * toolFactory.register( SettingsTool );
7608 *
7609 * // Register two more tools, nothing interesting here
7610 * function StuffTool() {
7611 * StuffTool.parent.apply( this, arguments );
7612 * this.reallyActive = false;
7613 * }
7614 * OO.inheritClass( StuffTool, OO.ui.Tool );
7615 * StuffTool.static.name = 'stuff';
7616 * StuffTool.static.icon = 'ellipsis';
7617 * StuffTool.static.title = 'More stuff';
7618 * StuffTool.prototype.onSelect = function () {
7619 * $area.text( 'More stuff tool clicked!' );
7620 * // Toggle the active state on each click
7621 * this.reallyActive = !this.reallyActive;
7622 * this.setActive( this.reallyActive );
7623 * // To update the menu label
7624 * this.toolbar.emit( 'updateState' );
7625 * };
7626 * StuffTool.prototype.onUpdateState = function () {
7627 * };
7628 * toolFactory.register( StuffTool );
7629 *
7630 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7631 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7632 * function HelpTool( toolGroup, config ) {
7633 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7634 * padded: true,
7635 * label: 'Help',
7636 * head: true
7637 * } }, config ) );
7638 * this.popup.$body.append( '<p>I am helpful!</p>' );
7639 * }
7640 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7641 * HelpTool.static.name = 'help';
7642 * HelpTool.static.icon = 'help';
7643 * HelpTool.static.title = 'Help';
7644 * toolFactory.register( HelpTool );
7645 *
7646 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7647 * // used once (but not all defined tools must be used).
7648 * toolbar.setup( [
7649 * {
7650 * // 'bar' tool groups display tools' icons only, side-by-side.
7651 * type: 'bar',
7652 * include: [ 'picture', 'help' ]
7653 * },
7654 * {
7655 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7656 * // Menu label indicates which items are selected.
7657 * type: 'menu',
7658 * indicator: 'down',
7659 * include: [ 'settings', 'stuff' ]
7660 * }
7661 * ] );
7662 *
7663 * // Create some UI around the toolbar and place it in the document
7664 * var frame = new OO.ui.PanelLayout( {
7665 * expanded: false,
7666 * framed: true
7667 * } );
7668 * var contentFrame = new OO.ui.PanelLayout( {
7669 * expanded: false,
7670 * padded: true
7671 * } );
7672 * frame.$element.append(
7673 * toolbar.$element,
7674 * contentFrame.$element.append( $area )
7675 * );
7676 * $( 'body' ).append( frame.$element );
7677 *
7678 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7679 * // document.
7680 * toolbar.initialize();
7681 * toolbar.emit( 'updateState' );
7682 *
7683 * @class
7684 * @extends OO.ui.Element
7685 * @mixins OO.EventEmitter
7686 * @mixins OO.ui.mixin.GroupElement
7687 *
7688 * @constructor
7689 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7690 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7691 * @param {Object} [config] Configuration options
7692 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7693 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7694 * the toolbar.
7695 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7696 */
7697 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7698 // Allow passing positional parameters inside the config object
7699 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7700 config = toolFactory;
7701 toolFactory = config.toolFactory;
7702 toolGroupFactory = config.toolGroupFactory;
7703 }
7704
7705 // Configuration initialization
7706 config = config || {};
7707
7708 // Parent constructor
7709 OO.ui.Toolbar.parent.call( this, config );
7710
7711 // Mixin constructors
7712 OO.EventEmitter.call( this );
7713 OO.ui.mixin.GroupElement.call( this, config );
7714
7715 // Properties
7716 this.toolFactory = toolFactory;
7717 this.toolGroupFactory = toolGroupFactory;
7718 this.groups = [];
7719 this.tools = {};
7720 this.$bar = $( '<div>' );
7721 this.$actions = $( '<div>' );
7722 this.initialized = false;
7723 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7724
7725 // Events
7726 this.$element
7727 .add( this.$bar ).add( this.$group ).add( this.$actions )
7728 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7729
7730 // Initialization
7731 this.$group.addClass( 'oo-ui-toolbar-tools' );
7732 if ( config.actions ) {
7733 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7734 }
7735 this.$bar
7736 .addClass( 'oo-ui-toolbar-bar' )
7737 .append( this.$group, '<div style="clear:both"></div>' );
7738 if ( config.shadow ) {
7739 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7740 }
7741 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7742 };
7743
7744 /* Setup */
7745
7746 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7747 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7748 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7749
7750 /* Methods */
7751
7752 /**
7753 * Get the tool factory.
7754 *
7755 * @return {OO.ui.ToolFactory} Tool factory
7756 */
7757 OO.ui.Toolbar.prototype.getToolFactory = function () {
7758 return this.toolFactory;
7759 };
7760
7761 /**
7762 * Get the toolgroup factory.
7763 *
7764 * @return {OO.Factory} Toolgroup factory
7765 */
7766 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7767 return this.toolGroupFactory;
7768 };
7769
7770 /**
7771 * Handles mouse down events.
7772 *
7773 * @private
7774 * @param {jQuery.Event} e Mouse down event
7775 */
7776 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7777 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7778 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7779 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7780 return false;
7781 }
7782 };
7783
7784 /**
7785 * Handle window resize event.
7786 *
7787 * @private
7788 * @param {jQuery.Event} e Window resize event
7789 */
7790 OO.ui.Toolbar.prototype.onWindowResize = function () {
7791 this.$element.toggleClass(
7792 'oo-ui-toolbar-narrow',
7793 this.$bar.width() <= this.narrowThreshold
7794 );
7795 };
7796
7797 /**
7798 * Sets up handles and preloads required information for the toolbar to work.
7799 * This must be called after it is attached to a visible document and before doing anything else.
7800 */
7801 OO.ui.Toolbar.prototype.initialize = function () {
7802 if ( !this.initialized ) {
7803 this.initialized = true;
7804 this.narrowThreshold = this.$group.width() + this.$actions.width();
7805 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7806 this.onWindowResize();
7807 }
7808 };
7809
7810 /**
7811 * Set up the toolbar.
7812 *
7813 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7814 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7815 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7816 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7817 *
7818 * @param {Object.<string,Array>} groups List of toolgroup configurations
7819 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7820 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7821 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7822 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7823 */
7824 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7825 var i, len, type, group,
7826 items = [],
7827 defaultType = 'bar';
7828
7829 // Cleanup previous groups
7830 this.reset();
7831
7832 // Build out new groups
7833 for ( i = 0, len = groups.length; i < len; i++ ) {
7834 group = groups[ i ];
7835 if ( group.include === '*' ) {
7836 // Apply defaults to catch-all groups
7837 if ( group.type === undefined ) {
7838 group.type = 'list';
7839 }
7840 if ( group.label === undefined ) {
7841 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7842 }
7843 }
7844 // Check type has been registered
7845 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7846 items.push(
7847 this.getToolGroupFactory().create( type, this, group )
7848 );
7849 }
7850 this.addItems( items );
7851 };
7852
7853 /**
7854 * Remove all tools and toolgroups from the toolbar.
7855 */
7856 OO.ui.Toolbar.prototype.reset = function () {
7857 var i, len;
7858
7859 this.groups = [];
7860 this.tools = {};
7861 for ( i = 0, len = this.items.length; i < len; i++ ) {
7862 this.items[ i ].destroy();
7863 }
7864 this.clearItems();
7865 };
7866
7867 /**
7868 * Destroy the toolbar.
7869 *
7870 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7871 * this method whenever you are done using a toolbar.
7872 */
7873 OO.ui.Toolbar.prototype.destroy = function () {
7874 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7875 this.reset();
7876 this.$element.remove();
7877 };
7878
7879 /**
7880 * Check if the tool is available.
7881 *
7882 * Available tools are ones that have not yet been added to the toolbar.
7883 *
7884 * @param {string} name Symbolic name of tool
7885 * @return {boolean} Tool is available
7886 */
7887 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7888 return !this.tools[ name ];
7889 };
7890
7891 /**
7892 * Prevent tool from being used again.
7893 *
7894 * @param {OO.ui.Tool} tool Tool to reserve
7895 */
7896 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7897 this.tools[ tool.getName() ] = tool;
7898 };
7899
7900 /**
7901 * Allow tool to be used again.
7902 *
7903 * @param {OO.ui.Tool} tool Tool to release
7904 */
7905 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7906 delete this.tools[ tool.getName() ];
7907 };
7908
7909 /**
7910 * Get accelerator label for tool.
7911 *
7912 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7913 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7914 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7915 *
7916 * @param {string} name Symbolic name of tool
7917 * @return {string|undefined} Tool accelerator label if available
7918 */
7919 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7920 return undefined;
7921 };
7922
7923 /**
7924 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7925 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7926 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7927 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7928 *
7929 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7930 *
7931 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7932 *
7933 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7934 *
7935 * 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.)
7936 *
7937 * include: [ { group: 'group-name' } ]
7938 *
7939 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7940 *
7941 * include: '*'
7942 *
7943 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7944 * please see the [OOjs UI documentation on MediaWiki][1].
7945 *
7946 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7947 *
7948 * @abstract
7949 * @class
7950 * @extends OO.ui.Widget
7951 * @mixins OO.ui.mixin.GroupElement
7952 *
7953 * @constructor
7954 * @param {OO.ui.Toolbar} toolbar
7955 * @param {Object} [config] Configuration options
7956 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7957 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7958 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7959 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7960 * This setting is particularly useful when tools have been added to the toolgroup
7961 * en masse (e.g., via the catch-all selector).
7962 */
7963 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7964 // Allow passing positional parameters inside the config object
7965 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7966 config = toolbar;
7967 toolbar = config.toolbar;
7968 }
7969
7970 // Configuration initialization
7971 config = config || {};
7972
7973 // Parent constructor
7974 OO.ui.ToolGroup.parent.call( this, config );
7975
7976 // Mixin constructors
7977 OO.ui.mixin.GroupElement.call( this, config );
7978
7979 // Properties
7980 this.toolbar = toolbar;
7981 this.tools = {};
7982 this.pressed = null;
7983 this.autoDisabled = false;
7984 this.include = config.include || [];
7985 this.exclude = config.exclude || [];
7986 this.promote = config.promote || [];
7987 this.demote = config.demote || [];
7988 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7989
7990 // Events
7991 this.$element.on( {
7992 mousedown: this.onMouseKeyDown.bind( this ),
7993 mouseup: this.onMouseKeyUp.bind( this ),
7994 keydown: this.onMouseKeyDown.bind( this ),
7995 keyup: this.onMouseKeyUp.bind( this ),
7996 focus: this.onMouseOverFocus.bind( this ),
7997 blur: this.onMouseOutBlur.bind( this ),
7998 mouseover: this.onMouseOverFocus.bind( this ),
7999 mouseout: this.onMouseOutBlur.bind( this )
8000 } );
8001 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8002 this.aggregate( { disable: 'itemDisable' } );
8003 this.connect( this, { itemDisable: 'updateDisabled' } );
8004
8005 // Initialization
8006 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8007 this.$element
8008 .addClass( 'oo-ui-toolGroup' )
8009 .append( this.$group );
8010 this.populate();
8011 };
8012
8013 /* Setup */
8014
8015 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8016 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8017
8018 /* Events */
8019
8020 /**
8021 * @event update
8022 */
8023
8024 /* Static Properties */
8025
8026 /**
8027 * Show labels in tooltips.
8028 *
8029 * @static
8030 * @inheritable
8031 * @property {boolean}
8032 */
8033 OO.ui.ToolGroup.static.titleTooltips = false;
8034
8035 /**
8036 * Show acceleration labels in tooltips.
8037 *
8038 * Note: The OOjs UI library does not include an accelerator system, but does contain
8039 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8040 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8041 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8042 *
8043 * @static
8044 * @inheritable
8045 * @property {boolean}
8046 */
8047 OO.ui.ToolGroup.static.accelTooltips = false;
8048
8049 /**
8050 * Automatically disable the toolgroup when all tools are disabled
8051 *
8052 * @static
8053 * @inheritable
8054 * @property {boolean}
8055 */
8056 OO.ui.ToolGroup.static.autoDisable = true;
8057
8058 /* Methods */
8059
8060 /**
8061 * @inheritdoc
8062 */
8063 OO.ui.ToolGroup.prototype.isDisabled = function () {
8064 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8065 };
8066
8067 /**
8068 * @inheritdoc
8069 */
8070 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8071 var i, item, allDisabled = true;
8072
8073 if ( this.constructor.static.autoDisable ) {
8074 for ( i = this.items.length - 1; i >= 0; i-- ) {
8075 item = this.items[ i ];
8076 if ( !item.isDisabled() ) {
8077 allDisabled = false;
8078 break;
8079 }
8080 }
8081 this.autoDisabled = allDisabled;
8082 }
8083 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8084 };
8085
8086 /**
8087 * Handle mouse down and key down events.
8088 *
8089 * @protected
8090 * @param {jQuery.Event} e Mouse down or key down event
8091 */
8092 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8093 if (
8094 !this.isDisabled() &&
8095 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8096 ) {
8097 this.pressed = this.getTargetTool( e );
8098 if ( this.pressed ) {
8099 this.pressed.setActive( true );
8100 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8101 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8102 }
8103 return false;
8104 }
8105 };
8106
8107 /**
8108 * Handle captured mouse up and key up events.
8109 *
8110 * @protected
8111 * @param {Event} e Mouse up or key up event
8112 */
8113 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8114 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8115 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8116 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8117 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8118 this.onMouseKeyUp( e );
8119 };
8120
8121 /**
8122 * Handle mouse up and key up events.
8123 *
8124 * @protected
8125 * @param {jQuery.Event} e Mouse up or key up event
8126 */
8127 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8128 var tool = this.getTargetTool( e );
8129
8130 if (
8131 !this.isDisabled() && this.pressed && this.pressed === tool &&
8132 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8133 ) {
8134 this.pressed.onSelect();
8135 this.pressed = null;
8136 return false;
8137 }
8138
8139 this.pressed = null;
8140 };
8141
8142 /**
8143 * Handle mouse over and focus events.
8144 *
8145 * @protected
8146 * @param {jQuery.Event} e Mouse over or focus event
8147 */
8148 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8149 var tool = this.getTargetTool( e );
8150
8151 if ( this.pressed && this.pressed === tool ) {
8152 this.pressed.setActive( true );
8153 }
8154 };
8155
8156 /**
8157 * Handle mouse out and blur events.
8158 *
8159 * @protected
8160 * @param {jQuery.Event} e Mouse out or blur event
8161 */
8162 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8163 var tool = this.getTargetTool( e );
8164
8165 if ( this.pressed && this.pressed === tool ) {
8166 this.pressed.setActive( false );
8167 }
8168 };
8169
8170 /**
8171 * Get the closest tool to a jQuery.Event.
8172 *
8173 * Only tool links are considered, which prevents other elements in the tool such as popups from
8174 * triggering tool group interactions.
8175 *
8176 * @private
8177 * @param {jQuery.Event} e
8178 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8179 */
8180 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8181 var tool,
8182 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8183
8184 if ( $item.length ) {
8185 tool = $item.parent().data( 'oo-ui-tool' );
8186 }
8187
8188 return tool && !tool.isDisabled() ? tool : null;
8189 };
8190
8191 /**
8192 * Handle tool registry register events.
8193 *
8194 * If a tool is registered after the group is created, we must repopulate the list to account for:
8195 *
8196 * - a tool being added that may be included
8197 * - a tool already included being overridden
8198 *
8199 * @protected
8200 * @param {string} name Symbolic name of tool
8201 */
8202 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8203 this.populate();
8204 };
8205
8206 /**
8207 * Get the toolbar that contains the toolgroup.
8208 *
8209 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8210 */
8211 OO.ui.ToolGroup.prototype.getToolbar = function () {
8212 return this.toolbar;
8213 };
8214
8215 /**
8216 * Add and remove tools based on configuration.
8217 */
8218 OO.ui.ToolGroup.prototype.populate = function () {
8219 var i, len, name, tool,
8220 toolFactory = this.toolbar.getToolFactory(),
8221 names = {},
8222 add = [],
8223 remove = [],
8224 list = this.toolbar.getToolFactory().getTools(
8225 this.include, this.exclude, this.promote, this.demote
8226 );
8227
8228 // Build a list of needed tools
8229 for ( i = 0, len = list.length; i < len; i++ ) {
8230 name = list[ i ];
8231 if (
8232 // Tool exists
8233 toolFactory.lookup( name ) &&
8234 // Tool is available or is already in this group
8235 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8236 ) {
8237 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8238 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8239 this.toolbar.tools[ name ] = true;
8240 tool = this.tools[ name ];
8241 if ( !tool ) {
8242 // Auto-initialize tools on first use
8243 this.tools[ name ] = tool = toolFactory.create( name, this );
8244 tool.updateTitle();
8245 }
8246 this.toolbar.reserveTool( tool );
8247 add.push( tool );
8248 names[ name ] = true;
8249 }
8250 }
8251 // Remove tools that are no longer needed
8252 for ( name in this.tools ) {
8253 if ( !names[ name ] ) {
8254 this.tools[ name ].destroy();
8255 this.toolbar.releaseTool( this.tools[ name ] );
8256 remove.push( this.tools[ name ] );
8257 delete this.tools[ name ];
8258 }
8259 }
8260 if ( remove.length ) {
8261 this.removeItems( remove );
8262 }
8263 // Update emptiness state
8264 if ( add.length ) {
8265 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8266 } else {
8267 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8268 }
8269 // Re-add tools (moving existing ones to new locations)
8270 this.addItems( add );
8271 // Disabled state may depend on items
8272 this.updateDisabled();
8273 };
8274
8275 /**
8276 * Destroy toolgroup.
8277 */
8278 OO.ui.ToolGroup.prototype.destroy = function () {
8279 var name;
8280
8281 this.clearItems();
8282 this.toolbar.getToolFactory().disconnect( this );
8283 for ( name in this.tools ) {
8284 this.toolbar.releaseTool( this.tools[ name ] );
8285 this.tools[ name ].disconnect( this ).destroy();
8286 delete this.tools[ name ];
8287 }
8288 this.$element.remove();
8289 };
8290
8291 /**
8292 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8293 * consists of a header that contains the dialog title, a body with the message, and a footer that
8294 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8295 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8296 *
8297 * There are two basic types of message dialogs, confirmation and alert:
8298 *
8299 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8300 * more details about the consequences.
8301 * - **alert**: the dialog title describes which event occurred and the message provides more information
8302 * about why the event occurred.
8303 *
8304 * The MessageDialog class specifies two actions: ‘accept’, the primary
8305 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8306 * passing along the selected action.
8307 *
8308 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8309 *
8310 * @example
8311 * // Example: Creating and opening a message dialog window.
8312 * var messageDialog = new OO.ui.MessageDialog();
8313 *
8314 * // Create and append a window manager.
8315 * var windowManager = new OO.ui.WindowManager();
8316 * $( 'body' ).append( windowManager.$element );
8317 * windowManager.addWindows( [ messageDialog ] );
8318 * // Open the window.
8319 * windowManager.openWindow( messageDialog, {
8320 * title: 'Basic message dialog',
8321 * message: 'This is the message'
8322 * } );
8323 *
8324 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8325 *
8326 * @class
8327 * @extends OO.ui.Dialog
8328 *
8329 * @constructor
8330 * @param {Object} [config] Configuration options
8331 */
8332 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8333 // Parent constructor
8334 OO.ui.MessageDialog.parent.call( this, config );
8335
8336 // Properties
8337 this.verticalActionLayout = null;
8338
8339 // Initialization
8340 this.$element.addClass( 'oo-ui-messageDialog' );
8341 };
8342
8343 /* Setup */
8344
8345 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8346
8347 /* Static Properties */
8348
8349 OO.ui.MessageDialog.static.name = 'message';
8350
8351 OO.ui.MessageDialog.static.size = 'small';
8352
8353 OO.ui.MessageDialog.static.verbose = false;
8354
8355 /**
8356 * Dialog title.
8357 *
8358 * The title of a confirmation dialog describes what a progressive action will do. The
8359 * title of an alert dialog describes which event occurred.
8360 *
8361 * @static
8362 * @inheritable
8363 * @property {jQuery|string|Function|null}
8364 */
8365 OO.ui.MessageDialog.static.title = null;
8366
8367 /**
8368 * The message displayed in the dialog body.
8369 *
8370 * A confirmation message describes the consequences of a progressive action. An alert
8371 * message describes why an event occurred.
8372 *
8373 * @static
8374 * @inheritable
8375 * @property {jQuery|string|Function|null}
8376 */
8377 OO.ui.MessageDialog.static.message = null;
8378
8379 OO.ui.MessageDialog.static.actions = [
8380 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8381 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8382 ];
8383
8384 /* Methods */
8385
8386 /**
8387 * @inheritdoc
8388 */
8389 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8390 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8391
8392 // Events
8393 this.manager.connect( this, {
8394 resize: 'onResize'
8395 } );
8396
8397 return this;
8398 };
8399
8400 /**
8401 * @inheritdoc
8402 */
8403 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8404 this.fitActions();
8405 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8406 };
8407
8408 /**
8409 * Handle window resized events.
8410 *
8411 * @private
8412 */
8413 OO.ui.MessageDialog.prototype.onResize = function () {
8414 var dialog = this;
8415 dialog.fitActions();
8416 // Wait for CSS transition to finish and do it again :(
8417 setTimeout( function () {
8418 dialog.fitActions();
8419 }, 300 );
8420 };
8421
8422 /**
8423 * Toggle action layout between vertical and horizontal.
8424 *
8425 * @private
8426 * @param {boolean} [value] Layout actions vertically, omit to toggle
8427 * @chainable
8428 */
8429 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8430 value = value === undefined ? !this.verticalActionLayout : !!value;
8431
8432 if ( value !== this.verticalActionLayout ) {
8433 this.verticalActionLayout = value;
8434 this.$actions
8435 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8436 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8437 }
8438
8439 return this;
8440 };
8441
8442 /**
8443 * @inheritdoc
8444 */
8445 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8446 if ( action ) {
8447 return new OO.ui.Process( function () {
8448 this.close( { action: action } );
8449 }, this );
8450 }
8451 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8452 };
8453
8454 /**
8455 * @inheritdoc
8456 *
8457 * @param {Object} [data] Dialog opening data
8458 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8459 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8460 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8461 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8462 * action item
8463 */
8464 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8465 data = data || {};
8466
8467 // Parent method
8468 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8469 .next( function () {
8470 this.title.setLabel(
8471 data.title !== undefined ? data.title : this.constructor.static.title
8472 );
8473 this.message.setLabel(
8474 data.message !== undefined ? data.message : this.constructor.static.message
8475 );
8476 this.message.$element.toggleClass(
8477 'oo-ui-messageDialog-message-verbose',
8478 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8479 );
8480 }, this );
8481 };
8482
8483 /**
8484 * @inheritdoc
8485 */
8486 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8487 data = data || {};
8488
8489 // Parent method
8490 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8491 .next( function () {
8492 // Focus the primary action button
8493 var actions = this.actions.get();
8494 actions = actions.filter( function ( action ) {
8495 return action.getFlags().indexOf( 'primary' ) > -1;
8496 } );
8497 if ( actions.length > 0 ) {
8498 actions[ 0 ].$button.focus();
8499 }
8500 }, this );
8501 };
8502
8503 /**
8504 * @inheritdoc
8505 */
8506 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8507 var bodyHeight, oldOverflow,
8508 $scrollable = this.container.$element;
8509
8510 oldOverflow = $scrollable[ 0 ].style.overflow;
8511 $scrollable[ 0 ].style.overflow = 'hidden';
8512
8513 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8514
8515 bodyHeight = this.text.$element.outerHeight( true );
8516 $scrollable[ 0 ].style.overflow = oldOverflow;
8517
8518 return bodyHeight;
8519 };
8520
8521 /**
8522 * @inheritdoc
8523 */
8524 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8525 var $scrollable = this.container.$element;
8526 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8527
8528 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8529 // Need to do it after transition completes (250ms), add 50ms just in case.
8530 setTimeout( function () {
8531 var oldOverflow = $scrollable[ 0 ].style.overflow;
8532 $scrollable[ 0 ].style.overflow = 'hidden';
8533
8534 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8535
8536 $scrollable[ 0 ].style.overflow = oldOverflow;
8537 }, 300 );
8538
8539 return this;
8540 };
8541
8542 /**
8543 * @inheritdoc
8544 */
8545 OO.ui.MessageDialog.prototype.initialize = function () {
8546 // Parent method
8547 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8548
8549 // Properties
8550 this.$actions = $( '<div>' );
8551 this.container = new OO.ui.PanelLayout( {
8552 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8553 } );
8554 this.text = new OO.ui.PanelLayout( {
8555 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8556 } );
8557 this.message = new OO.ui.LabelWidget( {
8558 classes: [ 'oo-ui-messageDialog-message' ]
8559 } );
8560
8561 // Initialization
8562 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8563 this.$content.addClass( 'oo-ui-messageDialog-content' );
8564 this.container.$element.append( this.text.$element );
8565 this.text.$element.append( this.title.$element, this.message.$element );
8566 this.$body.append( this.container.$element );
8567 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8568 this.$foot.append( this.$actions );
8569 };
8570
8571 /**
8572 * @inheritdoc
8573 */
8574 OO.ui.MessageDialog.prototype.attachActions = function () {
8575 var i, len, other, special, others;
8576
8577 // Parent method
8578 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8579
8580 special = this.actions.getSpecial();
8581 others = this.actions.getOthers();
8582
8583 if ( special.safe ) {
8584 this.$actions.append( special.safe.$element );
8585 special.safe.toggleFramed( false );
8586 }
8587 if ( others.length ) {
8588 for ( i = 0, len = others.length; i < len; i++ ) {
8589 other = others[ i ];
8590 this.$actions.append( other.$element );
8591 other.toggleFramed( false );
8592 }
8593 }
8594 if ( special.primary ) {
8595 this.$actions.append( special.primary.$element );
8596 special.primary.toggleFramed( false );
8597 }
8598
8599 if ( !this.isOpening() ) {
8600 // If the dialog is currently opening, this will be called automatically soon.
8601 // This also calls #fitActions.
8602 this.updateSize();
8603 }
8604 };
8605
8606 /**
8607 * Fit action actions into columns or rows.
8608 *
8609 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8610 *
8611 * @private
8612 */
8613 OO.ui.MessageDialog.prototype.fitActions = function () {
8614 var i, len, action,
8615 previous = this.verticalActionLayout,
8616 actions = this.actions.get();
8617
8618 // Detect clipping
8619 this.toggleVerticalActionLayout( false );
8620 for ( i = 0, len = actions.length; i < len; i++ ) {
8621 action = actions[ i ];
8622 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8623 this.toggleVerticalActionLayout( true );
8624 break;
8625 }
8626 }
8627
8628 // Move the body out of the way of the foot
8629 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8630
8631 if ( this.verticalActionLayout !== previous ) {
8632 // We changed the layout, window height might need to be updated.
8633 this.updateSize();
8634 }
8635 };
8636
8637 /**
8638 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8639 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8640 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8641 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8642 * required for each process.
8643 *
8644 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8645 * processes with an animation. The header contains the dialog title as well as
8646 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8647 * a ‘primary’ action on the right (e.g., ‘Done’).
8648 *
8649 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8650 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8651 *
8652 * @example
8653 * // Example: Creating and opening a process dialog window.
8654 * function MyProcessDialog( config ) {
8655 * MyProcessDialog.parent.call( this, config );
8656 * }
8657 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8658 *
8659 * MyProcessDialog.static.title = 'Process dialog';
8660 * MyProcessDialog.static.actions = [
8661 * { action: 'save', label: 'Done', flags: 'primary' },
8662 * { label: 'Cancel', flags: 'safe' }
8663 * ];
8664 *
8665 * MyProcessDialog.prototype.initialize = function () {
8666 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8667 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8668 * 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>' );
8669 * this.$body.append( this.content.$element );
8670 * };
8671 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8672 * var dialog = this;
8673 * if ( action ) {
8674 * return new OO.ui.Process( function () {
8675 * dialog.close( { action: action } );
8676 * } );
8677 * }
8678 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8679 * };
8680 *
8681 * var windowManager = new OO.ui.WindowManager();
8682 * $( 'body' ).append( windowManager.$element );
8683 *
8684 * var dialog = new MyProcessDialog();
8685 * windowManager.addWindows( [ dialog ] );
8686 * windowManager.openWindow( dialog );
8687 *
8688 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8689 *
8690 * @abstract
8691 * @class
8692 * @extends OO.ui.Dialog
8693 *
8694 * @constructor
8695 * @param {Object} [config] Configuration options
8696 */
8697 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8698 // Parent constructor
8699 OO.ui.ProcessDialog.parent.call( this, config );
8700
8701 // Properties
8702 this.fitOnOpen = false;
8703
8704 // Initialization
8705 this.$element.addClass( 'oo-ui-processDialog' );
8706 };
8707
8708 /* Setup */
8709
8710 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8711
8712 /* Methods */
8713
8714 /**
8715 * Handle dismiss button click events.
8716 *
8717 * Hides errors.
8718 *
8719 * @private
8720 */
8721 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8722 this.hideErrors();
8723 };
8724
8725 /**
8726 * Handle retry button click events.
8727 *
8728 * Hides errors and then tries again.
8729 *
8730 * @private
8731 */
8732 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8733 this.hideErrors();
8734 this.executeAction( this.currentAction );
8735 };
8736
8737 /**
8738 * @inheritdoc
8739 */
8740 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8741 if ( this.actions.isSpecial( action ) ) {
8742 this.fitLabel();
8743 }
8744 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8745 };
8746
8747 /**
8748 * @inheritdoc
8749 */
8750 OO.ui.ProcessDialog.prototype.initialize = function () {
8751 // Parent method
8752 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8753
8754 // Properties
8755 this.$navigation = $( '<div>' );
8756 this.$location = $( '<div>' );
8757 this.$safeActions = $( '<div>' );
8758 this.$primaryActions = $( '<div>' );
8759 this.$otherActions = $( '<div>' );
8760 this.dismissButton = new OO.ui.ButtonWidget( {
8761 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8762 } );
8763 this.retryButton = new OO.ui.ButtonWidget();
8764 this.$errors = $( '<div>' );
8765 this.$errorsTitle = $( '<div>' );
8766
8767 // Events
8768 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8769 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8770
8771 // Initialization
8772 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8773 this.$location
8774 .append( this.title.$element )
8775 .addClass( 'oo-ui-processDialog-location' );
8776 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8777 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8778 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8779 this.$errorsTitle
8780 .addClass( 'oo-ui-processDialog-errors-title' )
8781 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8782 this.$errors
8783 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8784 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8785 this.$content
8786 .addClass( 'oo-ui-processDialog-content' )
8787 .append( this.$errors );
8788 this.$navigation
8789 .addClass( 'oo-ui-processDialog-navigation' )
8790 .append( this.$safeActions, this.$location, this.$primaryActions );
8791 this.$head.append( this.$navigation );
8792 this.$foot.append( this.$otherActions );
8793 };
8794
8795 /**
8796 * @inheritdoc
8797 */
8798 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8799 var i, len, widgets = [];
8800 for ( i = 0, len = actions.length; i < len; i++ ) {
8801 widgets.push(
8802 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8803 );
8804 }
8805 return widgets;
8806 };
8807
8808 /**
8809 * @inheritdoc
8810 */
8811 OO.ui.ProcessDialog.prototype.attachActions = function () {
8812 var i, len, other, special, others;
8813
8814 // Parent method
8815 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8816
8817 special = this.actions.getSpecial();
8818 others = this.actions.getOthers();
8819 if ( special.primary ) {
8820 this.$primaryActions.append( special.primary.$element );
8821 }
8822 for ( i = 0, len = others.length; i < len; i++ ) {
8823 other = others[ i ];
8824 this.$otherActions.append( other.$element );
8825 }
8826 if ( special.safe ) {
8827 this.$safeActions.append( special.safe.$element );
8828 }
8829
8830 this.fitLabel();
8831 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8832 };
8833
8834 /**
8835 * @inheritdoc
8836 */
8837 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8838 var process = this;
8839 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8840 .fail( function ( errors ) {
8841 process.showErrors( errors || [] );
8842 } );
8843 };
8844
8845 /**
8846 * @inheritdoc
8847 */
8848 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8849 // Parent method
8850 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8851
8852 this.fitLabel();
8853 };
8854
8855 /**
8856 * Fit label between actions.
8857 *
8858 * @private
8859 * @chainable
8860 */
8861 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8862 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8863 size = this.getSizeProperties();
8864
8865 if ( typeof size.width !== 'number' ) {
8866 if ( this.isOpened() ) {
8867 navigationWidth = this.$head.width() - 20;
8868 } else if ( this.isOpening() ) {
8869 if ( !this.fitOnOpen ) {
8870 // Size is relative and the dialog isn't open yet, so wait.
8871 this.manager.opening.done( this.fitLabel.bind( this ) );
8872 this.fitOnOpen = true;
8873 }
8874 return;
8875 } else {
8876 return;
8877 }
8878 } else {
8879 navigationWidth = size.width - 20;
8880 }
8881
8882 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8883 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8884 biggerWidth = Math.max( safeWidth, primaryWidth );
8885
8886 labelWidth = this.title.$element.width();
8887
8888 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8889 // We have enough space to center the label
8890 leftWidth = rightWidth = biggerWidth;
8891 } else {
8892 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8893 if ( this.getDir() === 'ltr' ) {
8894 leftWidth = safeWidth;
8895 rightWidth = primaryWidth;
8896 } else {
8897 leftWidth = primaryWidth;
8898 rightWidth = safeWidth;
8899 }
8900 }
8901
8902 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8903
8904 return this;
8905 };
8906
8907 /**
8908 * Handle errors that occurred during accept or reject processes.
8909 *
8910 * @private
8911 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8912 */
8913 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8914 var i, len, $item, actions,
8915 items = [],
8916 abilities = {},
8917 recoverable = true,
8918 warning = false;
8919
8920 if ( errors instanceof OO.ui.Error ) {
8921 errors = [ errors ];
8922 }
8923
8924 for ( i = 0, len = errors.length; i < len; i++ ) {
8925 if ( !errors[ i ].isRecoverable() ) {
8926 recoverable = false;
8927 }
8928 if ( errors[ i ].isWarning() ) {
8929 warning = true;
8930 }
8931 $item = $( '<div>' )
8932 .addClass( 'oo-ui-processDialog-error' )
8933 .append( errors[ i ].getMessage() );
8934 items.push( $item[ 0 ] );
8935 }
8936 this.$errorItems = $( items );
8937 if ( recoverable ) {
8938 abilities[ this.currentAction ] = true;
8939 // Copy the flags from the first matching action
8940 actions = this.actions.get( { actions: this.currentAction } );
8941 if ( actions.length ) {
8942 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8943 }
8944 } else {
8945 abilities[ this.currentAction ] = false;
8946 this.actions.setAbilities( abilities );
8947 }
8948 if ( warning ) {
8949 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8950 } else {
8951 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8952 }
8953 this.retryButton.toggle( recoverable );
8954 this.$errorsTitle.after( this.$errorItems );
8955 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8956 };
8957
8958 /**
8959 * Hide errors.
8960 *
8961 * @private
8962 */
8963 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8964 this.$errors.addClass( 'oo-ui-element-hidden' );
8965 if ( this.$errorItems ) {
8966 this.$errorItems.remove();
8967 this.$errorItems = null;
8968 }
8969 };
8970
8971 /**
8972 * @inheritdoc
8973 */
8974 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8975 // Parent method
8976 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8977 .first( function () {
8978 // Make sure to hide errors
8979 this.hideErrors();
8980 this.fitOnOpen = false;
8981 }, this );
8982 };
8983
8984 /**
8985 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8986 * which is a widget that is specified by reference before any optional configuration settings.
8987 *
8988 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8989 *
8990 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8991 * A left-alignment is used for forms with many fields.
8992 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8993 * A right-alignment is used for long but familiar forms which users tab through,
8994 * verifying the current field with a quick glance at the label.
8995 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8996 * that users fill out from top to bottom.
8997 * - **inline**: The label is placed after the field-widget and aligned to the left.
8998 * An inline-alignment is best used with checkboxes or radio buttons.
8999 *
9000 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9001 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9002 *
9003 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9004 * @class
9005 * @extends OO.ui.Layout
9006 * @mixins OO.ui.mixin.LabelElement
9007 * @mixins OO.ui.mixin.TitledElement
9008 *
9009 * @constructor
9010 * @param {OO.ui.Widget} fieldWidget Field widget
9011 * @param {Object} [config] Configuration options
9012 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9013 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9014 * The array may contain strings or OO.ui.HtmlSnippet instances.
9015 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9016 * The array may contain strings or OO.ui.HtmlSnippet instances.
9017 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9018 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9019 * For important messages, you are advised to use `notices`, as they are always shown.
9020 *
9021 * @throws {Error} An error is thrown if no widget is specified
9022 */
9023 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9024 var hasInputWidget, div, i;
9025
9026 // Allow passing positional parameters inside the config object
9027 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9028 config = fieldWidget;
9029 fieldWidget = config.fieldWidget;
9030 }
9031
9032 // Make sure we have required constructor arguments
9033 if ( fieldWidget === undefined ) {
9034 throw new Error( 'Widget not found' );
9035 }
9036
9037 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9038
9039 // Configuration initialization
9040 config = $.extend( { align: 'left' }, config );
9041
9042 // Parent constructor
9043 OO.ui.FieldLayout.parent.call( this, config );
9044
9045 // Mixin constructors
9046 OO.ui.mixin.LabelElement.call( this, config );
9047 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9048
9049 // Properties
9050 this.fieldWidget = fieldWidget;
9051 this.errors = config.errors || [];
9052 this.notices = config.notices || [];
9053 this.$field = $( '<div>' );
9054 this.$messages = $( '<ul>' );
9055 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9056 this.align = null;
9057 if ( config.help ) {
9058 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9059 classes: [ 'oo-ui-fieldLayout-help' ],
9060 framed: false,
9061 icon: 'info'
9062 } );
9063
9064 div = $( '<div>' );
9065 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9066 div.html( config.help.toString() );
9067 } else {
9068 div.text( config.help );
9069 }
9070 this.popupButtonWidget.getPopup().$body.append(
9071 div.addClass( 'oo-ui-fieldLayout-help-content' )
9072 );
9073 this.$help = this.popupButtonWidget.$element;
9074 } else {
9075 this.$help = $( [] );
9076 }
9077
9078 // Events
9079 if ( hasInputWidget ) {
9080 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9081 }
9082 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9083
9084 // Initialization
9085 this.$element
9086 .addClass( 'oo-ui-fieldLayout' )
9087 .append( this.$help, this.$body );
9088 if ( this.errors.length || this.notices.length ) {
9089 this.$element.append( this.$messages );
9090 }
9091 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9092 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9093 this.$field
9094 .addClass( 'oo-ui-fieldLayout-field' )
9095 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9096 .append( this.fieldWidget.$element );
9097
9098 for ( i = 0; i < this.notices.length; i++ ) {
9099 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9100 }
9101 for ( i = 0; i < this.errors.length; i++ ) {
9102 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9103 }
9104
9105 this.setAlignment( config.align );
9106 };
9107
9108 /* Setup */
9109
9110 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9111 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9112 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9113
9114 /* Methods */
9115
9116 /**
9117 * Handle field disable events.
9118 *
9119 * @private
9120 * @param {boolean} value Field is disabled
9121 */
9122 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9123 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9124 };
9125
9126 /**
9127 * Handle label mouse click events.
9128 *
9129 * @private
9130 * @param {jQuery.Event} e Mouse click event
9131 */
9132 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9133 this.fieldWidget.simulateLabelClick();
9134 return false;
9135 };
9136
9137 /**
9138 * Get the widget contained by the field.
9139 *
9140 * @return {OO.ui.Widget} Field widget
9141 */
9142 OO.ui.FieldLayout.prototype.getField = function () {
9143 return this.fieldWidget;
9144 };
9145
9146 /**
9147 * @param {string} kind 'error' or 'notice'
9148 * @param {string|OO.ui.HtmlSnippet} text
9149 * @return {jQuery}
9150 */
9151 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9152 var $listItem, $icon, message;
9153 $listItem = $( '<li>' );
9154 if ( kind === 'error' ) {
9155 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9156 } else if ( kind === 'notice' ) {
9157 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9158 } else {
9159 $icon = '';
9160 }
9161 message = new OO.ui.LabelWidget( { label: text } );
9162 $listItem
9163 .append( $icon, message.$element )
9164 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9165 return $listItem;
9166 };
9167
9168 /**
9169 * Set the field alignment mode.
9170 *
9171 * @private
9172 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9173 * @chainable
9174 */
9175 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9176 if ( value !== this.align ) {
9177 // Default to 'left'
9178 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9179 value = 'left';
9180 }
9181 // Reorder elements
9182 if ( value === 'inline' ) {
9183 this.$body.append( this.$field, this.$label );
9184 } else {
9185 this.$body.append( this.$label, this.$field );
9186 }
9187 // Set classes. The following classes can be used here:
9188 // * oo-ui-fieldLayout-align-left
9189 // * oo-ui-fieldLayout-align-right
9190 // * oo-ui-fieldLayout-align-top
9191 // * oo-ui-fieldLayout-align-inline
9192 if ( this.align ) {
9193 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9194 }
9195 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9196 this.align = value;
9197 }
9198
9199 return this;
9200 };
9201
9202 /**
9203 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9204 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9205 * is required and is specified before any optional configuration settings.
9206 *
9207 * Labels can be aligned in one of four ways:
9208 *
9209 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9210 * A left-alignment is used for forms with many fields.
9211 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9212 * A right-alignment is used for long but familiar forms which users tab through,
9213 * verifying the current field with a quick glance at the label.
9214 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9215 * that users fill out from top to bottom.
9216 * - **inline**: The label is placed after the field-widget and aligned to the left.
9217 * An inline-alignment is best used with checkboxes or radio buttons.
9218 *
9219 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9220 * text is specified.
9221 *
9222 * @example
9223 * // Example of an ActionFieldLayout
9224 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9225 * new OO.ui.TextInputWidget( {
9226 * placeholder: 'Field widget'
9227 * } ),
9228 * new OO.ui.ButtonWidget( {
9229 * label: 'Button'
9230 * } ),
9231 * {
9232 * label: 'An ActionFieldLayout. This label is aligned top',
9233 * align: 'top',
9234 * help: 'This is help text'
9235 * }
9236 * );
9237 *
9238 * $( 'body' ).append( actionFieldLayout.$element );
9239 *
9240 * @class
9241 * @extends OO.ui.FieldLayout
9242 *
9243 * @constructor
9244 * @param {OO.ui.Widget} fieldWidget Field widget
9245 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9246 */
9247 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9248 // Allow passing positional parameters inside the config object
9249 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9250 config = fieldWidget;
9251 fieldWidget = config.fieldWidget;
9252 buttonWidget = config.buttonWidget;
9253 }
9254
9255 // Parent constructor
9256 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9257
9258 // Properties
9259 this.buttonWidget = buttonWidget;
9260 this.$button = $( '<div>' );
9261 this.$input = $( '<div>' );
9262
9263 // Initialization
9264 this.$element
9265 .addClass( 'oo-ui-actionFieldLayout' );
9266 this.$button
9267 .addClass( 'oo-ui-actionFieldLayout-button' )
9268 .append( this.buttonWidget.$element );
9269 this.$input
9270 .addClass( 'oo-ui-actionFieldLayout-input' )
9271 .append( this.fieldWidget.$element );
9272 this.$field
9273 .append( this.$input, this.$button );
9274 };
9275
9276 /* Setup */
9277
9278 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9279
9280 /**
9281 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9282 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9283 * configured with a label as well. For more information and examples,
9284 * please see the [OOjs UI documentation on MediaWiki][1].
9285 *
9286 * @example
9287 * // Example of a fieldset layout
9288 * var input1 = new OO.ui.TextInputWidget( {
9289 * placeholder: 'A text input field'
9290 * } );
9291 *
9292 * var input2 = new OO.ui.TextInputWidget( {
9293 * placeholder: 'A text input field'
9294 * } );
9295 *
9296 * var fieldset = new OO.ui.FieldsetLayout( {
9297 * label: 'Example of a fieldset layout'
9298 * } );
9299 *
9300 * fieldset.addItems( [
9301 * new OO.ui.FieldLayout( input1, {
9302 * label: 'Field One'
9303 * } ),
9304 * new OO.ui.FieldLayout( input2, {
9305 * label: 'Field Two'
9306 * } )
9307 * ] );
9308 * $( 'body' ).append( fieldset.$element );
9309 *
9310 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9311 *
9312 * @class
9313 * @extends OO.ui.Layout
9314 * @mixins OO.ui.mixin.IconElement
9315 * @mixins OO.ui.mixin.LabelElement
9316 * @mixins OO.ui.mixin.GroupElement
9317 *
9318 * @constructor
9319 * @param {Object} [config] Configuration options
9320 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9321 */
9322 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9323 // Configuration initialization
9324 config = config || {};
9325
9326 // Parent constructor
9327 OO.ui.FieldsetLayout.parent.call( this, config );
9328
9329 // Mixin constructors
9330 OO.ui.mixin.IconElement.call( this, config );
9331 OO.ui.mixin.LabelElement.call( this, config );
9332 OO.ui.mixin.GroupElement.call( this, config );
9333
9334 if ( config.help ) {
9335 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9336 classes: [ 'oo-ui-fieldsetLayout-help' ],
9337 framed: false,
9338 icon: 'info'
9339 } );
9340
9341 this.popupButtonWidget.getPopup().$body.append(
9342 $( '<div>' )
9343 .text( config.help )
9344 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9345 );
9346 this.$help = this.popupButtonWidget.$element;
9347 } else {
9348 this.$help = $( [] );
9349 }
9350
9351 // Initialization
9352 this.$element
9353 .addClass( 'oo-ui-fieldsetLayout' )
9354 .prepend( this.$help, this.$icon, this.$label, this.$group );
9355 if ( Array.isArray( config.items ) ) {
9356 this.addItems( config.items );
9357 }
9358 };
9359
9360 /* Setup */
9361
9362 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9363 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9364 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9365 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9366
9367 /**
9368 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9369 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9370 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9371 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9372 *
9373 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9374 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9375 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9376 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9377 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9378 * often have simplified APIs to match the capabilities of HTML forms.
9379 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9380 *
9381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9382 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9383 *
9384 * @example
9385 * // Example of a form layout that wraps a fieldset layout
9386 * var input1 = new OO.ui.TextInputWidget( {
9387 * placeholder: 'Username'
9388 * } );
9389 * var input2 = new OO.ui.TextInputWidget( {
9390 * placeholder: 'Password',
9391 * type: 'password'
9392 * } );
9393 * var submit = new OO.ui.ButtonInputWidget( {
9394 * label: 'Submit'
9395 * } );
9396 *
9397 * var fieldset = new OO.ui.FieldsetLayout( {
9398 * label: 'A form layout'
9399 * } );
9400 * fieldset.addItems( [
9401 * new OO.ui.FieldLayout( input1, {
9402 * label: 'Username',
9403 * align: 'top'
9404 * } ),
9405 * new OO.ui.FieldLayout( input2, {
9406 * label: 'Password',
9407 * align: 'top'
9408 * } ),
9409 * new OO.ui.FieldLayout( submit )
9410 * ] );
9411 * var form = new OO.ui.FormLayout( {
9412 * items: [ fieldset ],
9413 * action: '/api/formhandler',
9414 * method: 'get'
9415 * } )
9416 * $( 'body' ).append( form.$element );
9417 *
9418 * @class
9419 * @extends OO.ui.Layout
9420 * @mixins OO.ui.mixin.GroupElement
9421 *
9422 * @constructor
9423 * @param {Object} [config] Configuration options
9424 * @cfg {string} [method] HTML form `method` attribute
9425 * @cfg {string} [action] HTML form `action` attribute
9426 * @cfg {string} [enctype] HTML form `enctype` attribute
9427 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9428 */
9429 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9430 // Configuration initialization
9431 config = config || {};
9432
9433 // Parent constructor
9434 OO.ui.FormLayout.parent.call( this, config );
9435
9436 // Mixin constructors
9437 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9438
9439 // Events
9440 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9441
9442 // Make sure the action is safe
9443 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9444 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9445 }
9446
9447 // Initialization
9448 this.$element
9449 .addClass( 'oo-ui-formLayout' )
9450 .attr( {
9451 method: config.method,
9452 action: config.action,
9453 enctype: config.enctype
9454 } );
9455 if ( Array.isArray( config.items ) ) {
9456 this.addItems( config.items );
9457 }
9458 };
9459
9460 /* Setup */
9461
9462 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9463 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9464
9465 /* Events */
9466
9467 /**
9468 * A 'submit' event is emitted when the form is submitted.
9469 *
9470 * @event submit
9471 */
9472
9473 /* Static Properties */
9474
9475 OO.ui.FormLayout.static.tagName = 'form';
9476
9477 /* Methods */
9478
9479 /**
9480 * Handle form submit events.
9481 *
9482 * @private
9483 * @param {jQuery.Event} e Submit event
9484 * @fires submit
9485 */
9486 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9487 if ( this.emit( 'submit' ) ) {
9488 return false;
9489 }
9490 };
9491
9492 /**
9493 * 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)
9494 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9495 *
9496 * @example
9497 * var menuLayout = new OO.ui.MenuLayout( {
9498 * position: 'top'
9499 * } ),
9500 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9501 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9502 * select = new OO.ui.SelectWidget( {
9503 * items: [
9504 * new OO.ui.OptionWidget( {
9505 * data: 'before',
9506 * label: 'Before',
9507 * } ),
9508 * new OO.ui.OptionWidget( {
9509 * data: 'after',
9510 * label: 'After',
9511 * } ),
9512 * new OO.ui.OptionWidget( {
9513 * data: 'top',
9514 * label: 'Top',
9515 * } ),
9516 * new OO.ui.OptionWidget( {
9517 * data: 'bottom',
9518 * label: 'Bottom',
9519 * } )
9520 * ]
9521 * } ).on( 'select', function ( item ) {
9522 * menuLayout.setMenuPosition( item.getData() );
9523 * } );
9524 *
9525 * menuLayout.$menu.append(
9526 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9527 * );
9528 * menuLayout.$content.append(
9529 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9530 * );
9531 * $( 'body' ).append( menuLayout.$element );
9532 *
9533 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9534 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9535 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9536 * may be omitted.
9537 *
9538 * .oo-ui-menuLayout-menu {
9539 * height: 200px;
9540 * width: 200px;
9541 * }
9542 * .oo-ui-menuLayout-content {
9543 * top: 200px;
9544 * left: 200px;
9545 * right: 200px;
9546 * bottom: 200px;
9547 * }
9548 *
9549 * @class
9550 * @extends OO.ui.Layout
9551 *
9552 * @constructor
9553 * @param {Object} [config] Configuration options
9554 * @cfg {boolean} [showMenu=true] Show menu
9555 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9556 */
9557 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9558 // Configuration initialization
9559 config = $.extend( {
9560 showMenu: true,
9561 menuPosition: 'before'
9562 }, config );
9563
9564 // Parent constructor
9565 OO.ui.MenuLayout.parent.call( this, config );
9566
9567 /**
9568 * Menu DOM node
9569 *
9570 * @property {jQuery}
9571 */
9572 this.$menu = $( '<div>' );
9573 /**
9574 * Content DOM node
9575 *
9576 * @property {jQuery}
9577 */
9578 this.$content = $( '<div>' );
9579
9580 // Initialization
9581 this.$menu
9582 .addClass( 'oo-ui-menuLayout-menu' );
9583 this.$content.addClass( 'oo-ui-menuLayout-content' );
9584 this.$element
9585 .addClass( 'oo-ui-menuLayout' )
9586 .append( this.$content, this.$menu );
9587 this.setMenuPosition( config.menuPosition );
9588 this.toggleMenu( config.showMenu );
9589 };
9590
9591 /* Setup */
9592
9593 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9594
9595 /* Methods */
9596
9597 /**
9598 * Toggle menu.
9599 *
9600 * @param {boolean} showMenu Show menu, omit to toggle
9601 * @chainable
9602 */
9603 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9604 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9605
9606 if ( this.showMenu !== showMenu ) {
9607 this.showMenu = showMenu;
9608 this.$element
9609 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9610 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9611 }
9612
9613 return this;
9614 };
9615
9616 /**
9617 * Check if menu is visible
9618 *
9619 * @return {boolean} Menu is visible
9620 */
9621 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9622 return this.showMenu;
9623 };
9624
9625 /**
9626 * Set menu position.
9627 *
9628 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9629 * @throws {Error} If position value is not supported
9630 * @chainable
9631 */
9632 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9633 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9634 this.menuPosition = position;
9635 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9636
9637 return this;
9638 };
9639
9640 /**
9641 * Get menu position.
9642 *
9643 * @return {string} Menu position
9644 */
9645 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9646 return this.menuPosition;
9647 };
9648
9649 /**
9650 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9651 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9652 * through the pages and select which one to display. By default, only one page is
9653 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9654 * the booklet layout automatically focuses on the first focusable element, unless the
9655 * default setting is changed. Optionally, booklets can be configured to show
9656 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9657 *
9658 * @example
9659 * // Example of a BookletLayout that contains two PageLayouts.
9660 *
9661 * function PageOneLayout( name, config ) {
9662 * PageOneLayout.parent.call( this, name, config );
9663 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9664 * }
9665 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9666 * PageOneLayout.prototype.setupOutlineItem = function () {
9667 * this.outlineItem.setLabel( 'Page One' );
9668 * };
9669 *
9670 * function PageTwoLayout( name, config ) {
9671 * PageTwoLayout.parent.call( this, name, config );
9672 * this.$element.append( '<p>Second page</p>' );
9673 * }
9674 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9675 * PageTwoLayout.prototype.setupOutlineItem = function () {
9676 * this.outlineItem.setLabel( 'Page Two' );
9677 * };
9678 *
9679 * var page1 = new PageOneLayout( 'one' ),
9680 * page2 = new PageTwoLayout( 'two' );
9681 *
9682 * var booklet = new OO.ui.BookletLayout( {
9683 * outlined: true
9684 * } );
9685 *
9686 * booklet.addPages ( [ page1, page2 ] );
9687 * $( 'body' ).append( booklet.$element );
9688 *
9689 * @class
9690 * @extends OO.ui.MenuLayout
9691 *
9692 * @constructor
9693 * @param {Object} [config] Configuration options
9694 * @cfg {boolean} [continuous=false] Show all pages, one after another
9695 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9696 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9697 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9698 */
9699 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9700 // Configuration initialization
9701 config = config || {};
9702
9703 // Parent constructor
9704 OO.ui.BookletLayout.parent.call( this, config );
9705
9706 // Properties
9707 this.currentPageName = null;
9708 this.pages = {};
9709 this.ignoreFocus = false;
9710 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9711 this.$content.append( this.stackLayout.$element );
9712 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9713 this.outlineVisible = false;
9714 this.outlined = !!config.outlined;
9715 if ( this.outlined ) {
9716 this.editable = !!config.editable;
9717 this.outlineControlsWidget = null;
9718 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9719 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9720 this.$menu.append( this.outlinePanel.$element );
9721 this.outlineVisible = true;
9722 if ( this.editable ) {
9723 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9724 this.outlineSelectWidget
9725 );
9726 }
9727 }
9728 this.toggleMenu( this.outlined );
9729
9730 // Events
9731 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9732 if ( this.outlined ) {
9733 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9734 this.scrolling = false;
9735 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9736 }
9737 if ( this.autoFocus ) {
9738 // Event 'focus' does not bubble, but 'focusin' does
9739 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9740 }
9741
9742 // Initialization
9743 this.$element.addClass( 'oo-ui-bookletLayout' );
9744 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9745 if ( this.outlined ) {
9746 this.outlinePanel.$element
9747 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9748 .append( this.outlineSelectWidget.$element );
9749 if ( this.editable ) {
9750 this.outlinePanel.$element
9751 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9752 .append( this.outlineControlsWidget.$element );
9753 }
9754 }
9755 };
9756
9757 /* Setup */
9758
9759 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9760
9761 /* Events */
9762
9763 /**
9764 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9765 * @event set
9766 * @param {OO.ui.PageLayout} page Current page
9767 */
9768
9769 /**
9770 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9771 *
9772 * @event add
9773 * @param {OO.ui.PageLayout[]} page Added pages
9774 * @param {number} index Index pages were added at
9775 */
9776
9777 /**
9778 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9779 * {@link #removePages removed} from the booklet.
9780 *
9781 * @event remove
9782 * @param {OO.ui.PageLayout[]} pages Removed pages
9783 */
9784
9785 /* Methods */
9786
9787 /**
9788 * Handle stack layout focus.
9789 *
9790 * @private
9791 * @param {jQuery.Event} e Focusin event
9792 */
9793 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9794 var name, $target;
9795
9796 // Find the page that an element was focused within
9797 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9798 for ( name in this.pages ) {
9799 // Check for page match, exclude current page to find only page changes
9800 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9801 this.setPage( name );
9802 break;
9803 }
9804 }
9805 };
9806
9807 /**
9808 * Handle visibleItemChange events from the stackLayout
9809 *
9810 * The next visible page is set as the current page by selecting it
9811 * in the outline
9812 *
9813 * @param {OO.ui.PageLayout} page The next visible page in the layout
9814 */
9815 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
9816 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9817 // try and scroll the item into view again.
9818 this.scrolling = true;
9819 this.outlineSelectWidget.selectItemByData( page.getName() );
9820 this.scrolling = false;
9821 };
9822
9823 /**
9824 * Handle stack layout set events.
9825 *
9826 * @private
9827 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9828 */
9829 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9830 var layout = this;
9831 if ( !this.scrolling && page ) {
9832 page.scrollElementIntoView( { complete: function () {
9833 if ( layout.autoFocus ) {
9834 layout.focus();
9835 }
9836 } } );
9837 }
9838 };
9839
9840 /**
9841 * Focus the first input in the current page.
9842 *
9843 * If no page is selected, the first selectable page will be selected.
9844 * If the focus is already in an element on the current page, nothing will happen.
9845 * @param {number} [itemIndex] A specific item to focus on
9846 */
9847 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9848 var page,
9849 items = this.stackLayout.getItems();
9850
9851 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9852 page = items[ itemIndex ];
9853 } else {
9854 page = this.stackLayout.getCurrentItem();
9855 }
9856
9857 if ( !page && this.outlined ) {
9858 this.selectFirstSelectablePage();
9859 page = this.stackLayout.getCurrentItem();
9860 }
9861 if ( !page ) {
9862 return;
9863 }
9864 // Only change the focus if is not already in the current page
9865 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
9866 page.focus();
9867 }
9868 };
9869
9870 /**
9871 * Find the first focusable input in the booklet layout and focus
9872 * on it.
9873 */
9874 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9875 OO.ui.findFocusable( this.stackLayout.$element ).focus();
9876 };
9877
9878 /**
9879 * Handle outline widget select events.
9880 *
9881 * @private
9882 * @param {OO.ui.OptionWidget|null} item Selected item
9883 */
9884 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9885 if ( item ) {
9886 this.setPage( item.getData() );
9887 }
9888 };
9889
9890 /**
9891 * Check if booklet has an outline.
9892 *
9893 * @return {boolean} Booklet has an outline
9894 */
9895 OO.ui.BookletLayout.prototype.isOutlined = function () {
9896 return this.outlined;
9897 };
9898
9899 /**
9900 * Check if booklet has editing controls.
9901 *
9902 * @return {boolean} Booklet is editable
9903 */
9904 OO.ui.BookletLayout.prototype.isEditable = function () {
9905 return this.editable;
9906 };
9907
9908 /**
9909 * Check if booklet has a visible outline.
9910 *
9911 * @return {boolean} Outline is visible
9912 */
9913 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9914 return this.outlined && this.outlineVisible;
9915 };
9916
9917 /**
9918 * Hide or show the outline.
9919 *
9920 * @param {boolean} [show] Show outline, omit to invert current state
9921 * @chainable
9922 */
9923 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9924 if ( this.outlined ) {
9925 show = show === undefined ? !this.outlineVisible : !!show;
9926 this.outlineVisible = show;
9927 this.toggleMenu( show );
9928 }
9929
9930 return this;
9931 };
9932
9933 /**
9934 * Get the page closest to the specified page.
9935 *
9936 * @param {OO.ui.PageLayout} page Page to use as a reference point
9937 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9938 */
9939 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9940 var next, prev, level,
9941 pages = this.stackLayout.getItems(),
9942 index = pages.indexOf( page );
9943
9944 if ( index !== -1 ) {
9945 next = pages[ index + 1 ];
9946 prev = pages[ index - 1 ];
9947 // Prefer adjacent pages at the same level
9948 if ( this.outlined ) {
9949 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9950 if (
9951 prev &&
9952 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9953 ) {
9954 return prev;
9955 }
9956 if (
9957 next &&
9958 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9959 ) {
9960 return next;
9961 }
9962 }
9963 }
9964 return prev || next || null;
9965 };
9966
9967 /**
9968 * Get the outline widget.
9969 *
9970 * If the booklet is not outlined, the method will return `null`.
9971 *
9972 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9973 */
9974 OO.ui.BookletLayout.prototype.getOutline = function () {
9975 return this.outlineSelectWidget;
9976 };
9977
9978 /**
9979 * Get the outline controls widget.
9980 *
9981 * If the outline is not editable, the method will return `null`.
9982 *
9983 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9984 */
9985 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9986 return this.outlineControlsWidget;
9987 };
9988
9989 /**
9990 * Get a page by its symbolic name.
9991 *
9992 * @param {string} name Symbolic name of page
9993 * @return {OO.ui.PageLayout|undefined} Page, if found
9994 */
9995 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9996 return this.pages[ name ];
9997 };
9998
9999 /**
10000 * Get the current page.
10001 *
10002 * @return {OO.ui.PageLayout|undefined} Current page, if found
10003 */
10004 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10005 var name = this.getCurrentPageName();
10006 return name ? this.getPage( name ) : undefined;
10007 };
10008
10009 /**
10010 * Get the symbolic name of the current page.
10011 *
10012 * @return {string|null} Symbolic name of the current page
10013 */
10014 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10015 return this.currentPageName;
10016 };
10017
10018 /**
10019 * Add pages to the booklet layout
10020 *
10021 * When pages are added with the same names as existing pages, the existing pages will be
10022 * automatically removed before the new pages are added.
10023 *
10024 * @param {OO.ui.PageLayout[]} pages Pages to add
10025 * @param {number} index Index of the insertion point
10026 * @fires add
10027 * @chainable
10028 */
10029 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10030 var i, len, name, page, item, currentIndex,
10031 stackLayoutPages = this.stackLayout.getItems(),
10032 remove = [],
10033 items = [];
10034
10035 // Remove pages with same names
10036 for ( i = 0, len = pages.length; i < len; i++ ) {
10037 page = pages[ i ];
10038 name = page.getName();
10039
10040 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10041 // Correct the insertion index
10042 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10043 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10044 index--;
10045 }
10046 remove.push( this.pages[ name ] );
10047 }
10048 }
10049 if ( remove.length ) {
10050 this.removePages( remove );
10051 }
10052
10053 // Add new pages
10054 for ( i = 0, len = pages.length; i < len; i++ ) {
10055 page = pages[ i ];
10056 name = page.getName();
10057 this.pages[ page.getName() ] = page;
10058 if ( this.outlined ) {
10059 item = new OO.ui.OutlineOptionWidget( { data: name } );
10060 page.setOutlineItem( item );
10061 items.push( item );
10062 }
10063 }
10064
10065 if ( this.outlined && items.length ) {
10066 this.outlineSelectWidget.addItems( items, index );
10067 this.selectFirstSelectablePage();
10068 }
10069 this.stackLayout.addItems( pages, index );
10070 this.emit( 'add', pages, index );
10071
10072 return this;
10073 };
10074
10075 /**
10076 * Remove the specified pages from the booklet layout.
10077 *
10078 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10079 *
10080 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10081 * @fires remove
10082 * @chainable
10083 */
10084 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10085 var i, len, name, page,
10086 items = [];
10087
10088 for ( i = 0, len = pages.length; i < len; i++ ) {
10089 page = pages[ i ];
10090 name = page.getName();
10091 delete this.pages[ name ];
10092 if ( this.outlined ) {
10093 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10094 page.setOutlineItem( null );
10095 }
10096 }
10097 if ( this.outlined && items.length ) {
10098 this.outlineSelectWidget.removeItems( items );
10099 this.selectFirstSelectablePage();
10100 }
10101 this.stackLayout.removeItems( pages );
10102 this.emit( 'remove', pages );
10103
10104 return this;
10105 };
10106
10107 /**
10108 * Clear all pages from the booklet layout.
10109 *
10110 * To remove only a subset of pages from the booklet, use the #removePages method.
10111 *
10112 * @fires remove
10113 * @chainable
10114 */
10115 OO.ui.BookletLayout.prototype.clearPages = function () {
10116 var i, len,
10117 pages = this.stackLayout.getItems();
10118
10119 this.pages = {};
10120 this.currentPageName = null;
10121 if ( this.outlined ) {
10122 this.outlineSelectWidget.clearItems();
10123 for ( i = 0, len = pages.length; i < len; i++ ) {
10124 pages[ i ].setOutlineItem( null );
10125 }
10126 }
10127 this.stackLayout.clearItems();
10128
10129 this.emit( 'remove', pages );
10130
10131 return this;
10132 };
10133
10134 /**
10135 * Set the current page by symbolic name.
10136 *
10137 * @fires set
10138 * @param {string} name Symbolic name of page
10139 */
10140 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10141 var selectedItem,
10142 $focused,
10143 page = this.pages[ name ],
10144 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10145
10146 if ( name !== this.currentPageName ) {
10147 if ( this.outlined ) {
10148 selectedItem = this.outlineSelectWidget.getSelectedItem();
10149 if ( selectedItem && selectedItem.getData() !== name ) {
10150 this.outlineSelectWidget.selectItemByData( name );
10151 }
10152 }
10153 if ( page ) {
10154 if ( previousPage ) {
10155 previousPage.setActive( false );
10156 // Blur anything focused if the next page doesn't have anything focusable.
10157 // This is not needed if the next page has something focusable (because once it is focused
10158 // this blur happens automatically). If the layout is non-continuous, this check is
10159 // meaningless because the next page is not visible yet and thus can't hold focus.
10160 if (
10161 this.autoFocus &&
10162 this.stackLayout.continuous &&
10163 OO.ui.findFocusable( page.$element ).length !== 0
10164 ) {
10165 $focused = previousPage.$element.find( ':focus' );
10166 if ( $focused.length ) {
10167 $focused[ 0 ].blur();
10168 }
10169 }
10170 }
10171 this.currentPageName = name;
10172 page.setActive( true );
10173 this.stackLayout.setItem( page );
10174 if ( !this.stackLayout.continuous && previousPage ) {
10175 // This should not be necessary, since any inputs on the previous page should have been
10176 // blurred when it was hidden, but browsers are not very consistent about this.
10177 $focused = previousPage.$element.find( ':focus' );
10178 if ( $focused.length ) {
10179 $focused[ 0 ].blur();
10180 }
10181 }
10182 this.emit( 'set', page );
10183 }
10184 }
10185 };
10186
10187 /**
10188 * Select the first selectable page.
10189 *
10190 * @chainable
10191 */
10192 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10193 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10194 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10195 }
10196
10197 return this;
10198 };
10199
10200 /**
10201 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10202 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10203 * select which one to display. By default, only one card is displayed at a time. When a user
10204 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10205 * unless the default setting is changed.
10206 *
10207 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10208 *
10209 * @example
10210 * // Example of a IndexLayout that contains two CardLayouts.
10211 *
10212 * function CardOneLayout( name, config ) {
10213 * CardOneLayout.parent.call( this, name, config );
10214 * this.$element.append( '<p>First card</p>' );
10215 * }
10216 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10217 * CardOneLayout.prototype.setupTabItem = function () {
10218 * this.tabItem.setLabel( 'Card one' );
10219 * };
10220 *
10221 * var card1 = new CardOneLayout( 'one' ),
10222 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10223 *
10224 * card2.$element.append( '<p>Second card</p>' );
10225 *
10226 * var index = new OO.ui.IndexLayout();
10227 *
10228 * index.addCards ( [ card1, card2 ] );
10229 * $( 'body' ).append( index.$element );
10230 *
10231 * @class
10232 * @extends OO.ui.MenuLayout
10233 *
10234 * @constructor
10235 * @param {Object} [config] Configuration options
10236 * @cfg {boolean} [continuous=false] Show all cards, one after another
10237 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10238 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10239 */
10240 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10241 // Configuration initialization
10242 config = $.extend( {}, config, { menuPosition: 'top' } );
10243
10244 // Parent constructor
10245 OO.ui.IndexLayout.parent.call( this, config );
10246
10247 // Properties
10248 this.currentCardName = null;
10249 this.cards = {};
10250 this.ignoreFocus = false;
10251 this.stackLayout = new OO.ui.StackLayout( {
10252 continuous: !!config.continuous,
10253 expanded: config.expanded
10254 } );
10255 this.$content.append( this.stackLayout.$element );
10256 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10257
10258 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10259 this.tabPanel = new OO.ui.PanelLayout();
10260 this.$menu.append( this.tabPanel.$element );
10261
10262 this.toggleMenu( true );
10263
10264 // Events
10265 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10266 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10267 if ( this.autoFocus ) {
10268 // Event 'focus' does not bubble, but 'focusin' does
10269 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10270 }
10271
10272 // Initialization
10273 this.$element.addClass( 'oo-ui-indexLayout' );
10274 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10275 this.tabPanel.$element
10276 .addClass( 'oo-ui-indexLayout-tabPanel' )
10277 .append( this.tabSelectWidget.$element );
10278 };
10279
10280 /* Setup */
10281
10282 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10283
10284 /* Events */
10285
10286 /**
10287 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10288 * @event set
10289 * @param {OO.ui.CardLayout} card Current card
10290 */
10291
10292 /**
10293 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10294 *
10295 * @event add
10296 * @param {OO.ui.CardLayout[]} card Added cards
10297 * @param {number} index Index cards were added at
10298 */
10299
10300 /**
10301 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10302 * {@link #removeCards removed} from the index.
10303 *
10304 * @event remove
10305 * @param {OO.ui.CardLayout[]} cards Removed cards
10306 */
10307
10308 /* Methods */
10309
10310 /**
10311 * Handle stack layout focus.
10312 *
10313 * @private
10314 * @param {jQuery.Event} e Focusin event
10315 */
10316 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10317 var name, $target;
10318
10319 // Find the card that an element was focused within
10320 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10321 for ( name in this.cards ) {
10322 // Check for card match, exclude current card to find only card changes
10323 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10324 this.setCard( name );
10325 break;
10326 }
10327 }
10328 };
10329
10330 /**
10331 * Handle stack layout set events.
10332 *
10333 * @private
10334 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10335 */
10336 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10337 var layout = this;
10338 if ( card ) {
10339 card.scrollElementIntoView( { complete: function () {
10340 if ( layout.autoFocus ) {
10341 layout.focus();
10342 }
10343 } } );
10344 }
10345 };
10346
10347 /**
10348 * Focus the first input in the current card.
10349 *
10350 * If no card is selected, the first selectable card will be selected.
10351 * If the focus is already in an element on the current card, nothing will happen.
10352 * @param {number} [itemIndex] A specific item to focus on
10353 */
10354 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10355 var card,
10356 items = this.stackLayout.getItems();
10357
10358 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10359 card = items[ itemIndex ];
10360 } else {
10361 card = this.stackLayout.getCurrentItem();
10362 }
10363
10364 if ( !card ) {
10365 this.selectFirstSelectableCard();
10366 card = this.stackLayout.getCurrentItem();
10367 }
10368 if ( !card ) {
10369 return;
10370 }
10371 // Only change the focus if is not already in the current page
10372 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10373 card.focus();
10374 }
10375 };
10376
10377 /**
10378 * Find the first focusable input in the index layout and focus
10379 * on it.
10380 */
10381 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10382 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10383 };
10384
10385 /**
10386 * Handle tab widget select events.
10387 *
10388 * @private
10389 * @param {OO.ui.OptionWidget|null} item Selected item
10390 */
10391 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10392 if ( item ) {
10393 this.setCard( item.getData() );
10394 }
10395 };
10396
10397 /**
10398 * Get the card closest to the specified card.
10399 *
10400 * @param {OO.ui.CardLayout} card Card to use as a reference point
10401 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10402 */
10403 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10404 var next, prev, level,
10405 cards = this.stackLayout.getItems(),
10406 index = cards.indexOf( card );
10407
10408 if ( index !== -1 ) {
10409 next = cards[ index + 1 ];
10410 prev = cards[ index - 1 ];
10411 // Prefer adjacent cards at the same level
10412 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10413 if (
10414 prev &&
10415 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10416 ) {
10417 return prev;
10418 }
10419 if (
10420 next &&
10421 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10422 ) {
10423 return next;
10424 }
10425 }
10426 return prev || next || null;
10427 };
10428
10429 /**
10430 * Get the tabs widget.
10431 *
10432 * @return {OO.ui.TabSelectWidget} Tabs widget
10433 */
10434 OO.ui.IndexLayout.prototype.getTabs = function () {
10435 return this.tabSelectWidget;
10436 };
10437
10438 /**
10439 * Get a card by its symbolic name.
10440 *
10441 * @param {string} name Symbolic name of card
10442 * @return {OO.ui.CardLayout|undefined} Card, if found
10443 */
10444 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10445 return this.cards[ name ];
10446 };
10447
10448 /**
10449 * Get the current card.
10450 *
10451 * @return {OO.ui.CardLayout|undefined} Current card, if found
10452 */
10453 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10454 var name = this.getCurrentCardName();
10455 return name ? this.getCard( name ) : undefined;
10456 };
10457
10458 /**
10459 * Get the symbolic name of the current card.
10460 *
10461 * @return {string|null} Symbolic name of the current card
10462 */
10463 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10464 return this.currentCardName;
10465 };
10466
10467 /**
10468 * Add cards to the index layout
10469 *
10470 * When cards are added with the same names as existing cards, the existing cards will be
10471 * automatically removed before the new cards are added.
10472 *
10473 * @param {OO.ui.CardLayout[]} cards Cards to add
10474 * @param {number} index Index of the insertion point
10475 * @fires add
10476 * @chainable
10477 */
10478 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10479 var i, len, name, card, item, currentIndex,
10480 stackLayoutCards = this.stackLayout.getItems(),
10481 remove = [],
10482 items = [];
10483
10484 // Remove cards with same names
10485 for ( i = 0, len = cards.length; i < len; i++ ) {
10486 card = cards[ i ];
10487 name = card.getName();
10488
10489 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10490 // Correct the insertion index
10491 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10492 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10493 index--;
10494 }
10495 remove.push( this.cards[ name ] );
10496 }
10497 }
10498 if ( remove.length ) {
10499 this.removeCards( remove );
10500 }
10501
10502 // Add new cards
10503 for ( i = 0, len = cards.length; i < len; i++ ) {
10504 card = cards[ i ];
10505 name = card.getName();
10506 this.cards[ card.getName() ] = card;
10507 item = new OO.ui.TabOptionWidget( { data: name } );
10508 card.setTabItem( item );
10509 items.push( item );
10510 }
10511
10512 if ( items.length ) {
10513 this.tabSelectWidget.addItems( items, index );
10514 this.selectFirstSelectableCard();
10515 }
10516 this.stackLayout.addItems( cards, index );
10517 this.emit( 'add', cards, index );
10518
10519 return this;
10520 };
10521
10522 /**
10523 * Remove the specified cards from the index layout.
10524 *
10525 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10526 *
10527 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10528 * @fires remove
10529 * @chainable
10530 */
10531 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10532 var i, len, name, card,
10533 items = [];
10534
10535 for ( i = 0, len = cards.length; i < len; i++ ) {
10536 card = cards[ i ];
10537 name = card.getName();
10538 delete this.cards[ name ];
10539 items.push( this.tabSelectWidget.getItemFromData( name ) );
10540 card.setTabItem( null );
10541 }
10542 if ( items.length ) {
10543 this.tabSelectWidget.removeItems( items );
10544 this.selectFirstSelectableCard();
10545 }
10546 this.stackLayout.removeItems( cards );
10547 this.emit( 'remove', cards );
10548
10549 return this;
10550 };
10551
10552 /**
10553 * Clear all cards from the index layout.
10554 *
10555 * To remove only a subset of cards from the index, use the #removeCards method.
10556 *
10557 * @fires remove
10558 * @chainable
10559 */
10560 OO.ui.IndexLayout.prototype.clearCards = function () {
10561 var i, len,
10562 cards = this.stackLayout.getItems();
10563
10564 this.cards = {};
10565 this.currentCardName = null;
10566 this.tabSelectWidget.clearItems();
10567 for ( i = 0, len = cards.length; i < len; i++ ) {
10568 cards[ i ].setTabItem( null );
10569 }
10570 this.stackLayout.clearItems();
10571
10572 this.emit( 'remove', cards );
10573
10574 return this;
10575 };
10576
10577 /**
10578 * Set the current card by symbolic name.
10579 *
10580 * @fires set
10581 * @param {string} name Symbolic name of card
10582 */
10583 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10584 var selectedItem,
10585 $focused,
10586 card = this.cards[ name ],
10587 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10588
10589 if ( name !== this.currentCardName ) {
10590 selectedItem = this.tabSelectWidget.getSelectedItem();
10591 if ( selectedItem && selectedItem.getData() !== name ) {
10592 this.tabSelectWidget.selectItemByData( name );
10593 }
10594 if ( card ) {
10595 if ( previousCard ) {
10596 previousCard.setActive( false );
10597 // Blur anything focused if the next card doesn't have anything focusable.
10598 // This is not needed if the next card has something focusable (because once it is focused
10599 // this blur happens automatically). If the layout is non-continuous, this check is
10600 // meaningless because the next card is not visible yet and thus can't hold focus.
10601 if (
10602 this.autoFocus &&
10603 this.stackLayout.continuous &&
10604 OO.ui.findFocusable( card.$element ).length !== 0
10605 ) {
10606 $focused = previousCard.$element.find( ':focus' );
10607 if ( $focused.length ) {
10608 $focused[ 0 ].blur();
10609 }
10610 }
10611 }
10612 this.currentCardName = name;
10613 card.setActive( true );
10614 this.stackLayout.setItem( card );
10615 if ( !this.stackLayout.continuous && previousCard ) {
10616 // This should not be necessary, since any inputs on the previous card should have been
10617 // blurred when it was hidden, but browsers are not very consistent about this.
10618 $focused = previousCard.$element.find( ':focus' );
10619 if ( $focused.length ) {
10620 $focused[ 0 ].blur();
10621 }
10622 }
10623 this.emit( 'set', card );
10624 }
10625 }
10626 };
10627
10628 /**
10629 * Select the first selectable card.
10630 *
10631 * @chainable
10632 */
10633 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10634 if ( !this.tabSelectWidget.getSelectedItem() ) {
10635 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10636 }
10637
10638 return this;
10639 };
10640
10641 /**
10642 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10643 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10644 *
10645 * @example
10646 * // Example of a panel layout
10647 * var panel = new OO.ui.PanelLayout( {
10648 * expanded: false,
10649 * framed: true,
10650 * padded: true,
10651 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10652 * } );
10653 * $( 'body' ).append( panel.$element );
10654 *
10655 * @class
10656 * @extends OO.ui.Layout
10657 *
10658 * @constructor
10659 * @param {Object} [config] Configuration options
10660 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10661 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10662 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10663 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10664 */
10665 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10666 // Configuration initialization
10667 config = $.extend( {
10668 scrollable: false,
10669 padded: false,
10670 expanded: true,
10671 framed: false
10672 }, config );
10673
10674 // Parent constructor
10675 OO.ui.PanelLayout.parent.call( this, config );
10676
10677 // Initialization
10678 this.$element.addClass( 'oo-ui-panelLayout' );
10679 if ( config.scrollable ) {
10680 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10681 }
10682 if ( config.padded ) {
10683 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10684 }
10685 if ( config.expanded ) {
10686 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10687 }
10688 if ( config.framed ) {
10689 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10690 }
10691 };
10692
10693 /* Setup */
10694
10695 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10696
10697 /* Methods */
10698
10699 /**
10700 * Focus the panel layout
10701 *
10702 * The default implementation just focuses the first focusable element in the panel
10703 */
10704 OO.ui.PanelLayout.prototype.focus = function () {
10705 OO.ui.findFocusable( this.$element ).focus();
10706 };
10707
10708 /**
10709 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10710 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10711 * rather extended to include the required content and functionality.
10712 *
10713 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10714 * item is customized (with a label) using the #setupTabItem method. See
10715 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10716 *
10717 * @class
10718 * @extends OO.ui.PanelLayout
10719 *
10720 * @constructor
10721 * @param {string} name Unique symbolic name of card
10722 * @param {Object} [config] Configuration options
10723 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10724 */
10725 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10726 // Allow passing positional parameters inside the config object
10727 if ( OO.isPlainObject( name ) && config === undefined ) {
10728 config = name;
10729 name = config.name;
10730 }
10731
10732 // Configuration initialization
10733 config = $.extend( { scrollable: true }, config );
10734
10735 // Parent constructor
10736 OO.ui.CardLayout.parent.call( this, config );
10737
10738 // Properties
10739 this.name = name;
10740 this.label = config.label;
10741 this.tabItem = null;
10742 this.active = false;
10743
10744 // Initialization
10745 this.$element.addClass( 'oo-ui-cardLayout' );
10746 };
10747
10748 /* Setup */
10749
10750 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10751
10752 /* Events */
10753
10754 /**
10755 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10756 * shown in a index layout that is configured to display only one card at a time.
10757 *
10758 * @event active
10759 * @param {boolean} active Card is active
10760 */
10761
10762 /* Methods */
10763
10764 /**
10765 * Get the symbolic name of the card.
10766 *
10767 * @return {string} Symbolic name of card
10768 */
10769 OO.ui.CardLayout.prototype.getName = function () {
10770 return this.name;
10771 };
10772
10773 /**
10774 * Check if card is active.
10775 *
10776 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10777 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10778 *
10779 * @return {boolean} Card is active
10780 */
10781 OO.ui.CardLayout.prototype.isActive = function () {
10782 return this.active;
10783 };
10784
10785 /**
10786 * Get tab item.
10787 *
10788 * The tab item allows users to access the card from the index's tab
10789 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10790 *
10791 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10792 */
10793 OO.ui.CardLayout.prototype.getTabItem = function () {
10794 return this.tabItem;
10795 };
10796
10797 /**
10798 * Set or unset the tab item.
10799 *
10800 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10801 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10802 * level), use #setupTabItem instead of this method.
10803 *
10804 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10805 * @chainable
10806 */
10807 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10808 this.tabItem = tabItem || null;
10809 if ( tabItem ) {
10810 this.setupTabItem();
10811 }
10812 return this;
10813 };
10814
10815 /**
10816 * Set up the tab item.
10817 *
10818 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10819 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10820 * the #setTabItem method instead.
10821 *
10822 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10823 * @chainable
10824 */
10825 OO.ui.CardLayout.prototype.setupTabItem = function () {
10826 if ( this.label ) {
10827 this.tabItem.setLabel( this.label );
10828 }
10829 return this;
10830 };
10831
10832 /**
10833 * Set the card to its 'active' state.
10834 *
10835 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10836 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10837 * context, setting the active state on a card does nothing.
10838 *
10839 * @param {boolean} value Card is active
10840 * @fires active
10841 */
10842 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10843 active = !!active;
10844
10845 if ( active !== this.active ) {
10846 this.active = active;
10847 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10848 this.emit( 'active', this.active );
10849 }
10850 };
10851
10852 /**
10853 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10854 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10855 * rather extended to include the required content and functionality.
10856 *
10857 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10858 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10859 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10860 *
10861 * @class
10862 * @extends OO.ui.PanelLayout
10863 *
10864 * @constructor
10865 * @param {string} name Unique symbolic name of page
10866 * @param {Object} [config] Configuration options
10867 */
10868 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10869 // Allow passing positional parameters inside the config object
10870 if ( OO.isPlainObject( name ) && config === undefined ) {
10871 config = name;
10872 name = config.name;
10873 }
10874
10875 // Configuration initialization
10876 config = $.extend( { scrollable: true }, config );
10877
10878 // Parent constructor
10879 OO.ui.PageLayout.parent.call( this, config );
10880
10881 // Properties
10882 this.name = name;
10883 this.outlineItem = null;
10884 this.active = false;
10885
10886 // Initialization
10887 this.$element.addClass( 'oo-ui-pageLayout' );
10888 };
10889
10890 /* Setup */
10891
10892 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10893
10894 /* Events */
10895
10896 /**
10897 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10898 * shown in a booklet layout that is configured to display only one page at a time.
10899 *
10900 * @event active
10901 * @param {boolean} active Page is active
10902 */
10903
10904 /* Methods */
10905
10906 /**
10907 * Get the symbolic name of the page.
10908 *
10909 * @return {string} Symbolic name of page
10910 */
10911 OO.ui.PageLayout.prototype.getName = function () {
10912 return this.name;
10913 };
10914
10915 /**
10916 * Check if page is active.
10917 *
10918 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10919 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10920 *
10921 * @return {boolean} Page is active
10922 */
10923 OO.ui.PageLayout.prototype.isActive = function () {
10924 return this.active;
10925 };
10926
10927 /**
10928 * Get outline item.
10929 *
10930 * The outline item allows users to access the page from the booklet's outline
10931 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10932 *
10933 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10934 */
10935 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10936 return this.outlineItem;
10937 };
10938
10939 /**
10940 * Set or unset the outline item.
10941 *
10942 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10943 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10944 * level), use #setupOutlineItem instead of this method.
10945 *
10946 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10947 * @chainable
10948 */
10949 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10950 this.outlineItem = outlineItem || null;
10951 if ( outlineItem ) {
10952 this.setupOutlineItem();
10953 }
10954 return this;
10955 };
10956
10957 /**
10958 * Set up the outline item.
10959 *
10960 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10961 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10962 * the #setOutlineItem method instead.
10963 *
10964 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10965 * @chainable
10966 */
10967 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10968 return this;
10969 };
10970
10971 /**
10972 * Set the page to its 'active' state.
10973 *
10974 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10975 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10976 * context, setting the active state on a page does nothing.
10977 *
10978 * @param {boolean} value Page is active
10979 * @fires active
10980 */
10981 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10982 active = !!active;
10983
10984 if ( active !== this.active ) {
10985 this.active = active;
10986 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10987 this.emit( 'active', this.active );
10988 }
10989 };
10990
10991 /**
10992 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10993 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10994 * by setting the #continuous option to 'true'.
10995 *
10996 * @example
10997 * // A stack layout with two panels, configured to be displayed continously
10998 * var myStack = new OO.ui.StackLayout( {
10999 * items: [
11000 * new OO.ui.PanelLayout( {
11001 * $content: $( '<p>Panel One</p>' ),
11002 * padded: true,
11003 * framed: true
11004 * } ),
11005 * new OO.ui.PanelLayout( {
11006 * $content: $( '<p>Panel Two</p>' ),
11007 * padded: true,
11008 * framed: true
11009 * } )
11010 * ],
11011 * continuous: true
11012 * } );
11013 * $( 'body' ).append( myStack.$element );
11014 *
11015 * @class
11016 * @extends OO.ui.PanelLayout
11017 * @mixins OO.ui.mixin.GroupElement
11018 *
11019 * @constructor
11020 * @param {Object} [config] Configuration options
11021 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11022 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11023 */
11024 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11025 // Configuration initialization
11026 config = $.extend( { scrollable: true }, config );
11027
11028 // Parent constructor
11029 OO.ui.StackLayout.parent.call( this, config );
11030
11031 // Mixin constructors
11032 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11033
11034 // Properties
11035 this.currentItem = null;
11036 this.continuous = !!config.continuous;
11037
11038 // Initialization
11039 this.$element.addClass( 'oo-ui-stackLayout' );
11040 if ( this.continuous ) {
11041 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11042 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11043 }
11044 if ( Array.isArray( config.items ) ) {
11045 this.addItems( config.items );
11046 }
11047 };
11048
11049 /* Setup */
11050
11051 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11052 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11053
11054 /* Events */
11055
11056 /**
11057 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11058 * {@link #clearItems cleared} or {@link #setItem displayed}.
11059 *
11060 * @event set
11061 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11062 */
11063
11064 /**
11065 * When used in continuous mode, this event is emitted when the user scrolls down
11066 * far enough such that currentItem is no longer visible.
11067 *
11068 * @event visibleItemChange
11069 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11070 */
11071
11072 /* Methods */
11073
11074 /**
11075 * Handle scroll events from the layout element
11076 *
11077 * @param {jQuery.Event} e
11078 * @fires visibleItemChange
11079 */
11080 OO.ui.StackLayout.prototype.onScroll = function () {
11081 var currentRect,
11082 len = this.items.length,
11083 currentIndex = this.items.indexOf( this.currentItem ),
11084 newIndex = currentIndex,
11085 containerRect = this.$element[ 0 ].getBoundingClientRect();
11086
11087 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11088 // Can't get bounding rect, possibly not attached.
11089 return;
11090 }
11091
11092 function getRect( item ) {
11093 return item.$element[ 0 ].getBoundingClientRect();
11094 }
11095
11096 function isVisible( item ) {
11097 var rect = getRect( item );
11098 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11099 }
11100
11101 currentRect = getRect( this.currentItem );
11102
11103 if ( currentRect.bottom < containerRect.top ) {
11104 // Scrolled down past current item
11105 while ( ++newIndex < len ) {
11106 if ( isVisible( this.items[ newIndex ] ) ) {
11107 break;
11108 }
11109 }
11110 } else if ( currentRect.top > containerRect.bottom ) {
11111 // Scrolled up past current item
11112 while ( --newIndex >= 0 ) {
11113 if ( isVisible( this.items[ newIndex ] ) ) {
11114 break;
11115 }
11116 }
11117 }
11118
11119 if ( newIndex !== currentIndex ) {
11120 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11121 }
11122 };
11123
11124 /**
11125 * Get the current panel.
11126 *
11127 * @return {OO.ui.Layout|null}
11128 */
11129 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11130 return this.currentItem;
11131 };
11132
11133 /**
11134 * Unset the current item.
11135 *
11136 * @private
11137 * @param {OO.ui.StackLayout} layout
11138 * @fires set
11139 */
11140 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11141 var prevItem = this.currentItem;
11142 if ( prevItem === null ) {
11143 return;
11144 }
11145
11146 this.currentItem = null;
11147 this.emit( 'set', null );
11148 };
11149
11150 /**
11151 * Add panel layouts to the stack layout.
11152 *
11153 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11154 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11155 * by the index.
11156 *
11157 * @param {OO.ui.Layout[]} items Panels to add
11158 * @param {number} [index] Index of the insertion point
11159 * @chainable
11160 */
11161 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11162 // Update the visibility
11163 this.updateHiddenState( items, this.currentItem );
11164
11165 // Mixin method
11166 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11167
11168 if ( !this.currentItem && items.length ) {
11169 this.setItem( items[ 0 ] );
11170 }
11171
11172 return this;
11173 };
11174
11175 /**
11176 * Remove the specified panels from the stack layout.
11177 *
11178 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11179 * you may wish to use the #clearItems method instead.
11180 *
11181 * @param {OO.ui.Layout[]} items Panels to remove
11182 * @chainable
11183 * @fires set
11184 */
11185 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11186 // Mixin method
11187 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11188
11189 if ( items.indexOf( this.currentItem ) !== -1 ) {
11190 if ( this.items.length ) {
11191 this.setItem( this.items[ 0 ] );
11192 } else {
11193 this.unsetCurrentItem();
11194 }
11195 }
11196
11197 return this;
11198 };
11199
11200 /**
11201 * Clear all panels from the stack layout.
11202 *
11203 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11204 * a subset of panels, use the #removeItems method.
11205 *
11206 * @chainable
11207 * @fires set
11208 */
11209 OO.ui.StackLayout.prototype.clearItems = function () {
11210 this.unsetCurrentItem();
11211 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11212
11213 return this;
11214 };
11215
11216 /**
11217 * Show the specified panel.
11218 *
11219 * If another panel is currently displayed, it will be hidden.
11220 *
11221 * @param {OO.ui.Layout} item Panel to show
11222 * @chainable
11223 * @fires set
11224 */
11225 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11226 if ( item !== this.currentItem ) {
11227 this.updateHiddenState( this.items, item );
11228
11229 if ( this.items.indexOf( item ) !== -1 ) {
11230 this.currentItem = item;
11231 this.emit( 'set', item );
11232 } else {
11233 this.unsetCurrentItem();
11234 }
11235 }
11236
11237 return this;
11238 };
11239
11240 /**
11241 * Update the visibility of all items in case of non-continuous view.
11242 *
11243 * Ensure all items are hidden except for the selected one.
11244 * This method does nothing when the stack is continuous.
11245 *
11246 * @private
11247 * @param {OO.ui.Layout[]} items Item list iterate over
11248 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11249 */
11250 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11251 var i, len;
11252
11253 if ( !this.continuous ) {
11254 for ( i = 0, len = items.length; i < len; i++ ) {
11255 if ( !selectedItem || selectedItem !== items[ i ] ) {
11256 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11257 }
11258 }
11259 if ( selectedItem ) {
11260 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11261 }
11262 }
11263 };
11264
11265 /**
11266 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11267 * items), with small margins between them. Convenient when you need to put a number of block-level
11268 * widgets on a single line next to each other.
11269 *
11270 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11271 *
11272 * @example
11273 * // HorizontalLayout with a text input and a label
11274 * var layout = new OO.ui.HorizontalLayout( {
11275 * items: [
11276 * new OO.ui.LabelWidget( { label: 'Label' } ),
11277 * new OO.ui.TextInputWidget( { value: 'Text' } )
11278 * ]
11279 * } );
11280 * $( 'body' ).append( layout.$element );
11281 *
11282 * @class
11283 * @extends OO.ui.Layout
11284 * @mixins OO.ui.mixin.GroupElement
11285 *
11286 * @constructor
11287 * @param {Object} [config] Configuration options
11288 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11289 */
11290 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11291 // Configuration initialization
11292 config = config || {};
11293
11294 // Parent constructor
11295 OO.ui.HorizontalLayout.parent.call( this, config );
11296
11297 // Mixin constructors
11298 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11299
11300 // Initialization
11301 this.$element.addClass( 'oo-ui-horizontalLayout' );
11302 if ( Array.isArray( config.items ) ) {
11303 this.addItems( config.items );
11304 }
11305 };
11306
11307 /* Setup */
11308
11309 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11310 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11311
11312 /**
11313 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11314 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11315 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11316 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11317 * the tool.
11318 *
11319 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11320 * set up.
11321 *
11322 * @example
11323 * // Example of a BarToolGroup with two tools
11324 * var toolFactory = new OO.ui.ToolFactory();
11325 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11326 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11327 *
11328 * // We will be placing status text in this element when tools are used
11329 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11330 *
11331 * // Define the tools that we're going to place in our toolbar
11332 *
11333 * // Create a class inheriting from OO.ui.Tool
11334 * function PictureTool() {
11335 * PictureTool.parent.apply( this, arguments );
11336 * }
11337 * OO.inheritClass( PictureTool, OO.ui.Tool );
11338 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11339 * // of 'icon' and 'title' (displayed icon and text).
11340 * PictureTool.static.name = 'picture';
11341 * PictureTool.static.icon = 'picture';
11342 * PictureTool.static.title = 'Insert picture';
11343 * // Defines the action that will happen when this tool is selected (clicked).
11344 * PictureTool.prototype.onSelect = function () {
11345 * $area.text( 'Picture tool clicked!' );
11346 * // Never display this tool as "active" (selected).
11347 * this.setActive( false );
11348 * };
11349 * // Make this tool available in our toolFactory and thus our toolbar
11350 * toolFactory.register( PictureTool );
11351 *
11352 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11353 * // little popup window (a PopupWidget).
11354 * function HelpTool( toolGroup, config ) {
11355 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11356 * padded: true,
11357 * label: 'Help',
11358 * head: true
11359 * } }, config ) );
11360 * this.popup.$body.append( '<p>I am helpful!</p>' );
11361 * }
11362 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11363 * HelpTool.static.name = 'help';
11364 * HelpTool.static.icon = 'help';
11365 * HelpTool.static.title = 'Help';
11366 * toolFactory.register( HelpTool );
11367 *
11368 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11369 * // used once (but not all defined tools must be used).
11370 * toolbar.setup( [
11371 * {
11372 * // 'bar' tool groups display tools by icon only
11373 * type: 'bar',
11374 * include: [ 'picture', 'help' ]
11375 * }
11376 * ] );
11377 *
11378 * // Create some UI around the toolbar and place it in the document
11379 * var frame = new OO.ui.PanelLayout( {
11380 * expanded: false,
11381 * framed: true
11382 * } );
11383 * var contentFrame = new OO.ui.PanelLayout( {
11384 * expanded: false,
11385 * padded: true
11386 * } );
11387 * frame.$element.append(
11388 * toolbar.$element,
11389 * contentFrame.$element.append( $area )
11390 * );
11391 * $( 'body' ).append( frame.$element );
11392 *
11393 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11394 * // document.
11395 * toolbar.initialize();
11396 *
11397 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11398 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11399 *
11400 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11401 *
11402 * @class
11403 * @extends OO.ui.ToolGroup
11404 *
11405 * @constructor
11406 * @param {OO.ui.Toolbar} toolbar
11407 * @param {Object} [config] Configuration options
11408 */
11409 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11410 // Allow passing positional parameters inside the config object
11411 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11412 config = toolbar;
11413 toolbar = config.toolbar;
11414 }
11415
11416 // Parent constructor
11417 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11418
11419 // Initialization
11420 this.$element.addClass( 'oo-ui-barToolGroup' );
11421 };
11422
11423 /* Setup */
11424
11425 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11426
11427 /* Static Properties */
11428
11429 OO.ui.BarToolGroup.static.titleTooltips = true;
11430
11431 OO.ui.BarToolGroup.static.accelTooltips = true;
11432
11433 OO.ui.BarToolGroup.static.name = 'bar';
11434
11435 /**
11436 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11437 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11438 * optional icon and label. This class can be used for other base classes that also use this functionality.
11439 *
11440 * @abstract
11441 * @class
11442 * @extends OO.ui.ToolGroup
11443 * @mixins OO.ui.mixin.IconElement
11444 * @mixins OO.ui.mixin.IndicatorElement
11445 * @mixins OO.ui.mixin.LabelElement
11446 * @mixins OO.ui.mixin.TitledElement
11447 * @mixins OO.ui.mixin.ClippableElement
11448 * @mixins OO.ui.mixin.TabIndexedElement
11449 *
11450 * @constructor
11451 * @param {OO.ui.Toolbar} toolbar
11452 * @param {Object} [config] Configuration options
11453 * @cfg {string} [header] Text to display at the top of the popup
11454 */
11455 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11456 // Allow passing positional parameters inside the config object
11457 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11458 config = toolbar;
11459 toolbar = config.toolbar;
11460 }
11461
11462 // Configuration initialization
11463 config = config || {};
11464
11465 // Parent constructor
11466 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11467
11468 // Properties
11469 this.active = false;
11470 this.dragging = false;
11471 this.onBlurHandler = this.onBlur.bind( this );
11472 this.$handle = $( '<span>' );
11473
11474 // Mixin constructors
11475 OO.ui.mixin.IconElement.call( this, config );
11476 OO.ui.mixin.IndicatorElement.call( this, config );
11477 OO.ui.mixin.LabelElement.call( this, config );
11478 OO.ui.mixin.TitledElement.call( this, config );
11479 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11480 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11481
11482 // Events
11483 this.$handle.on( {
11484 keydown: this.onHandleMouseKeyDown.bind( this ),
11485 keyup: this.onHandleMouseKeyUp.bind( this ),
11486 mousedown: this.onHandleMouseKeyDown.bind( this ),
11487 mouseup: this.onHandleMouseKeyUp.bind( this )
11488 } );
11489
11490 // Initialization
11491 this.$handle
11492 .addClass( 'oo-ui-popupToolGroup-handle' )
11493 .append( this.$icon, this.$label, this.$indicator );
11494 // If the pop-up should have a header, add it to the top of the toolGroup.
11495 // Note: If this feature is useful for other widgets, we could abstract it into an
11496 // OO.ui.HeaderedElement mixin constructor.
11497 if ( config.header !== undefined ) {
11498 this.$group
11499 .prepend( $( '<span>' )
11500 .addClass( 'oo-ui-popupToolGroup-header' )
11501 .text( config.header )
11502 );
11503 }
11504 this.$element
11505 .addClass( 'oo-ui-popupToolGroup' )
11506 .prepend( this.$handle );
11507 };
11508
11509 /* Setup */
11510
11511 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11512 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11513 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11514 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11515 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11516 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11517 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11518
11519 /* Methods */
11520
11521 /**
11522 * @inheritdoc
11523 */
11524 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11525 // Parent method
11526 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11527
11528 if ( this.isDisabled() && this.isElementAttached() ) {
11529 this.setActive( false );
11530 }
11531 };
11532
11533 /**
11534 * Handle focus being lost.
11535 *
11536 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11537 *
11538 * @protected
11539 * @param {jQuery.Event} e Mouse up or key up event
11540 */
11541 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11542 // Only deactivate when clicking outside the dropdown element
11543 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11544 this.setActive( false );
11545 }
11546 };
11547
11548 /**
11549 * @inheritdoc
11550 */
11551 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11552 // Only close toolgroup when a tool was actually selected
11553 if (
11554 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11555 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11556 ) {
11557 this.setActive( false );
11558 }
11559 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11560 };
11561
11562 /**
11563 * Handle mouse up and key up events.
11564 *
11565 * @protected
11566 * @param {jQuery.Event} e Mouse up or key up event
11567 */
11568 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11569 if (
11570 !this.isDisabled() &&
11571 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11572 ) {
11573 return false;
11574 }
11575 };
11576
11577 /**
11578 * Handle mouse down and key down events.
11579 *
11580 * @protected
11581 * @param {jQuery.Event} e Mouse down or key down event
11582 */
11583 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11584 if (
11585 !this.isDisabled() &&
11586 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11587 ) {
11588 this.setActive( !this.active );
11589 return false;
11590 }
11591 };
11592
11593 /**
11594 * Switch into 'active' mode.
11595 *
11596 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11597 * deactivation.
11598 */
11599 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11600 var containerWidth, containerLeft;
11601 value = !!value;
11602 if ( this.active !== value ) {
11603 this.active = value;
11604 if ( value ) {
11605 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11606 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11607
11608 this.$clippable.css( 'left', '' );
11609 // Try anchoring the popup to the left first
11610 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11611 this.toggleClipping( true );
11612 if ( this.isClippedHorizontally() ) {
11613 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11614 this.toggleClipping( false );
11615 this.$element
11616 .removeClass( 'oo-ui-popupToolGroup-left' )
11617 .addClass( 'oo-ui-popupToolGroup-right' );
11618 this.toggleClipping( true );
11619 }
11620 if ( this.isClippedHorizontally() ) {
11621 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11622 containerWidth = this.$clippableScrollableContainer.width();
11623 containerLeft = this.$clippableScrollableContainer.offset().left;
11624
11625 this.toggleClipping( false );
11626 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11627
11628 this.$clippable.css( {
11629 left: -( this.$element.offset().left - containerLeft ),
11630 width: containerWidth
11631 } );
11632 }
11633 } else {
11634 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11635 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11636 this.$element.removeClass(
11637 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11638 );
11639 this.toggleClipping( false );
11640 }
11641 }
11642 };
11643
11644 /**
11645 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11646 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11647 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11648 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11649 * with a label, icon, indicator, header, and title.
11650 *
11651 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11652 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11653 * users to collapse the list again.
11654 *
11655 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11656 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11657 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11658 *
11659 * @example
11660 * // Example of a ListToolGroup
11661 * var toolFactory = new OO.ui.ToolFactory();
11662 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11663 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11664 *
11665 * // Configure and register two tools
11666 * function SettingsTool() {
11667 * SettingsTool.parent.apply( this, arguments );
11668 * }
11669 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11670 * SettingsTool.static.name = 'settings';
11671 * SettingsTool.static.icon = 'settings';
11672 * SettingsTool.static.title = 'Change settings';
11673 * SettingsTool.prototype.onSelect = function () {
11674 * this.setActive( false );
11675 * };
11676 * toolFactory.register( SettingsTool );
11677 * // Register two more tools, nothing interesting here
11678 * function StuffTool() {
11679 * StuffTool.parent.apply( this, arguments );
11680 * }
11681 * OO.inheritClass( StuffTool, OO.ui.Tool );
11682 * StuffTool.static.name = 'stuff';
11683 * StuffTool.static.icon = 'ellipsis';
11684 * StuffTool.static.title = 'Change the world';
11685 * StuffTool.prototype.onSelect = function () {
11686 * this.setActive( false );
11687 * };
11688 * toolFactory.register( StuffTool );
11689 * toolbar.setup( [
11690 * {
11691 * // Configurations for list toolgroup.
11692 * type: 'list',
11693 * label: 'ListToolGroup',
11694 * indicator: 'down',
11695 * icon: 'picture',
11696 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11697 * header: 'This is the header',
11698 * include: [ 'settings', 'stuff' ],
11699 * allowCollapse: ['stuff']
11700 * }
11701 * ] );
11702 *
11703 * // Create some UI around the toolbar and place it in the document
11704 * var frame = new OO.ui.PanelLayout( {
11705 * expanded: false,
11706 * framed: true
11707 * } );
11708 * frame.$element.append(
11709 * toolbar.$element
11710 * );
11711 * $( 'body' ).append( frame.$element );
11712 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11713 * toolbar.initialize();
11714 *
11715 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11716 *
11717 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11718 *
11719 * @class
11720 * @extends OO.ui.PopupToolGroup
11721 *
11722 * @constructor
11723 * @param {OO.ui.Toolbar} toolbar
11724 * @param {Object} [config] Configuration options
11725 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11726 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11727 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11728 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11729 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11730 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11731 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11732 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11733 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11734 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11735 */
11736 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11737 // Allow passing positional parameters inside the config object
11738 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11739 config = toolbar;
11740 toolbar = config.toolbar;
11741 }
11742
11743 // Configuration initialization
11744 config = config || {};
11745
11746 // Properties (must be set before parent constructor, which calls #populate)
11747 this.allowCollapse = config.allowCollapse;
11748 this.forceExpand = config.forceExpand;
11749 this.expanded = config.expanded !== undefined ? config.expanded : false;
11750 this.collapsibleTools = [];
11751
11752 // Parent constructor
11753 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11754
11755 // Initialization
11756 this.$element.addClass( 'oo-ui-listToolGroup' );
11757 };
11758
11759 /* Setup */
11760
11761 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11762
11763 /* Static Properties */
11764
11765 OO.ui.ListToolGroup.static.name = 'list';
11766
11767 /* Methods */
11768
11769 /**
11770 * @inheritdoc
11771 */
11772 OO.ui.ListToolGroup.prototype.populate = function () {
11773 var i, len, allowCollapse = [];
11774
11775 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11776
11777 // Update the list of collapsible tools
11778 if ( this.allowCollapse !== undefined ) {
11779 allowCollapse = this.allowCollapse;
11780 } else if ( this.forceExpand !== undefined ) {
11781 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11782 }
11783
11784 this.collapsibleTools = [];
11785 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11786 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11787 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11788 }
11789 }
11790
11791 // Keep at the end, even when tools are added
11792 this.$group.append( this.getExpandCollapseTool().$element );
11793
11794 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11795 this.updateCollapsibleState();
11796 };
11797
11798 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11799 var ExpandCollapseTool;
11800 if ( this.expandCollapseTool === undefined ) {
11801 ExpandCollapseTool = function () {
11802 ExpandCollapseTool.parent.apply( this, arguments );
11803 };
11804
11805 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11806
11807 ExpandCollapseTool.prototype.onSelect = function () {
11808 this.toolGroup.expanded = !this.toolGroup.expanded;
11809 this.toolGroup.updateCollapsibleState();
11810 this.setActive( false );
11811 };
11812 ExpandCollapseTool.prototype.onUpdateState = function () {
11813 // Do nothing. Tool interface requires an implementation of this function.
11814 };
11815
11816 ExpandCollapseTool.static.name = 'more-fewer';
11817
11818 this.expandCollapseTool = new ExpandCollapseTool( this );
11819 }
11820 return this.expandCollapseTool;
11821 };
11822
11823 /**
11824 * @inheritdoc
11825 */
11826 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11827 // Do not close the popup when the user wants to show more/fewer tools
11828 if (
11829 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11830 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11831 ) {
11832 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11833 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11834 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11835 } else {
11836 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11837 }
11838 };
11839
11840 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11841 var i, len;
11842
11843 this.getExpandCollapseTool()
11844 .setIcon( this.expanded ? 'collapse' : 'expand' )
11845 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11846
11847 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11848 this.collapsibleTools[ i ].toggle( this.expanded );
11849 }
11850 };
11851
11852 /**
11853 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11854 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11855 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11856 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11857 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11858 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11859 *
11860 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11861 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11862 * a MenuToolGroup is used.
11863 *
11864 * @example
11865 * // Example of a MenuToolGroup
11866 * var toolFactory = new OO.ui.ToolFactory();
11867 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11868 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11869 *
11870 * // We will be placing status text in this element when tools are used
11871 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11872 *
11873 * // Define the tools that we're going to place in our toolbar
11874 *
11875 * function SettingsTool() {
11876 * SettingsTool.parent.apply( this, arguments );
11877 * this.reallyActive = false;
11878 * }
11879 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11880 * SettingsTool.static.name = 'settings';
11881 * SettingsTool.static.icon = 'settings';
11882 * SettingsTool.static.title = 'Change settings';
11883 * SettingsTool.prototype.onSelect = function () {
11884 * $area.text( 'Settings tool clicked!' );
11885 * // Toggle the active state on each click
11886 * this.reallyActive = !this.reallyActive;
11887 * this.setActive( this.reallyActive );
11888 * // To update the menu label
11889 * this.toolbar.emit( 'updateState' );
11890 * };
11891 * SettingsTool.prototype.onUpdateState = function () {
11892 * };
11893 * toolFactory.register( SettingsTool );
11894 *
11895 * function StuffTool() {
11896 * StuffTool.parent.apply( this, arguments );
11897 * this.reallyActive = false;
11898 * }
11899 * OO.inheritClass( StuffTool, OO.ui.Tool );
11900 * StuffTool.static.name = 'stuff';
11901 * StuffTool.static.icon = 'ellipsis';
11902 * StuffTool.static.title = 'More stuff';
11903 * StuffTool.prototype.onSelect = function () {
11904 * $area.text( 'More stuff tool clicked!' );
11905 * // Toggle the active state on each click
11906 * this.reallyActive = !this.reallyActive;
11907 * this.setActive( this.reallyActive );
11908 * // To update the menu label
11909 * this.toolbar.emit( 'updateState' );
11910 * };
11911 * StuffTool.prototype.onUpdateState = function () {
11912 * };
11913 * toolFactory.register( StuffTool );
11914 *
11915 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11916 * // used once (but not all defined tools must be used).
11917 * toolbar.setup( [
11918 * {
11919 * type: 'menu',
11920 * header: 'This is the (optional) header',
11921 * title: 'This is the (optional) title',
11922 * indicator: 'down',
11923 * include: [ 'settings', 'stuff' ]
11924 * }
11925 * ] );
11926 *
11927 * // Create some UI around the toolbar and place it in the document
11928 * var frame = new OO.ui.PanelLayout( {
11929 * expanded: false,
11930 * framed: true
11931 * } );
11932 * var contentFrame = new OO.ui.PanelLayout( {
11933 * expanded: false,
11934 * padded: true
11935 * } );
11936 * frame.$element.append(
11937 * toolbar.$element,
11938 * contentFrame.$element.append( $area )
11939 * );
11940 * $( 'body' ).append( frame.$element );
11941 *
11942 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11943 * // document.
11944 * toolbar.initialize();
11945 * toolbar.emit( 'updateState' );
11946 *
11947 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11948 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11949 *
11950 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11951 *
11952 * @class
11953 * @extends OO.ui.PopupToolGroup
11954 *
11955 * @constructor
11956 * @param {OO.ui.Toolbar} toolbar
11957 * @param {Object} [config] Configuration options
11958 */
11959 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11960 // Allow passing positional parameters inside the config object
11961 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11962 config = toolbar;
11963 toolbar = config.toolbar;
11964 }
11965
11966 // Configuration initialization
11967 config = config || {};
11968
11969 // Parent constructor
11970 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11971
11972 // Events
11973 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11974
11975 // Initialization
11976 this.$element.addClass( 'oo-ui-menuToolGroup' );
11977 };
11978
11979 /* Setup */
11980
11981 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11982
11983 /* Static Properties */
11984
11985 OO.ui.MenuToolGroup.static.name = 'menu';
11986
11987 /* Methods */
11988
11989 /**
11990 * Handle the toolbar state being updated.
11991 *
11992 * When the state changes, the title of each active item in the menu will be joined together and
11993 * used as a label for the group. The label will be empty if none of the items are active.
11994 *
11995 * @private
11996 */
11997 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11998 var name,
11999 labelTexts = [];
12000
12001 for ( name in this.tools ) {
12002 if ( this.tools[ name ].isActive() ) {
12003 labelTexts.push( this.tools[ name ].getTitle() );
12004 }
12005 }
12006
12007 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12008 };
12009
12010 /**
12011 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12012 * 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
12013 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12014 *
12015 * // Example of a popup tool. When selected, a popup tool displays
12016 * // a popup window.
12017 * function HelpTool( toolGroup, config ) {
12018 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12019 * padded: true,
12020 * label: 'Help',
12021 * head: true
12022 * } }, config ) );
12023 * this.popup.$body.append( '<p>I am helpful!</p>' );
12024 * };
12025 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12026 * HelpTool.static.name = 'help';
12027 * HelpTool.static.icon = 'help';
12028 * HelpTool.static.title = 'Help';
12029 * toolFactory.register( HelpTool );
12030 *
12031 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12032 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12033 *
12034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12035 *
12036 * @abstract
12037 * @class
12038 * @extends OO.ui.Tool
12039 * @mixins OO.ui.mixin.PopupElement
12040 *
12041 * @constructor
12042 * @param {OO.ui.ToolGroup} toolGroup
12043 * @param {Object} [config] Configuration options
12044 */
12045 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12046 // Allow passing positional parameters inside the config object
12047 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12048 config = toolGroup;
12049 toolGroup = config.toolGroup;
12050 }
12051
12052 // Parent constructor
12053 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12054
12055 // Mixin constructors
12056 OO.ui.mixin.PopupElement.call( this, config );
12057
12058 // Initialization
12059 this.$element
12060 .addClass( 'oo-ui-popupTool' )
12061 .append( this.popup.$element );
12062 };
12063
12064 /* Setup */
12065
12066 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12067 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12068
12069 /* Methods */
12070
12071 /**
12072 * Handle the tool being selected.
12073 *
12074 * @inheritdoc
12075 */
12076 OO.ui.PopupTool.prototype.onSelect = function () {
12077 if ( !this.isDisabled() ) {
12078 this.popup.toggle();
12079 }
12080 this.setActive( false );
12081 return false;
12082 };
12083
12084 /**
12085 * Handle the toolbar state being updated.
12086 *
12087 * @inheritdoc
12088 */
12089 OO.ui.PopupTool.prototype.onUpdateState = function () {
12090 this.setActive( false );
12091 };
12092
12093 /**
12094 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12095 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12096 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12097 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12098 * when the ToolGroupTool is selected.
12099 *
12100 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12101 *
12102 * function SettingsTool() {
12103 * SettingsTool.parent.apply( this, arguments );
12104 * };
12105 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12106 * SettingsTool.static.name = 'settings';
12107 * SettingsTool.static.title = 'Change settings';
12108 * SettingsTool.static.groupConfig = {
12109 * icon: 'settings',
12110 * label: 'ToolGroupTool',
12111 * include: [ 'setting1', 'setting2' ]
12112 * };
12113 * toolFactory.register( SettingsTool );
12114 *
12115 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12116 *
12117 * Please note that this implementation is subject to change per [T74159] [2].
12118 *
12119 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12120 * [2]: https://phabricator.wikimedia.org/T74159
12121 *
12122 * @abstract
12123 * @class
12124 * @extends OO.ui.Tool
12125 *
12126 * @constructor
12127 * @param {OO.ui.ToolGroup} toolGroup
12128 * @param {Object} [config] Configuration options
12129 */
12130 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12131 // Allow passing positional parameters inside the config object
12132 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12133 config = toolGroup;
12134 toolGroup = config.toolGroup;
12135 }
12136
12137 // Parent constructor
12138 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12139
12140 // Properties
12141 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12142
12143 // Events
12144 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12145
12146 // Initialization
12147 this.$link.remove();
12148 this.$element
12149 .addClass( 'oo-ui-toolGroupTool' )
12150 .append( this.innerToolGroup.$element );
12151 };
12152
12153 /* Setup */
12154
12155 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12156
12157 /* Static Properties */
12158
12159 /**
12160 * Toolgroup configuration.
12161 *
12162 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12163 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12164 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12165 *
12166 * @property {Object.<string,Array>}
12167 */
12168 OO.ui.ToolGroupTool.static.groupConfig = {};
12169
12170 /* Methods */
12171
12172 /**
12173 * Handle the tool being selected.
12174 *
12175 * @inheritdoc
12176 */
12177 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12178 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12179 return false;
12180 };
12181
12182 /**
12183 * Synchronize disabledness state of the tool with the inner toolgroup.
12184 *
12185 * @private
12186 * @param {boolean} disabled Element is disabled
12187 */
12188 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12189 this.setDisabled( disabled );
12190 };
12191
12192 /**
12193 * Handle the toolbar state being updated.
12194 *
12195 * @inheritdoc
12196 */
12197 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12198 this.setActive( false );
12199 };
12200
12201 /**
12202 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12203 *
12204 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12205 * more information.
12206 * @return {OO.ui.ListToolGroup}
12207 */
12208 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12209 if ( group.include === '*' ) {
12210 // Apply defaults to catch-all groups
12211 if ( group.label === undefined ) {
12212 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12213 }
12214 }
12215
12216 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12217 };
12218
12219 /**
12220 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12221 *
12222 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12223 *
12224 * @private
12225 * @abstract
12226 * @class
12227 * @extends OO.ui.mixin.GroupElement
12228 *
12229 * @constructor
12230 * @param {Object} [config] Configuration options
12231 */
12232 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12233 // Parent constructor
12234 OO.ui.mixin.GroupWidget.parent.call( this, config );
12235 };
12236
12237 /* Setup */
12238
12239 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12240
12241 /* Methods */
12242
12243 /**
12244 * Set the disabled state of the widget.
12245 *
12246 * This will also update the disabled state of child widgets.
12247 *
12248 * @param {boolean} disabled Disable widget
12249 * @chainable
12250 */
12251 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12252 var i, len;
12253
12254 // Parent method
12255 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12256 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12257
12258 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12259 if ( this.items ) {
12260 for ( i = 0, len = this.items.length; i < len; i++ ) {
12261 this.items[ i ].updateDisabled();
12262 }
12263 }
12264
12265 return this;
12266 };
12267
12268 /**
12269 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12270 *
12271 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12272 * allows bidirectional communication.
12273 *
12274 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12275 *
12276 * @private
12277 * @abstract
12278 * @class
12279 *
12280 * @constructor
12281 */
12282 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12283 //
12284 };
12285
12286 /* Methods */
12287
12288 /**
12289 * Check if widget is disabled.
12290 *
12291 * Checks parent if present, making disabled state inheritable.
12292 *
12293 * @return {boolean} Widget is disabled
12294 */
12295 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12296 return this.disabled ||
12297 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12298 };
12299
12300 /**
12301 * Set group element is in.
12302 *
12303 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12304 * @chainable
12305 */
12306 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12307 // Parent method
12308 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12309 OO.ui.Element.prototype.setElementGroup.call( this, group );
12310
12311 // Initialize item disabled states
12312 this.updateDisabled();
12313
12314 return this;
12315 };
12316
12317 /**
12318 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12319 * Controls include moving items up and down, removing items, and adding different kinds of items.
12320 *
12321 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12322 *
12323 * @class
12324 * @extends OO.ui.Widget
12325 * @mixins OO.ui.mixin.GroupElement
12326 * @mixins OO.ui.mixin.IconElement
12327 *
12328 * @constructor
12329 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12330 * @param {Object} [config] Configuration options
12331 * @cfg {Object} [abilities] List of abilties
12332 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12333 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12334 */
12335 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12336 // Allow passing positional parameters inside the config object
12337 if ( OO.isPlainObject( outline ) && config === undefined ) {
12338 config = outline;
12339 outline = config.outline;
12340 }
12341
12342 // Configuration initialization
12343 config = $.extend( { icon: 'add' }, config );
12344
12345 // Parent constructor
12346 OO.ui.OutlineControlsWidget.parent.call( this, config );
12347
12348 // Mixin constructors
12349 OO.ui.mixin.GroupElement.call( this, config );
12350 OO.ui.mixin.IconElement.call( this, config );
12351
12352 // Properties
12353 this.outline = outline;
12354 this.$movers = $( '<div>' );
12355 this.upButton = new OO.ui.ButtonWidget( {
12356 framed: false,
12357 icon: 'collapse',
12358 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12359 } );
12360 this.downButton = new OO.ui.ButtonWidget( {
12361 framed: false,
12362 icon: 'expand',
12363 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12364 } );
12365 this.removeButton = new OO.ui.ButtonWidget( {
12366 framed: false,
12367 icon: 'remove',
12368 title: OO.ui.msg( 'ooui-outline-control-remove' )
12369 } );
12370 this.abilities = { move: true, remove: true };
12371
12372 // Events
12373 outline.connect( this, {
12374 select: 'onOutlineChange',
12375 add: 'onOutlineChange',
12376 remove: 'onOutlineChange'
12377 } );
12378 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12379 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12380 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12381
12382 // Initialization
12383 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12384 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12385 this.$movers
12386 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12387 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12388 this.$element.append( this.$icon, this.$group, this.$movers );
12389 this.setAbilities( config.abilities || {} );
12390 };
12391
12392 /* Setup */
12393
12394 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12395 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12396 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12397
12398 /* Events */
12399
12400 /**
12401 * @event move
12402 * @param {number} places Number of places to move
12403 */
12404
12405 /**
12406 * @event remove
12407 */
12408
12409 /* Methods */
12410
12411 /**
12412 * Set abilities.
12413 *
12414 * @param {Object} abilities List of abilties
12415 * @param {boolean} [abilities.move] Allow moving movable items
12416 * @param {boolean} [abilities.remove] Allow removing removable items
12417 */
12418 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12419 var ability;
12420
12421 for ( ability in this.abilities ) {
12422 if ( abilities[ ability ] !== undefined ) {
12423 this.abilities[ ability ] = !!abilities[ ability ];
12424 }
12425 }
12426
12427 this.onOutlineChange();
12428 };
12429
12430 /**
12431 * @private
12432 * Handle outline change events.
12433 */
12434 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12435 var i, len, firstMovable, lastMovable,
12436 items = this.outline.getItems(),
12437 selectedItem = this.outline.getSelectedItem(),
12438 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12439 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12440
12441 if ( movable ) {
12442 i = -1;
12443 len = items.length;
12444 while ( ++i < len ) {
12445 if ( items[ i ].isMovable() ) {
12446 firstMovable = items[ i ];
12447 break;
12448 }
12449 }
12450 i = len;
12451 while ( i-- ) {
12452 if ( items[ i ].isMovable() ) {
12453 lastMovable = items[ i ];
12454 break;
12455 }
12456 }
12457 }
12458 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12459 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12460 this.removeButton.setDisabled( !removable );
12461 };
12462
12463 /**
12464 * ToggleWidget implements basic behavior of widgets with an on/off state.
12465 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12466 *
12467 * @abstract
12468 * @class
12469 * @extends OO.ui.Widget
12470 *
12471 * @constructor
12472 * @param {Object} [config] Configuration options
12473 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12474 * By default, the toggle is in the 'off' state.
12475 */
12476 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12477 // Configuration initialization
12478 config = config || {};
12479
12480 // Parent constructor
12481 OO.ui.ToggleWidget.parent.call( this, config );
12482
12483 // Properties
12484 this.value = null;
12485
12486 // Initialization
12487 this.$element.addClass( 'oo-ui-toggleWidget' );
12488 this.setValue( !!config.value );
12489 };
12490
12491 /* Setup */
12492
12493 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12494
12495 /* Events */
12496
12497 /**
12498 * @event change
12499 *
12500 * A change event is emitted when the on/off state of the toggle changes.
12501 *
12502 * @param {boolean} value Value representing the new state of the toggle
12503 */
12504
12505 /* Methods */
12506
12507 /**
12508 * Get the value representing the toggle’s state.
12509 *
12510 * @return {boolean} The on/off state of the toggle
12511 */
12512 OO.ui.ToggleWidget.prototype.getValue = function () {
12513 return this.value;
12514 };
12515
12516 /**
12517 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12518 *
12519 * @param {boolean} value The state of the toggle
12520 * @fires change
12521 * @chainable
12522 */
12523 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12524 value = !!value;
12525 if ( this.value !== value ) {
12526 this.value = value;
12527 this.emit( 'change', value );
12528 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12529 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12530 this.$element.attr( 'aria-checked', value.toString() );
12531 }
12532 return this;
12533 };
12534
12535 /**
12536 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12537 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12538 * removed, and cleared from the group.
12539 *
12540 * @example
12541 * // Example: A ButtonGroupWidget with two buttons
12542 * var button1 = new OO.ui.PopupButtonWidget( {
12543 * label: 'Select a category',
12544 * icon: 'menu',
12545 * popup: {
12546 * $content: $( '<p>List of categories...</p>' ),
12547 * padded: true,
12548 * align: 'left'
12549 * }
12550 * } );
12551 * var button2 = new OO.ui.ButtonWidget( {
12552 * label: 'Add item'
12553 * });
12554 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12555 * items: [button1, button2]
12556 * } );
12557 * $( 'body' ).append( buttonGroup.$element );
12558 *
12559 * @class
12560 * @extends OO.ui.Widget
12561 * @mixins OO.ui.mixin.GroupElement
12562 *
12563 * @constructor
12564 * @param {Object} [config] Configuration options
12565 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12566 */
12567 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12568 // Configuration initialization
12569 config = config || {};
12570
12571 // Parent constructor
12572 OO.ui.ButtonGroupWidget.parent.call( this, config );
12573
12574 // Mixin constructors
12575 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12576
12577 // Initialization
12578 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12579 if ( Array.isArray( config.items ) ) {
12580 this.addItems( config.items );
12581 }
12582 };
12583
12584 /* Setup */
12585
12586 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12587 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12588
12589 /**
12590 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12591 * feels, and functionality can be customized via the class’s configuration options
12592 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12593 * and examples.
12594 *
12595 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12596 *
12597 * @example
12598 * // A button widget
12599 * var button = new OO.ui.ButtonWidget( {
12600 * label: 'Button with Icon',
12601 * icon: 'remove',
12602 * iconTitle: 'Remove'
12603 * } );
12604 * $( 'body' ).append( button.$element );
12605 *
12606 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12607 *
12608 * @class
12609 * @extends OO.ui.Widget
12610 * @mixins OO.ui.mixin.ButtonElement
12611 * @mixins OO.ui.mixin.IconElement
12612 * @mixins OO.ui.mixin.IndicatorElement
12613 * @mixins OO.ui.mixin.LabelElement
12614 * @mixins OO.ui.mixin.TitledElement
12615 * @mixins OO.ui.mixin.FlaggedElement
12616 * @mixins OO.ui.mixin.TabIndexedElement
12617 * @mixins OO.ui.mixin.AccessKeyedElement
12618 *
12619 * @constructor
12620 * @param {Object} [config] Configuration options
12621 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12622 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12623 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12624 */
12625 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12626 // Configuration initialization
12627 config = config || {};
12628
12629 // Parent constructor
12630 OO.ui.ButtonWidget.parent.call( this, config );
12631
12632 // Mixin constructors
12633 OO.ui.mixin.ButtonElement.call( this, config );
12634 OO.ui.mixin.IconElement.call( this, config );
12635 OO.ui.mixin.IndicatorElement.call( this, config );
12636 OO.ui.mixin.LabelElement.call( this, config );
12637 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12638 OO.ui.mixin.FlaggedElement.call( this, config );
12639 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12640 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12641
12642 // Properties
12643 this.href = null;
12644 this.target = null;
12645 this.noFollow = false;
12646
12647 // Events
12648 this.connect( this, { disable: 'onDisable' } );
12649
12650 // Initialization
12651 this.$button.append( this.$icon, this.$label, this.$indicator );
12652 this.$element
12653 .addClass( 'oo-ui-buttonWidget' )
12654 .append( this.$button );
12655 this.setHref( config.href );
12656 this.setTarget( config.target );
12657 this.setNoFollow( config.noFollow );
12658 };
12659
12660 /* Setup */
12661
12662 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12663 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12664 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12665 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12666 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12667 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12668 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12669 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12670 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12671
12672 /* Methods */
12673
12674 /**
12675 * @inheritdoc
12676 */
12677 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12678 if ( !this.isDisabled() ) {
12679 // Remove the tab-index while the button is down to prevent the button from stealing focus
12680 this.$button.removeAttr( 'tabindex' );
12681 }
12682
12683 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12684 };
12685
12686 /**
12687 * @inheritdoc
12688 */
12689 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12690 if ( !this.isDisabled() ) {
12691 // Restore the tab-index after the button is up to restore the button's accessibility
12692 this.$button.attr( 'tabindex', this.tabIndex );
12693 }
12694
12695 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12696 };
12697
12698 /**
12699 * Get hyperlink location.
12700 *
12701 * @return {string} Hyperlink location
12702 */
12703 OO.ui.ButtonWidget.prototype.getHref = function () {
12704 return this.href;
12705 };
12706
12707 /**
12708 * Get hyperlink target.
12709 *
12710 * @return {string} Hyperlink target
12711 */
12712 OO.ui.ButtonWidget.prototype.getTarget = function () {
12713 return this.target;
12714 };
12715
12716 /**
12717 * Get search engine traversal hint.
12718 *
12719 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12720 */
12721 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12722 return this.noFollow;
12723 };
12724
12725 /**
12726 * Set hyperlink location.
12727 *
12728 * @param {string|null} href Hyperlink location, null to remove
12729 */
12730 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12731 href = typeof href === 'string' ? href : null;
12732 if ( href !== null ) {
12733 if ( !OO.ui.isSafeUrl( href ) ) {
12734 throw new Error( 'Potentially unsafe href provided: ' + href );
12735 }
12736
12737 }
12738
12739 if ( href !== this.href ) {
12740 this.href = href;
12741 this.updateHref();
12742 }
12743
12744 return this;
12745 };
12746
12747 /**
12748 * Update the `href` attribute, in case of changes to href or
12749 * disabled state.
12750 *
12751 * @private
12752 * @chainable
12753 */
12754 OO.ui.ButtonWidget.prototype.updateHref = function () {
12755 if ( this.href !== null && !this.isDisabled() ) {
12756 this.$button.attr( 'href', this.href );
12757 } else {
12758 this.$button.removeAttr( 'href' );
12759 }
12760
12761 return this;
12762 };
12763
12764 /**
12765 * Handle disable events.
12766 *
12767 * @private
12768 * @param {boolean} disabled Element is disabled
12769 */
12770 OO.ui.ButtonWidget.prototype.onDisable = function () {
12771 this.updateHref();
12772 };
12773
12774 /**
12775 * Set hyperlink target.
12776 *
12777 * @param {string|null} target Hyperlink target, null to remove
12778 */
12779 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12780 target = typeof target === 'string' ? target : null;
12781
12782 if ( target !== this.target ) {
12783 this.target = target;
12784 if ( target !== null ) {
12785 this.$button.attr( 'target', target );
12786 } else {
12787 this.$button.removeAttr( 'target' );
12788 }
12789 }
12790
12791 return this;
12792 };
12793
12794 /**
12795 * Set search engine traversal hint.
12796 *
12797 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12798 */
12799 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12800 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12801
12802 if ( noFollow !== this.noFollow ) {
12803 this.noFollow = noFollow;
12804 if ( noFollow ) {
12805 this.$button.attr( 'rel', 'nofollow' );
12806 } else {
12807 this.$button.removeAttr( 'rel' );
12808 }
12809 }
12810
12811 return this;
12812 };
12813
12814 /**
12815 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12816 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12817 * of the actions.
12818 *
12819 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12820 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12821 * and examples.
12822 *
12823 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12824 *
12825 * @class
12826 * @extends OO.ui.ButtonWidget
12827 * @mixins OO.ui.mixin.PendingElement
12828 *
12829 * @constructor
12830 * @param {Object} [config] Configuration options
12831 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12832 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12833 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12834 * for more information about setting modes.
12835 * @cfg {boolean} [framed=false] Render the action button with a frame
12836 */
12837 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12838 // Configuration initialization
12839 config = $.extend( { framed: false }, config );
12840
12841 // Parent constructor
12842 OO.ui.ActionWidget.parent.call( this, config );
12843
12844 // Mixin constructors
12845 OO.ui.mixin.PendingElement.call( this, config );
12846
12847 // Properties
12848 this.action = config.action || '';
12849 this.modes = config.modes || [];
12850 this.width = 0;
12851 this.height = 0;
12852
12853 // Initialization
12854 this.$element.addClass( 'oo-ui-actionWidget' );
12855 };
12856
12857 /* Setup */
12858
12859 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12860 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12861
12862 /* Events */
12863
12864 /**
12865 * A resize event is emitted when the size of the widget changes.
12866 *
12867 * @event resize
12868 */
12869
12870 /* Methods */
12871
12872 /**
12873 * Check if the action is configured to be available in the specified `mode`.
12874 *
12875 * @param {string} mode Name of mode
12876 * @return {boolean} The action is configured with the mode
12877 */
12878 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12879 return this.modes.indexOf( mode ) !== -1;
12880 };
12881
12882 /**
12883 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12884 *
12885 * @return {string}
12886 */
12887 OO.ui.ActionWidget.prototype.getAction = function () {
12888 return this.action;
12889 };
12890
12891 /**
12892 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12893 *
12894 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12895 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12896 * are hidden.
12897 *
12898 * @return {string[]}
12899 */
12900 OO.ui.ActionWidget.prototype.getModes = function () {
12901 return this.modes.slice();
12902 };
12903
12904 /**
12905 * Emit a resize event if the size has changed.
12906 *
12907 * @private
12908 * @chainable
12909 */
12910 OO.ui.ActionWidget.prototype.propagateResize = function () {
12911 var width, height;
12912
12913 if ( this.isElementAttached() ) {
12914 width = this.$element.width();
12915 height = this.$element.height();
12916
12917 if ( width !== this.width || height !== this.height ) {
12918 this.width = width;
12919 this.height = height;
12920 this.emit( 'resize' );
12921 }
12922 }
12923
12924 return this;
12925 };
12926
12927 /**
12928 * @inheritdoc
12929 */
12930 OO.ui.ActionWidget.prototype.setIcon = function () {
12931 // Mixin method
12932 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12933 this.propagateResize();
12934
12935 return this;
12936 };
12937
12938 /**
12939 * @inheritdoc
12940 */
12941 OO.ui.ActionWidget.prototype.setLabel = function () {
12942 // Mixin method
12943 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12944 this.propagateResize();
12945
12946 return this;
12947 };
12948
12949 /**
12950 * @inheritdoc
12951 */
12952 OO.ui.ActionWidget.prototype.setFlags = function () {
12953 // Mixin method
12954 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12955 this.propagateResize();
12956
12957 return this;
12958 };
12959
12960 /**
12961 * @inheritdoc
12962 */
12963 OO.ui.ActionWidget.prototype.clearFlags = function () {
12964 // Mixin method
12965 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12966 this.propagateResize();
12967
12968 return this;
12969 };
12970
12971 /**
12972 * Toggle the visibility of the action button.
12973 *
12974 * @param {boolean} [show] Show button, omit to toggle visibility
12975 * @chainable
12976 */
12977 OO.ui.ActionWidget.prototype.toggle = function () {
12978 // Parent method
12979 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12980 this.propagateResize();
12981
12982 return this;
12983 };
12984
12985 /**
12986 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12987 * which is used to display additional information or options.
12988 *
12989 * @example
12990 * // Example of a popup button.
12991 * var popupButton = new OO.ui.PopupButtonWidget( {
12992 * label: 'Popup button with options',
12993 * icon: 'menu',
12994 * popup: {
12995 * $content: $( '<p>Additional options here.</p>' ),
12996 * padded: true,
12997 * align: 'force-left'
12998 * }
12999 * } );
13000 * // Append the button to the DOM.
13001 * $( 'body' ).append( popupButton.$element );
13002 *
13003 * @class
13004 * @extends OO.ui.ButtonWidget
13005 * @mixins OO.ui.mixin.PopupElement
13006 *
13007 * @constructor
13008 * @param {Object} [config] Configuration options
13009 */
13010 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13011 // Parent constructor
13012 OO.ui.PopupButtonWidget.parent.call( this, config );
13013
13014 // Mixin constructors
13015 OO.ui.mixin.PopupElement.call( this, config );
13016
13017 // Events
13018 this.connect( this, { click: 'onAction' } );
13019
13020 // Initialization
13021 this.$element
13022 .addClass( 'oo-ui-popupButtonWidget' )
13023 .attr( 'aria-haspopup', 'true' )
13024 .append( this.popup.$element );
13025 };
13026
13027 /* Setup */
13028
13029 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13030 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13031
13032 /* Methods */
13033
13034 /**
13035 * Handle the button action being triggered.
13036 *
13037 * @private
13038 */
13039 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13040 this.popup.toggle();
13041 };
13042
13043 /**
13044 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13045 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13046 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13047 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13048 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13049 * the [OOjs UI documentation][1] on MediaWiki for more information.
13050 *
13051 * @example
13052 * // Toggle buttons in the 'off' and 'on' state.
13053 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13054 * label: 'Toggle Button off'
13055 * } );
13056 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13057 * label: 'Toggle Button on',
13058 * value: true
13059 * } );
13060 * // Append the buttons to the DOM.
13061 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13062 *
13063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13064 *
13065 * @class
13066 * @extends OO.ui.ToggleWidget
13067 * @mixins OO.ui.mixin.ButtonElement
13068 * @mixins OO.ui.mixin.IconElement
13069 * @mixins OO.ui.mixin.IndicatorElement
13070 * @mixins OO.ui.mixin.LabelElement
13071 * @mixins OO.ui.mixin.TitledElement
13072 * @mixins OO.ui.mixin.FlaggedElement
13073 * @mixins OO.ui.mixin.TabIndexedElement
13074 *
13075 * @constructor
13076 * @param {Object} [config] Configuration options
13077 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13078 * state. By default, the button is in the 'off' state.
13079 */
13080 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13081 // Configuration initialization
13082 config = config || {};
13083
13084 // Parent constructor
13085 OO.ui.ToggleButtonWidget.parent.call( this, config );
13086
13087 // Mixin constructors
13088 OO.ui.mixin.ButtonElement.call( this, config );
13089 OO.ui.mixin.IconElement.call( this, config );
13090 OO.ui.mixin.IndicatorElement.call( this, config );
13091 OO.ui.mixin.LabelElement.call( this, config );
13092 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13093 OO.ui.mixin.FlaggedElement.call( this, config );
13094 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13095
13096 // Events
13097 this.connect( this, { click: 'onAction' } );
13098
13099 // Initialization
13100 this.$button.append( this.$icon, this.$label, this.$indicator );
13101 this.$element
13102 .addClass( 'oo-ui-toggleButtonWidget' )
13103 .append( this.$button );
13104 };
13105
13106 /* Setup */
13107
13108 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13109 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13110 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13111 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13112 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13113 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13114 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13115 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13116
13117 /* Methods */
13118
13119 /**
13120 * Handle the button action being triggered.
13121 *
13122 * @private
13123 */
13124 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13125 this.setValue( !this.value );
13126 };
13127
13128 /**
13129 * @inheritdoc
13130 */
13131 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13132 value = !!value;
13133 if ( value !== this.value ) {
13134 // Might be called from parent constructor before ButtonElement constructor
13135 if ( this.$button ) {
13136 this.$button.attr( 'aria-pressed', value.toString() );
13137 }
13138 this.setActive( value );
13139 }
13140
13141 // Parent method
13142 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13143
13144 return this;
13145 };
13146
13147 /**
13148 * @inheritdoc
13149 */
13150 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13151 if ( this.$button ) {
13152 this.$button.removeAttr( 'aria-pressed' );
13153 }
13154 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13155 this.$button.attr( 'aria-pressed', this.value.toString() );
13156 };
13157
13158 /**
13159 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13160 * that allows for selecting multiple values.
13161 *
13162 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13163 *
13164 * @example
13165 * // Example: A CapsuleMultiSelectWidget.
13166 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13167 * label: 'CapsuleMultiSelectWidget',
13168 * selected: [ 'Option 1', 'Option 3' ],
13169 * menu: {
13170 * items: [
13171 * new OO.ui.MenuOptionWidget( {
13172 * data: 'Option 1',
13173 * label: 'Option One'
13174 * } ),
13175 * new OO.ui.MenuOptionWidget( {
13176 * data: 'Option 2',
13177 * label: 'Option Two'
13178 * } ),
13179 * new OO.ui.MenuOptionWidget( {
13180 * data: 'Option 3',
13181 * label: 'Option Three'
13182 * } ),
13183 * new OO.ui.MenuOptionWidget( {
13184 * data: 'Option 4',
13185 * label: 'Option Four'
13186 * } ),
13187 * new OO.ui.MenuOptionWidget( {
13188 * data: 'Option 5',
13189 * label: 'Option Five'
13190 * } )
13191 * ]
13192 * }
13193 * } );
13194 * $( 'body' ).append( capsule.$element );
13195 *
13196 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13197 *
13198 * @class
13199 * @extends OO.ui.Widget
13200 * @mixins OO.ui.mixin.TabIndexedElement
13201 * @mixins OO.ui.mixin.GroupElement
13202 *
13203 * @constructor
13204 * @param {Object} [config] Configuration options
13205 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13206 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13207 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13208 * If specified, this popup will be shown instead of the menu (but the menu
13209 * will still be used for item labels and allowArbitrary=false). The widgets
13210 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13211 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13212 * This configuration is useful in cases where the expanded menu is larger than
13213 * its containing `<div>`. The specified overlay layer is usually on top of
13214 * the containing `<div>` and has a larger area. By default, the menu uses
13215 * relative positioning.
13216 */
13217 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13218 var $tabFocus;
13219
13220 // Configuration initialization
13221 config = config || {};
13222
13223 // Parent constructor
13224 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13225
13226 // Properties (must be set before mixin constructor calls)
13227 this.$input = config.popup ? null : $( '<input>' );
13228 this.$handle = $( '<div>' );
13229
13230 // Mixin constructors
13231 OO.ui.mixin.GroupElement.call( this, config );
13232 if ( config.popup ) {
13233 config.popup = $.extend( {}, config.popup, {
13234 align: 'forwards',
13235 anchor: false
13236 } );
13237 OO.ui.mixin.PopupElement.call( this, config );
13238 $tabFocus = $( '<span>' );
13239 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13240 } else {
13241 this.popup = null;
13242 $tabFocus = null;
13243 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13244 }
13245 OO.ui.mixin.IndicatorElement.call( this, config );
13246 OO.ui.mixin.IconElement.call( this, config );
13247
13248 // Properties
13249 this.allowArbitrary = !!config.allowArbitrary;
13250 this.$overlay = config.$overlay || this.$element;
13251 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13252 {
13253 widget: this,
13254 $input: this.$input,
13255 $container: this.$element,
13256 filterFromInput: true,
13257 disabled: this.isDisabled()
13258 },
13259 config.menu
13260 ) );
13261
13262 // Events
13263 if ( this.popup ) {
13264 $tabFocus.on( {
13265 focus: this.onFocusForPopup.bind( this )
13266 } );
13267 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13268 if ( this.popup.$autoCloseIgnore ) {
13269 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13270 }
13271 this.popup.connect( this, {
13272 toggle: function ( visible ) {
13273 $tabFocus.toggle( !visible );
13274 }
13275 } );
13276 } else {
13277 this.$input.on( {
13278 focus: this.onInputFocus.bind( this ),
13279 blur: this.onInputBlur.bind( this ),
13280 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13281 keydown: this.onKeyDown.bind( this ),
13282 keypress: this.onKeyPress.bind( this )
13283 } );
13284 }
13285 this.menu.connect( this, {
13286 choose: 'onMenuChoose',
13287 add: 'onMenuItemsChange',
13288 remove: 'onMenuItemsChange'
13289 } );
13290 this.$handle.on( {
13291 click: this.onClick.bind( this )
13292 } );
13293
13294 // Initialization
13295 if ( this.$input ) {
13296 this.$input.prop( 'disabled', this.isDisabled() );
13297 this.$input.attr( {
13298 role: 'combobox',
13299 'aria-autocomplete': 'list'
13300 } );
13301 this.$input.width( '1em' );
13302 }
13303 if ( config.data ) {
13304 this.setItemsFromData( config.data );
13305 }
13306 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13307 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13308 .append( this.$indicator, this.$icon, this.$group );
13309 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13310 .append( this.$handle );
13311 if ( this.popup ) {
13312 this.$handle.append( $tabFocus );
13313 this.$overlay.append( this.popup.$element );
13314 } else {
13315 this.$handle.append( this.$input );
13316 this.$overlay.append( this.menu.$element );
13317 }
13318 this.onMenuItemsChange();
13319 };
13320
13321 /* Setup */
13322
13323 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13324 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13325 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13326 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13327 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13328 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13329
13330 /* Events */
13331
13332 /**
13333 * @event change
13334 *
13335 * A change event is emitted when the set of selected items changes.
13336 *
13337 * @param {Mixed[]} datas Data of the now-selected items
13338 */
13339
13340 /* Methods */
13341
13342 /**
13343 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13344 *
13345 * @protected
13346 * @param {Mixed} data Custom data of any type.
13347 * @param {string} label The label text.
13348 * @return {OO.ui.CapsuleItemWidget}
13349 */
13350 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13351 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13352 };
13353
13354 /**
13355 * Get the data of the items in the capsule
13356 * @return {Mixed[]}
13357 */
13358 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13359 return $.map( this.getItems(), function ( e ) { return e.data; } );
13360 };
13361
13362 /**
13363 * Set the items in the capsule by providing data
13364 * @chainable
13365 * @param {Mixed[]} datas
13366 * @return {OO.ui.CapsuleMultiSelectWidget}
13367 */
13368 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13369 var widget = this,
13370 menu = this.menu,
13371 items = this.getItems();
13372
13373 $.each( datas, function ( i, data ) {
13374 var j, label,
13375 item = menu.getItemFromData( data );
13376
13377 if ( item ) {
13378 label = item.label;
13379 } else if ( widget.allowArbitrary ) {
13380 label = String( data );
13381 } else {
13382 return;
13383 }
13384
13385 item = null;
13386 for ( j = 0; j < items.length; j++ ) {
13387 if ( items[ j ].data === data && items[ j ].label === label ) {
13388 item = items[ j ];
13389 items.splice( j, 1 );
13390 break;
13391 }
13392 }
13393 if ( !item ) {
13394 item = widget.createItemWidget( data, label );
13395 }
13396 widget.addItems( [ item ], i );
13397 } );
13398
13399 if ( items.length ) {
13400 widget.removeItems( items );
13401 }
13402
13403 return this;
13404 };
13405
13406 /**
13407 * Add items to the capsule by providing their data
13408 * @chainable
13409 * @param {Mixed[]} datas
13410 * @return {OO.ui.CapsuleMultiSelectWidget}
13411 */
13412 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13413 var widget = this,
13414 menu = this.menu,
13415 items = [];
13416
13417 $.each( datas, function ( i, data ) {
13418 var item;
13419
13420 if ( !widget.getItemFromData( data ) ) {
13421 item = menu.getItemFromData( data );
13422 if ( item ) {
13423 items.push( widget.createItemWidget( data, item.label ) );
13424 } else if ( widget.allowArbitrary ) {
13425 items.push( widget.createItemWidget( data, String( data ) ) );
13426 }
13427 }
13428 } );
13429
13430 if ( items.length ) {
13431 this.addItems( items );
13432 }
13433
13434 return this;
13435 };
13436
13437 /**
13438 * Remove items by data
13439 * @chainable
13440 * @param {Mixed[]} datas
13441 * @return {OO.ui.CapsuleMultiSelectWidget}
13442 */
13443 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13444 var widget = this,
13445 items = [];
13446
13447 $.each( datas, function ( i, data ) {
13448 var item = widget.getItemFromData( data );
13449 if ( item ) {
13450 items.push( item );
13451 }
13452 } );
13453
13454 if ( items.length ) {
13455 this.removeItems( items );
13456 }
13457
13458 return this;
13459 };
13460
13461 /**
13462 * @inheritdoc
13463 */
13464 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13465 var same, i, l,
13466 oldItems = this.items.slice();
13467
13468 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13469
13470 if ( this.items.length !== oldItems.length ) {
13471 same = false;
13472 } else {
13473 same = true;
13474 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13475 same = same && this.items[ i ] === oldItems[ i ];
13476 }
13477 }
13478 if ( !same ) {
13479 this.emit( 'change', this.getItemsData() );
13480 }
13481
13482 return this;
13483 };
13484
13485 /**
13486 * @inheritdoc
13487 */
13488 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13489 var same, i, l,
13490 oldItems = this.items.slice();
13491
13492 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13493
13494 if ( this.items.length !== oldItems.length ) {
13495 same = false;
13496 } else {
13497 same = true;
13498 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13499 same = same && this.items[ i ] === oldItems[ i ];
13500 }
13501 }
13502 if ( !same ) {
13503 this.emit( 'change', this.getItemsData() );
13504 }
13505
13506 return this;
13507 };
13508
13509 /**
13510 * @inheritdoc
13511 */
13512 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13513 if ( this.items.length ) {
13514 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13515 this.emit( 'change', this.getItemsData() );
13516 }
13517 return this;
13518 };
13519
13520 /**
13521 * Get the capsule widget's menu.
13522 * @return {OO.ui.MenuSelectWidget} Menu widget
13523 */
13524 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13525 return this.menu;
13526 };
13527
13528 /**
13529 * Handle focus events
13530 *
13531 * @private
13532 * @param {jQuery.Event} event
13533 */
13534 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13535 if ( !this.isDisabled() ) {
13536 this.menu.toggle( true );
13537 }
13538 };
13539
13540 /**
13541 * Handle blur events
13542 *
13543 * @private
13544 * @param {jQuery.Event} event
13545 */
13546 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13547 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13548 this.addItemsFromData( [ this.$input.val() ] );
13549 }
13550 this.clearInput();
13551 };
13552
13553 /**
13554 * Handle focus events
13555 *
13556 * @private
13557 * @param {jQuery.Event} event
13558 */
13559 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13560 if ( !this.isDisabled() ) {
13561 this.popup.setSize( this.$handle.width() );
13562 this.popup.toggle( true );
13563 this.popup.$element.find( '*' )
13564 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13565 .first()
13566 .focus();
13567 }
13568 };
13569
13570 /**
13571 * Handles popup focus out events.
13572 *
13573 * @private
13574 * @param {Event} e Focus out event
13575 */
13576 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13577 var widget = this.popup;
13578
13579 setTimeout( function () {
13580 if (
13581 widget.isVisible() &&
13582 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13583 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13584 ) {
13585 widget.toggle( false );
13586 }
13587 } );
13588 };
13589
13590 /**
13591 * Handle mouse click events.
13592 *
13593 * @private
13594 * @param {jQuery.Event} e Mouse click event
13595 */
13596 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13597 if ( e.which === 1 ) {
13598 this.focus();
13599 return false;
13600 }
13601 };
13602
13603 /**
13604 * Handle key press events.
13605 *
13606 * @private
13607 * @param {jQuery.Event} e Key press event
13608 */
13609 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13610 var item;
13611
13612 if ( !this.isDisabled() ) {
13613 if ( e.which === OO.ui.Keys.ESCAPE ) {
13614 this.clearInput();
13615 return false;
13616 }
13617
13618 if ( !this.popup ) {
13619 this.menu.toggle( true );
13620 if ( e.which === OO.ui.Keys.ENTER ) {
13621 item = this.menu.getItemFromLabel( this.$input.val(), true );
13622 if ( item ) {
13623 this.addItemsFromData( [ item.data ] );
13624 this.clearInput();
13625 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13626 this.addItemsFromData( [ this.$input.val() ] );
13627 this.clearInput();
13628 }
13629 return false;
13630 }
13631
13632 // Make sure the input gets resized.
13633 setTimeout( this.onInputChange.bind( this ), 0 );
13634 }
13635 }
13636 };
13637
13638 /**
13639 * Handle key down events.
13640 *
13641 * @private
13642 * @param {jQuery.Event} e Key down event
13643 */
13644 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13645 if ( !this.isDisabled() ) {
13646 // 'keypress' event is not triggered for Backspace
13647 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13648 if ( this.items.length ) {
13649 this.removeItems( this.items.slice( -1 ) );
13650 }
13651 return false;
13652 }
13653 }
13654 };
13655
13656 /**
13657 * Handle input change events.
13658 *
13659 * @private
13660 * @param {jQuery.Event} e Event of some sort
13661 */
13662 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13663 if ( !this.isDisabled() ) {
13664 this.$input.width( this.$input.val().length + 'em' );
13665 }
13666 };
13667
13668 /**
13669 * Handle menu choose events.
13670 *
13671 * @private
13672 * @param {OO.ui.OptionWidget} item Chosen item
13673 */
13674 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13675 if ( item && item.isVisible() ) {
13676 this.addItemsFromData( [ item.getData() ] );
13677 this.clearInput();
13678 }
13679 };
13680
13681 /**
13682 * Handle menu item change events.
13683 *
13684 * @private
13685 */
13686 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13687 this.setItemsFromData( this.getItemsData() );
13688 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13689 };
13690
13691 /**
13692 * Clear the input field
13693 * @private
13694 */
13695 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13696 if ( this.$input ) {
13697 this.$input.val( '' );
13698 this.$input.width( '1em' );
13699 }
13700 if ( this.popup ) {
13701 this.popup.toggle( false );
13702 }
13703 this.menu.toggle( false );
13704 this.menu.selectItem();
13705 this.menu.highlightItem();
13706 };
13707
13708 /**
13709 * @inheritdoc
13710 */
13711 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13712 var i, len;
13713
13714 // Parent method
13715 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13716
13717 if ( this.$input ) {
13718 this.$input.prop( 'disabled', this.isDisabled() );
13719 }
13720 if ( this.menu ) {
13721 this.menu.setDisabled( this.isDisabled() );
13722 }
13723 if ( this.popup ) {
13724 this.popup.setDisabled( this.isDisabled() );
13725 }
13726
13727 if ( this.items ) {
13728 for ( i = 0, len = this.items.length; i < len; i++ ) {
13729 this.items[ i ].updateDisabled();
13730 }
13731 }
13732
13733 return this;
13734 };
13735
13736 /**
13737 * Focus the widget
13738 * @chainable
13739 * @return {OO.ui.CapsuleMultiSelectWidget}
13740 */
13741 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13742 if ( !this.isDisabled() ) {
13743 if ( this.popup ) {
13744 this.popup.setSize( this.$handle.width() );
13745 this.popup.toggle( true );
13746 this.popup.$element.find( '*' )
13747 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13748 .first()
13749 .focus();
13750 } else {
13751 this.menu.toggle( true );
13752 this.$input.focus();
13753 }
13754 }
13755 return this;
13756 };
13757
13758 /**
13759 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13760 * CapsuleMultiSelectWidget} to display the selected items.
13761 *
13762 * @class
13763 * @extends OO.ui.Widget
13764 * @mixins OO.ui.mixin.ItemWidget
13765 * @mixins OO.ui.mixin.IndicatorElement
13766 * @mixins OO.ui.mixin.LabelElement
13767 * @mixins OO.ui.mixin.FlaggedElement
13768 * @mixins OO.ui.mixin.TabIndexedElement
13769 *
13770 * @constructor
13771 * @param {Object} [config] Configuration options
13772 */
13773 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13774 // Configuration initialization
13775 config = config || {};
13776
13777 // Parent constructor
13778 OO.ui.CapsuleItemWidget.parent.call( this, config );
13779
13780 // Properties (must be set before mixin constructor calls)
13781 this.$indicator = $( '<span>' );
13782
13783 // Mixin constructors
13784 OO.ui.mixin.ItemWidget.call( this );
13785 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13786 OO.ui.mixin.LabelElement.call( this, config );
13787 OO.ui.mixin.FlaggedElement.call( this, config );
13788 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13789
13790 // Events
13791 this.$indicator.on( {
13792 keydown: this.onCloseKeyDown.bind( this ),
13793 click: this.onCloseClick.bind( this )
13794 } );
13795
13796 // Initialization
13797 this.$element
13798 .addClass( 'oo-ui-capsuleItemWidget' )
13799 .append( this.$indicator, this.$label );
13800 };
13801
13802 /* Setup */
13803
13804 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13805 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13806 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13807 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13808 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13809 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13810
13811 /* Methods */
13812
13813 /**
13814 * Handle close icon clicks
13815 * @param {jQuery.Event} event
13816 */
13817 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13818 var element = this.getElementGroup();
13819
13820 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13821 element.removeItems( [ this ] );
13822 element.focus();
13823 }
13824 };
13825
13826 /**
13827 * Handle close keyboard events
13828 * @param {jQuery.Event} event Key down event
13829 */
13830 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13831 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13832 switch ( e.which ) {
13833 case OO.ui.Keys.ENTER:
13834 case OO.ui.Keys.BACKSPACE:
13835 case OO.ui.Keys.SPACE:
13836 this.getElementGroup().removeItems( [ this ] );
13837 return false;
13838 }
13839 }
13840 };
13841
13842 /**
13843 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13844 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13845 * users can interact with it.
13846 *
13847 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13848 * OO.ui.DropdownInputWidget instead.
13849 *
13850 * @example
13851 * // Example: A DropdownWidget with a menu that contains three options
13852 * var dropDown = new OO.ui.DropdownWidget( {
13853 * label: 'Dropdown menu: Select a menu option',
13854 * menu: {
13855 * items: [
13856 * new OO.ui.MenuOptionWidget( {
13857 * data: 'a',
13858 * label: 'First'
13859 * } ),
13860 * new OO.ui.MenuOptionWidget( {
13861 * data: 'b',
13862 * label: 'Second'
13863 * } ),
13864 * new OO.ui.MenuOptionWidget( {
13865 * data: 'c',
13866 * label: 'Third'
13867 * } )
13868 * ]
13869 * }
13870 * } );
13871 *
13872 * $( 'body' ).append( dropDown.$element );
13873 *
13874 * dropDown.getMenu().selectItemByData( 'b' );
13875 *
13876 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13877 *
13878 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13879 *
13880 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13881 *
13882 * @class
13883 * @extends OO.ui.Widget
13884 * @mixins OO.ui.mixin.IconElement
13885 * @mixins OO.ui.mixin.IndicatorElement
13886 * @mixins OO.ui.mixin.LabelElement
13887 * @mixins OO.ui.mixin.TitledElement
13888 * @mixins OO.ui.mixin.TabIndexedElement
13889 *
13890 * @constructor
13891 * @param {Object} [config] Configuration options
13892 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13893 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13894 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13895 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13896 */
13897 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13898 // Configuration initialization
13899 config = $.extend( { indicator: 'down' }, config );
13900
13901 // Parent constructor
13902 OO.ui.DropdownWidget.parent.call( this, config );
13903
13904 // Properties (must be set before TabIndexedElement constructor call)
13905 this.$handle = this.$( '<span>' );
13906 this.$overlay = config.$overlay || this.$element;
13907
13908 // Mixin constructors
13909 OO.ui.mixin.IconElement.call( this, config );
13910 OO.ui.mixin.IndicatorElement.call( this, config );
13911 OO.ui.mixin.LabelElement.call( this, config );
13912 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13913 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13914
13915 // Properties
13916 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13917 widget: this,
13918 $container: this.$element
13919 }, config.menu ) );
13920
13921 // Events
13922 this.$handle.on( {
13923 click: this.onClick.bind( this ),
13924 keypress: this.onKeyPress.bind( this )
13925 } );
13926 this.menu.connect( this, { select: 'onMenuSelect' } );
13927
13928 // Initialization
13929 this.$handle
13930 .addClass( 'oo-ui-dropdownWidget-handle' )
13931 .append( this.$icon, this.$label, this.$indicator );
13932 this.$element
13933 .addClass( 'oo-ui-dropdownWidget' )
13934 .append( this.$handle );
13935 this.$overlay.append( this.menu.$element );
13936 };
13937
13938 /* Setup */
13939
13940 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13941 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13942 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13943 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13944 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13945 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13946
13947 /* Methods */
13948
13949 /**
13950 * Get the menu.
13951 *
13952 * @return {OO.ui.MenuSelectWidget} Menu of widget
13953 */
13954 OO.ui.DropdownWidget.prototype.getMenu = function () {
13955 return this.menu;
13956 };
13957
13958 /**
13959 * Handles menu select events.
13960 *
13961 * @private
13962 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13963 */
13964 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13965 var selectedLabel;
13966
13967 if ( !item ) {
13968 this.setLabel( null );
13969 return;
13970 }
13971
13972 selectedLabel = item.getLabel();
13973
13974 // If the label is a DOM element, clone it, because setLabel will append() it
13975 if ( selectedLabel instanceof jQuery ) {
13976 selectedLabel = selectedLabel.clone();
13977 }
13978
13979 this.setLabel( selectedLabel );
13980 };
13981
13982 /**
13983 * Handle mouse click events.
13984 *
13985 * @private
13986 * @param {jQuery.Event} e Mouse click event
13987 */
13988 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13989 if ( !this.isDisabled() && e.which === 1 ) {
13990 this.menu.toggle();
13991 }
13992 return false;
13993 };
13994
13995 /**
13996 * Handle key press events.
13997 *
13998 * @private
13999 * @param {jQuery.Event} e Key press event
14000 */
14001 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14002 if ( !this.isDisabled() &&
14003 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14004 ) {
14005 this.menu.toggle();
14006 return false;
14007 }
14008 };
14009
14010 /**
14011 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14012 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14013 * OO.ui.mixin.IndicatorElement indicators}.
14014 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14015 *
14016 * @example
14017 * // Example of a file select widget
14018 * var selectFile = new OO.ui.SelectFileWidget();
14019 * $( 'body' ).append( selectFile.$element );
14020 *
14021 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14022 *
14023 * @class
14024 * @extends OO.ui.Widget
14025 * @mixins OO.ui.mixin.IconElement
14026 * @mixins OO.ui.mixin.IndicatorElement
14027 * @mixins OO.ui.mixin.PendingElement
14028 * @mixins OO.ui.mixin.LabelElement
14029 *
14030 * @constructor
14031 * @param {Object} [config] Configuration options
14032 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14033 * @cfg {string} [placeholder] Text to display when no file is selected.
14034 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14035 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14036 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14037 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14038 */
14039 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14040 var dragHandler;
14041
14042 // TODO: Remove in next release
14043 if ( config && config.dragDropUI ) {
14044 config.showDropTarget = true;
14045 }
14046
14047 // Configuration initialization
14048 config = $.extend( {
14049 accept: null,
14050 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14051 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14052 droppable: true,
14053 showDropTarget: false
14054 }, config );
14055
14056 // Parent constructor
14057 OO.ui.SelectFileWidget.parent.call( this, config );
14058
14059 // Mixin constructors
14060 OO.ui.mixin.IconElement.call( this, config );
14061 OO.ui.mixin.IndicatorElement.call( this, config );
14062 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14063 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14064
14065 // Properties
14066 this.$info = $( '<span>' );
14067
14068 // Properties
14069 this.showDropTarget = config.showDropTarget;
14070 this.isSupported = this.constructor.static.isSupported();
14071 this.currentFile = null;
14072 if ( Array.isArray( config.accept ) ) {
14073 this.accept = config.accept;
14074 } else {
14075 this.accept = null;
14076 }
14077 this.placeholder = config.placeholder;
14078 this.notsupported = config.notsupported;
14079 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14080
14081 this.selectButton = new OO.ui.ButtonWidget( {
14082 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14083 label: 'Select a file',
14084 disabled: this.disabled || !this.isSupported
14085 } );
14086
14087 this.clearButton = new OO.ui.ButtonWidget( {
14088 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14089 framed: false,
14090 icon: 'remove',
14091 disabled: this.disabled
14092 } );
14093
14094 // Events
14095 this.selectButton.$button.on( {
14096 keypress: this.onKeyPress.bind( this )
14097 } );
14098 this.clearButton.connect( this, {
14099 click: 'onClearClick'
14100 } );
14101 if ( config.droppable ) {
14102 dragHandler = this.onDragEnterOrOver.bind( this );
14103 this.$element.on( {
14104 dragenter: dragHandler,
14105 dragover: dragHandler,
14106 dragleave: this.onDragLeave.bind( this ),
14107 drop: this.onDrop.bind( this )
14108 } );
14109 }
14110
14111 // Initialization
14112 this.addInput();
14113 this.updateUI();
14114 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14115 this.$info
14116 .addClass( 'oo-ui-selectFileWidget-info' )
14117 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14118 this.$element
14119 .addClass( 'oo-ui-selectFileWidget' )
14120 .append( this.$info, this.selectButton.$element );
14121 if ( config.droppable && config.showDropTarget ) {
14122 this.$dropTarget = $( '<div>' )
14123 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14124 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14125 .on( {
14126 click: this.onDropTargetClick.bind( this )
14127 } );
14128 this.$element.prepend( this.$dropTarget );
14129 }
14130 };
14131
14132 /* Setup */
14133
14134 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14135 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14136 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14137 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14138 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14139
14140 /* Static Properties */
14141
14142 /**
14143 * Check if this widget is supported
14144 *
14145 * @static
14146 * @return {boolean}
14147 */
14148 OO.ui.SelectFileWidget.static.isSupported = function () {
14149 var $input;
14150 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14151 $input = $( '<input type="file">' );
14152 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14153 }
14154 return OO.ui.SelectFileWidget.static.isSupportedCache;
14155 };
14156
14157 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14158
14159 /* Events */
14160
14161 /**
14162 * @event change
14163 *
14164 * A change event is emitted when the on/off state of the toggle changes.
14165 *
14166 * @param {File|null} value New value
14167 */
14168
14169 /* Methods */
14170
14171 /**
14172 * Get the current value of the field
14173 *
14174 * @return {File|null}
14175 */
14176 OO.ui.SelectFileWidget.prototype.getValue = function () {
14177 return this.currentFile;
14178 };
14179
14180 /**
14181 * Set the current value of the field
14182 *
14183 * @param {File|null} file File to select
14184 */
14185 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14186 if ( this.currentFile !== file ) {
14187 this.currentFile = file;
14188 this.updateUI();
14189 this.emit( 'change', this.currentFile );
14190 }
14191 };
14192
14193 /**
14194 * Focus the widget.
14195 *
14196 * Focusses the select file button.
14197 *
14198 * @chainable
14199 */
14200 OO.ui.SelectFileWidget.prototype.focus = function () {
14201 this.selectButton.$button[ 0 ].focus();
14202 return this;
14203 };
14204
14205 /**
14206 * Update the user interface when a file is selected or unselected
14207 *
14208 * @protected
14209 */
14210 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14211 var $label;
14212 if ( !this.isSupported ) {
14213 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14214 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14215 this.setLabel( this.notsupported );
14216 } else {
14217 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14218 if ( this.currentFile ) {
14219 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14220 $label = $( [] );
14221 if ( this.currentFile.type !== '' ) {
14222 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14223 }
14224 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14225 this.setLabel( $label );
14226 } else {
14227 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14228 this.setLabel( this.placeholder );
14229 }
14230 }
14231
14232 if ( this.$input ) {
14233 this.$input.attr( 'title', this.getLabel() );
14234 }
14235 };
14236
14237 /**
14238 * Add the input to the widget
14239 *
14240 * @private
14241 */
14242 OO.ui.SelectFileWidget.prototype.addInput = function () {
14243 if ( this.$input ) {
14244 this.$input.remove();
14245 }
14246
14247 if ( !this.isSupported ) {
14248 this.$input = null;
14249 return;
14250 }
14251
14252 this.$input = $( '<input type="file">' );
14253 this.$input.on( 'change', this.onFileSelectedHandler );
14254 this.$input.attr( {
14255 tabindex: -1,
14256 title: this.getLabel()
14257 } );
14258 if ( this.accept ) {
14259 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14260 }
14261 this.selectButton.$button.append( this.$input );
14262 };
14263
14264 /**
14265 * Determine if we should accept this file
14266 *
14267 * @private
14268 * @param {string} File MIME type
14269 * @return {boolean}
14270 */
14271 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14272 var i, mimeTest;
14273
14274 if ( !this.accept || !mimeType ) {
14275 return true;
14276 }
14277
14278 for ( i = 0; i < this.accept.length; i++ ) {
14279 mimeTest = this.accept[ i ];
14280 if ( mimeTest === mimeType ) {
14281 return true;
14282 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14283 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14284 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14285 return true;
14286 }
14287 }
14288 }
14289
14290 return false;
14291 };
14292
14293 /**
14294 * Handle file selection from the input
14295 *
14296 * @private
14297 * @param {jQuery.Event} e
14298 */
14299 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14300 var file = OO.getProp( e.target, 'files', 0 ) || null;
14301
14302 if ( file && !this.isAllowedType( file.type ) ) {
14303 file = null;
14304 }
14305
14306 this.setValue( file );
14307 this.addInput();
14308 };
14309
14310 /**
14311 * Handle clear button click events.
14312 *
14313 * @private
14314 */
14315 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14316 this.setValue( null );
14317 return false;
14318 };
14319
14320 /**
14321 * Handle key press events.
14322 *
14323 * @private
14324 * @param {jQuery.Event} e Key press event
14325 */
14326 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14327 if ( this.isSupported && !this.isDisabled() && this.$input &&
14328 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14329 ) {
14330 this.$input.click();
14331 return false;
14332 }
14333 };
14334
14335 /**
14336 * Handle drop target click events.
14337 *
14338 * @private
14339 * @param {jQuery.Event} e Key press event
14340 */
14341 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14342 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14343 this.$input.click();
14344 return false;
14345 }
14346 };
14347
14348 /**
14349 * Handle drag enter and over events
14350 *
14351 * @private
14352 * @param {jQuery.Event} e Drag event
14353 */
14354 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14355 var itemOrFile,
14356 droppableFile = false,
14357 dt = e.originalEvent.dataTransfer;
14358
14359 e.preventDefault();
14360 e.stopPropagation();
14361
14362 if ( this.isDisabled() || !this.isSupported ) {
14363 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14364 dt.dropEffect = 'none';
14365 return false;
14366 }
14367
14368 // DataTransferItem and File both have a type property, but in Chrome files
14369 // have no information at this point.
14370 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14371 if ( itemOrFile ) {
14372 if ( this.isAllowedType( itemOrFile.type ) ) {
14373 droppableFile = true;
14374 }
14375 // dt.types is Array-like, but not an Array
14376 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14377 // File information is not available at this point for security so just assume
14378 // it is acceptable for now.
14379 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14380 droppableFile = true;
14381 }
14382
14383 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14384 if ( !droppableFile ) {
14385 dt.dropEffect = 'none';
14386 }
14387
14388 return false;
14389 };
14390
14391 /**
14392 * Handle drag leave events
14393 *
14394 * @private
14395 * @param {jQuery.Event} e Drag event
14396 */
14397 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14398 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14399 };
14400
14401 /**
14402 * Handle drop events
14403 *
14404 * @private
14405 * @param {jQuery.Event} e Drop event
14406 */
14407 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14408 var file = null,
14409 dt = e.originalEvent.dataTransfer;
14410
14411 e.preventDefault();
14412 e.stopPropagation();
14413 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14414
14415 if ( this.isDisabled() || !this.isSupported ) {
14416 return false;
14417 }
14418
14419 file = OO.getProp( dt, 'files', 0 );
14420 if ( file && !this.isAllowedType( file.type ) ) {
14421 file = null;
14422 }
14423 if ( file ) {
14424 this.setValue( file );
14425 }
14426
14427 return false;
14428 };
14429
14430 /**
14431 * @inheritdoc
14432 */
14433 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14434 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14435 if ( this.selectButton ) {
14436 this.selectButton.setDisabled( disabled );
14437 }
14438 if ( this.clearButton ) {
14439 this.clearButton.setDisabled( disabled );
14440 }
14441 return this;
14442 };
14443
14444 /**
14445 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14446 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14447 * for a list of icons included in the library.
14448 *
14449 * @example
14450 * // An icon widget with a label
14451 * var myIcon = new OO.ui.IconWidget( {
14452 * icon: 'help',
14453 * iconTitle: 'Help'
14454 * } );
14455 * // Create a label.
14456 * var iconLabel = new OO.ui.LabelWidget( {
14457 * label: 'Help'
14458 * } );
14459 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14460 *
14461 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14462 *
14463 * @class
14464 * @extends OO.ui.Widget
14465 * @mixins OO.ui.mixin.IconElement
14466 * @mixins OO.ui.mixin.TitledElement
14467 * @mixins OO.ui.mixin.FlaggedElement
14468 *
14469 * @constructor
14470 * @param {Object} [config] Configuration options
14471 */
14472 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14473 // Configuration initialization
14474 config = config || {};
14475
14476 // Parent constructor
14477 OO.ui.IconWidget.parent.call( this, config );
14478
14479 // Mixin constructors
14480 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14481 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14482 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14483
14484 // Initialization
14485 this.$element.addClass( 'oo-ui-iconWidget' );
14486 };
14487
14488 /* Setup */
14489
14490 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14491 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14492 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14493 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14494
14495 /* Static Properties */
14496
14497 OO.ui.IconWidget.static.tagName = 'span';
14498
14499 /**
14500 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14501 * attention to the status of an item or to clarify the function of a control. For a list of
14502 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14503 *
14504 * @example
14505 * // Example of an indicator widget
14506 * var indicator1 = new OO.ui.IndicatorWidget( {
14507 * indicator: 'alert'
14508 * } );
14509 *
14510 * // Create a fieldset layout to add a label
14511 * var fieldset = new OO.ui.FieldsetLayout();
14512 * fieldset.addItems( [
14513 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14514 * ] );
14515 * $( 'body' ).append( fieldset.$element );
14516 *
14517 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14518 *
14519 * @class
14520 * @extends OO.ui.Widget
14521 * @mixins OO.ui.mixin.IndicatorElement
14522 * @mixins OO.ui.mixin.TitledElement
14523 *
14524 * @constructor
14525 * @param {Object} [config] Configuration options
14526 */
14527 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14528 // Configuration initialization
14529 config = config || {};
14530
14531 // Parent constructor
14532 OO.ui.IndicatorWidget.parent.call( this, config );
14533
14534 // Mixin constructors
14535 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14536 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14537
14538 // Initialization
14539 this.$element.addClass( 'oo-ui-indicatorWidget' );
14540 };
14541
14542 /* Setup */
14543
14544 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14545 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14546 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14547
14548 /* Static Properties */
14549
14550 OO.ui.IndicatorWidget.static.tagName = 'span';
14551
14552 /**
14553 * InputWidget is the base class for all input widgets, which
14554 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14555 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14556 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14557 *
14558 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14559 *
14560 * @abstract
14561 * @class
14562 * @extends OO.ui.Widget
14563 * @mixins OO.ui.mixin.FlaggedElement
14564 * @mixins OO.ui.mixin.TabIndexedElement
14565 * @mixins OO.ui.mixin.TitledElement
14566 * @mixins OO.ui.mixin.AccessKeyedElement
14567 *
14568 * @constructor
14569 * @param {Object} [config] Configuration options
14570 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14571 * @cfg {string} [value=''] The value of the input.
14572 * @cfg {string} [accessKey=''] The access key of the input.
14573 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14574 * before it is accepted.
14575 */
14576 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14577 // Configuration initialization
14578 config = config || {};
14579
14580 // Parent constructor
14581 OO.ui.InputWidget.parent.call( this, config );
14582
14583 // Properties
14584 this.$input = this.getInputElement( config );
14585 this.value = '';
14586 this.inputFilter = config.inputFilter;
14587
14588 // Mixin constructors
14589 OO.ui.mixin.FlaggedElement.call( this, config );
14590 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14591 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14592 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14593
14594 // Events
14595 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14596
14597 // Initialization
14598 this.$input
14599 .addClass( 'oo-ui-inputWidget-input' )
14600 .attr( 'name', config.name )
14601 .prop( 'disabled', this.isDisabled() );
14602 this.$element
14603 .addClass( 'oo-ui-inputWidget' )
14604 .append( this.$input );
14605 this.setValue( config.value );
14606 this.setAccessKey( config.accessKey );
14607 };
14608
14609 /* Setup */
14610
14611 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14612 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14613 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14614 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14615 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14616
14617 /* Static Properties */
14618
14619 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14620
14621 /* Static Methods */
14622
14623 /**
14624 * @inheritdoc
14625 */
14626 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14627 var
14628 state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config ),
14629 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14630 state.value = $input.val();
14631 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14632 state.focus = $input.is( ':focus' );
14633 return state;
14634 };
14635
14636 /* Events */
14637
14638 /**
14639 * @event change
14640 *
14641 * A change event is emitted when the value of the input changes.
14642 *
14643 * @param {string} value
14644 */
14645
14646 /* Methods */
14647
14648 /**
14649 * Get input element.
14650 *
14651 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14652 * different circumstances. The element must have a `value` property (like form elements).
14653 *
14654 * @protected
14655 * @param {Object} config Configuration options
14656 * @return {jQuery} Input element
14657 */
14658 OO.ui.InputWidget.prototype.getInputElement = function () {
14659 return $( '<input>' );
14660 };
14661
14662 /**
14663 * Handle potentially value-changing events.
14664 *
14665 * @private
14666 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14667 */
14668 OO.ui.InputWidget.prototype.onEdit = function () {
14669 var widget = this;
14670 if ( !this.isDisabled() ) {
14671 // Allow the stack to clear so the value will be updated
14672 setTimeout( function () {
14673 widget.setValue( widget.$input.val() );
14674 } );
14675 }
14676 };
14677
14678 /**
14679 * Get the value of the input.
14680 *
14681 * @return {string} Input value
14682 */
14683 OO.ui.InputWidget.prototype.getValue = function () {
14684 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14685 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14686 var value = this.$input.val();
14687 if ( this.value !== value ) {
14688 this.setValue( value );
14689 }
14690 return this.value;
14691 };
14692
14693 /**
14694 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14695 *
14696 * @param {boolean} isRTL
14697 * Direction is right-to-left
14698 */
14699 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14700 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14701 };
14702
14703 /**
14704 * Set the value of the input.
14705 *
14706 * @param {string} value New value
14707 * @fires change
14708 * @chainable
14709 */
14710 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14711 value = this.cleanUpValue( value );
14712 // Update the DOM if it has changed. Note that with cleanUpValue, it
14713 // is possible for the DOM value to change without this.value changing.
14714 if ( this.$input.val() !== value ) {
14715 this.$input.val( value );
14716 }
14717 if ( this.value !== value ) {
14718 this.value = value;
14719 this.emit( 'change', this.value );
14720 }
14721 return this;
14722 };
14723
14724 /**
14725 * Set the input's access key.
14726 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14727 *
14728 * @param {string} accessKey Input's access key, use empty string to remove
14729 * @chainable
14730 */
14731 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14732 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14733
14734 if ( this.accessKey !== accessKey ) {
14735 if ( this.$input ) {
14736 if ( accessKey !== null ) {
14737 this.$input.attr( 'accesskey', accessKey );
14738 } else {
14739 this.$input.removeAttr( 'accesskey' );
14740 }
14741 }
14742 this.accessKey = accessKey;
14743 }
14744
14745 return this;
14746 };
14747
14748 /**
14749 * Clean up incoming value.
14750 *
14751 * Ensures value is a string, and converts undefined and null to empty string.
14752 *
14753 * @private
14754 * @param {string} value Original value
14755 * @return {string} Cleaned up value
14756 */
14757 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14758 if ( value === undefined || value === null ) {
14759 return '';
14760 } else if ( this.inputFilter ) {
14761 return this.inputFilter( String( value ) );
14762 } else {
14763 return String( value );
14764 }
14765 };
14766
14767 /**
14768 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14769 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14770 * called directly.
14771 */
14772 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14773 if ( !this.isDisabled() ) {
14774 if ( this.$input.is( ':checkbox, :radio' ) ) {
14775 this.$input.click();
14776 }
14777 if ( this.$input.is( ':input' ) ) {
14778 this.$input[ 0 ].focus();
14779 }
14780 }
14781 };
14782
14783 /**
14784 * @inheritdoc
14785 */
14786 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14787 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14788 if ( this.$input ) {
14789 this.$input.prop( 'disabled', this.isDisabled() );
14790 }
14791 return this;
14792 };
14793
14794 /**
14795 * Focus the input.
14796 *
14797 * @chainable
14798 */
14799 OO.ui.InputWidget.prototype.focus = function () {
14800 this.$input[ 0 ].focus();
14801 return this;
14802 };
14803
14804 /**
14805 * Blur the input.
14806 *
14807 * @chainable
14808 */
14809 OO.ui.InputWidget.prototype.blur = function () {
14810 this.$input[ 0 ].blur();
14811 return this;
14812 };
14813
14814 /**
14815 * @inheritdoc
14816 */
14817 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14818 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14819 if ( state.value !== undefined && state.value !== this.getValue() ) {
14820 this.setValue( state.value );
14821 }
14822 if ( state.focus ) {
14823 this.focus();
14824 }
14825 };
14826
14827 /**
14828 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14829 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14830 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14831 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14832 * [OOjs UI documentation on MediaWiki] [1] for more information.
14833 *
14834 * @example
14835 * // A ButtonInputWidget rendered as an HTML button, the default.
14836 * var button = new OO.ui.ButtonInputWidget( {
14837 * label: 'Input button',
14838 * icon: 'check',
14839 * value: 'check'
14840 * } );
14841 * $( 'body' ).append( button.$element );
14842 *
14843 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14844 *
14845 * @class
14846 * @extends OO.ui.InputWidget
14847 * @mixins OO.ui.mixin.ButtonElement
14848 * @mixins OO.ui.mixin.IconElement
14849 * @mixins OO.ui.mixin.IndicatorElement
14850 * @mixins OO.ui.mixin.LabelElement
14851 * @mixins OO.ui.mixin.TitledElement
14852 *
14853 * @constructor
14854 * @param {Object} [config] Configuration options
14855 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14856 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14857 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14858 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14859 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14860 */
14861 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14862 // Configuration initialization
14863 config = $.extend( { type: 'button', useInputTag: false }, config );
14864
14865 // Properties (must be set before parent constructor, which calls #setValue)
14866 this.useInputTag = config.useInputTag;
14867
14868 // Parent constructor
14869 OO.ui.ButtonInputWidget.parent.call( this, config );
14870
14871 // Mixin constructors
14872 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14873 OO.ui.mixin.IconElement.call( this, config );
14874 OO.ui.mixin.IndicatorElement.call( this, config );
14875 OO.ui.mixin.LabelElement.call( this, config );
14876 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14877
14878 // Initialization
14879 if ( !config.useInputTag ) {
14880 this.$input.append( this.$icon, this.$label, this.$indicator );
14881 }
14882 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14883 };
14884
14885 /* Setup */
14886
14887 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14888 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14889 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14890 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14891 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14892 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14893
14894 /* Static Properties */
14895
14896 /**
14897 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14898 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14899 */
14900 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14901
14902 /* Methods */
14903
14904 /**
14905 * @inheritdoc
14906 * @protected
14907 */
14908 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14909 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14910 config.type :
14911 'button';
14912 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14913 };
14914
14915 /**
14916 * Set label value.
14917 *
14918 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14919 *
14920 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14921 * text, or `null` for no label
14922 * @chainable
14923 */
14924 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14925 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14926
14927 if ( this.useInputTag ) {
14928 if ( typeof label === 'function' ) {
14929 label = OO.ui.resolveMsg( label );
14930 }
14931 if ( label instanceof jQuery ) {
14932 label = label.text();
14933 }
14934 if ( !label ) {
14935 label = '';
14936 }
14937 this.$input.val( label );
14938 }
14939
14940 return this;
14941 };
14942
14943 /**
14944 * Set the value of the input.
14945 *
14946 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14947 * they do not support {@link #value values}.
14948 *
14949 * @param {string} value New value
14950 * @chainable
14951 */
14952 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14953 if ( !this.useInputTag ) {
14954 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14955 }
14956 return this;
14957 };
14958
14959 /**
14960 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14961 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14962 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14963 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14964 *
14965 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14966 *
14967 * @example
14968 * // An example of selected, unselected, and disabled checkbox inputs
14969 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14970 * value: 'a',
14971 * selected: true
14972 * } );
14973 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14974 * value: 'b'
14975 * } );
14976 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14977 * value:'c',
14978 * disabled: true
14979 * } );
14980 * // Create a fieldset layout with fields for each checkbox.
14981 * var fieldset = new OO.ui.FieldsetLayout( {
14982 * label: 'Checkboxes'
14983 * } );
14984 * fieldset.addItems( [
14985 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14986 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14987 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14988 * ] );
14989 * $( 'body' ).append( fieldset.$element );
14990 *
14991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14992 *
14993 * @class
14994 * @extends OO.ui.InputWidget
14995 *
14996 * @constructor
14997 * @param {Object} [config] Configuration options
14998 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14999 */
15000 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15001 // Configuration initialization
15002 config = config || {};
15003
15004 // Parent constructor
15005 OO.ui.CheckboxInputWidget.parent.call( this, config );
15006
15007 // Initialization
15008 this.$element
15009 .addClass( 'oo-ui-checkboxInputWidget' )
15010 // Required for pretty styling in MediaWiki theme
15011 .append( $( '<span>' ) );
15012 this.setSelected( config.selected !== undefined ? config.selected : false );
15013 };
15014
15015 /* Setup */
15016
15017 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15018
15019 /* Static Methods */
15020
15021 /**
15022 * @inheritdoc
15023 */
15024 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15025 var
15026 state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config ),
15027 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15028 state.$input = $input; // shortcut for performance, used in InputWidget
15029 state.checked = $input.prop( 'checked' );
15030 return state;
15031 };
15032
15033 /* Methods */
15034
15035 /**
15036 * @inheritdoc
15037 * @protected
15038 */
15039 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15040 return $( '<input type="checkbox" />' );
15041 };
15042
15043 /**
15044 * @inheritdoc
15045 */
15046 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15047 var widget = this;
15048 if ( !this.isDisabled() ) {
15049 // Allow the stack to clear so the value will be updated
15050 setTimeout( function () {
15051 widget.setSelected( widget.$input.prop( 'checked' ) );
15052 } );
15053 }
15054 };
15055
15056 /**
15057 * Set selection state of this checkbox.
15058 *
15059 * @param {boolean} state `true` for selected
15060 * @chainable
15061 */
15062 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15063 state = !!state;
15064 if ( this.selected !== state ) {
15065 this.selected = state;
15066 this.$input.prop( 'checked', this.selected );
15067 this.emit( 'change', this.selected );
15068 }
15069 return this;
15070 };
15071
15072 /**
15073 * Check if this checkbox is selected.
15074 *
15075 * @return {boolean} Checkbox is selected
15076 */
15077 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15078 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15079 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15080 var selected = this.$input.prop( 'checked' );
15081 if ( this.selected !== selected ) {
15082 this.setSelected( selected );
15083 }
15084 return this.selected;
15085 };
15086
15087 /**
15088 * @inheritdoc
15089 */
15090 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15091 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15092 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15093 this.setSelected( state.checked );
15094 }
15095 };
15096
15097 /**
15098 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15099 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15100 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15101 * more information about input widgets.
15102 *
15103 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15104 * are no options. If no `value` configuration option is provided, the first option is selected.
15105 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15106 *
15107 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15108 *
15109 * @example
15110 * // Example: A DropdownInputWidget with three options
15111 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15112 * options: [
15113 * { data: 'a', label: 'First' },
15114 * { data: 'b', label: 'Second'},
15115 * { data: 'c', label: 'Third' }
15116 * ]
15117 * } );
15118 * $( 'body' ).append( dropdownInput.$element );
15119 *
15120 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15121 *
15122 * @class
15123 * @extends OO.ui.InputWidget
15124 * @mixins OO.ui.mixin.TitledElement
15125 *
15126 * @constructor
15127 * @param {Object} [config] Configuration options
15128 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15129 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15130 */
15131 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15132 // Configuration initialization
15133 config = config || {};
15134
15135 // Properties (must be done before parent constructor which calls #setDisabled)
15136 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15137
15138 // Parent constructor
15139 OO.ui.DropdownInputWidget.parent.call( this, config );
15140
15141 // Mixin constructors
15142 OO.ui.mixin.TitledElement.call( this, config );
15143
15144 // Events
15145 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15146
15147 // Initialization
15148 this.setOptions( config.options || [] );
15149 this.$element
15150 .addClass( 'oo-ui-dropdownInputWidget' )
15151 .append( this.dropdownWidget.$element );
15152 };
15153
15154 /* Setup */
15155
15156 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15157 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15158
15159 /* Methods */
15160
15161 /**
15162 * @inheritdoc
15163 * @protected
15164 */
15165 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
15166 return $( '<input type="hidden">' );
15167 };
15168
15169 /**
15170 * Handles menu select events.
15171 *
15172 * @private
15173 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15174 */
15175 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15176 this.setValue( item.getData() );
15177 };
15178
15179 /**
15180 * @inheritdoc
15181 */
15182 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15183 value = this.cleanUpValue( value );
15184 this.dropdownWidget.getMenu().selectItemByData( value );
15185 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15186 return this;
15187 };
15188
15189 /**
15190 * @inheritdoc
15191 */
15192 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15193 this.dropdownWidget.setDisabled( state );
15194 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15195 return this;
15196 };
15197
15198 /**
15199 * Set the options available for this input.
15200 *
15201 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15202 * @chainable
15203 */
15204 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15205 var
15206 value = this.getValue(),
15207 widget = this;
15208
15209 // Rebuild the dropdown menu
15210 this.dropdownWidget.getMenu()
15211 .clearItems()
15212 .addItems( options.map( function ( opt ) {
15213 var optValue = widget.cleanUpValue( opt.data );
15214 return new OO.ui.MenuOptionWidget( {
15215 data: optValue,
15216 label: opt.label !== undefined ? opt.label : optValue
15217 } );
15218 } ) );
15219
15220 // Restore the previous value, or reset to something sensible
15221 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15222 // Previous value is still available, ensure consistency with the dropdown
15223 this.setValue( value );
15224 } else {
15225 // No longer valid, reset
15226 if ( options.length ) {
15227 this.setValue( options[ 0 ].data );
15228 }
15229 }
15230
15231 return this;
15232 };
15233
15234 /**
15235 * @inheritdoc
15236 */
15237 OO.ui.DropdownInputWidget.prototype.focus = function () {
15238 this.dropdownWidget.getMenu().toggle( true );
15239 return this;
15240 };
15241
15242 /**
15243 * @inheritdoc
15244 */
15245 OO.ui.DropdownInputWidget.prototype.blur = function () {
15246 this.dropdownWidget.getMenu().toggle( false );
15247 return this;
15248 };
15249
15250 /**
15251 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15252 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15253 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15254 * please see the [OOjs UI documentation on MediaWiki][1].
15255 *
15256 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15257 *
15258 * @example
15259 * // An example of selected, unselected, and disabled radio inputs
15260 * var radio1 = new OO.ui.RadioInputWidget( {
15261 * value: 'a',
15262 * selected: true
15263 * } );
15264 * var radio2 = new OO.ui.RadioInputWidget( {
15265 * value: 'b'
15266 * } );
15267 * var radio3 = new OO.ui.RadioInputWidget( {
15268 * value: 'c',
15269 * disabled: true
15270 * } );
15271 * // Create a fieldset layout with fields for each radio button.
15272 * var fieldset = new OO.ui.FieldsetLayout( {
15273 * label: 'Radio inputs'
15274 * } );
15275 * fieldset.addItems( [
15276 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15277 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15278 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15279 * ] );
15280 * $( 'body' ).append( fieldset.$element );
15281 *
15282 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15283 *
15284 * @class
15285 * @extends OO.ui.InputWidget
15286 *
15287 * @constructor
15288 * @param {Object} [config] Configuration options
15289 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15290 */
15291 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15292 // Configuration initialization
15293 config = config || {};
15294
15295 // Parent constructor
15296 OO.ui.RadioInputWidget.parent.call( this, config );
15297
15298 // Initialization
15299 this.$element
15300 .addClass( 'oo-ui-radioInputWidget' )
15301 // Required for pretty styling in MediaWiki theme
15302 .append( $( '<span>' ) );
15303 this.setSelected( config.selected !== undefined ? config.selected : false );
15304 };
15305
15306 /* Setup */
15307
15308 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15309
15310 /* Static Methods */
15311
15312 /**
15313 * @inheritdoc
15314 */
15315 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15316 var
15317 state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config ),
15318 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15319 state.$input = $input; // shortcut for performance, used in InputWidget
15320 state.checked = $input.prop( 'checked' );
15321 return state;
15322 };
15323
15324 /* Methods */
15325
15326 /**
15327 * @inheritdoc
15328 * @protected
15329 */
15330 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15331 return $( '<input type="radio" />' );
15332 };
15333
15334 /**
15335 * @inheritdoc
15336 */
15337 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15338 // RadioInputWidget doesn't track its state.
15339 };
15340
15341 /**
15342 * Set selection state of this radio button.
15343 *
15344 * @param {boolean} state `true` for selected
15345 * @chainable
15346 */
15347 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15348 // RadioInputWidget doesn't track its state.
15349 this.$input.prop( 'checked', state );
15350 return this;
15351 };
15352
15353 /**
15354 * Check if this radio button is selected.
15355 *
15356 * @return {boolean} Radio is selected
15357 */
15358 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15359 return this.$input.prop( 'checked' );
15360 };
15361
15362 /**
15363 * @inheritdoc
15364 */
15365 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15366 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15367 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15368 this.setSelected( state.checked );
15369 }
15370 };
15371
15372 /**
15373 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15374 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15375 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15376 * more information about input widgets.
15377 *
15378 * This and OO.ui.DropdownInputWidget support the same configuration options.
15379 *
15380 * @example
15381 * // Example: A RadioSelectInputWidget with three options
15382 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15383 * options: [
15384 * { data: 'a', label: 'First' },
15385 * { data: 'b', label: 'Second'},
15386 * { data: 'c', label: 'Third' }
15387 * ]
15388 * } );
15389 * $( 'body' ).append( radioSelectInput.$element );
15390 *
15391 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15392 *
15393 * @class
15394 * @extends OO.ui.InputWidget
15395 *
15396 * @constructor
15397 * @param {Object} [config] Configuration options
15398 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15399 */
15400 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15401 // Configuration initialization
15402 config = config || {};
15403
15404 // Properties (must be done before parent constructor which calls #setDisabled)
15405 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15406
15407 // Parent constructor
15408 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15409
15410 // Events
15411 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15412
15413 // Initialization
15414 this.setOptions( config.options || [] );
15415 this.$element
15416 .addClass( 'oo-ui-radioSelectInputWidget' )
15417 .append( this.radioSelectWidget.$element );
15418 };
15419
15420 /* Setup */
15421
15422 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15423
15424 /* Static Properties */
15425
15426 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15427
15428 /* Static Methods */
15429
15430 /**
15431 * @inheritdoc
15432 */
15433 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15434 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15435 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15436 return state;
15437 };
15438
15439 /* Methods */
15440
15441 /**
15442 * @inheritdoc
15443 * @protected
15444 */
15445 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15446 return $( '<input type="hidden">' );
15447 };
15448
15449 /**
15450 * Handles menu select events.
15451 *
15452 * @private
15453 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15454 */
15455 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15456 this.setValue( item.getData() );
15457 };
15458
15459 /**
15460 * @inheritdoc
15461 */
15462 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15463 value = this.cleanUpValue( value );
15464 this.radioSelectWidget.selectItemByData( value );
15465 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15466 return this;
15467 };
15468
15469 /**
15470 * @inheritdoc
15471 */
15472 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15473 this.radioSelectWidget.setDisabled( state );
15474 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15475 return this;
15476 };
15477
15478 /**
15479 * Set the options available for this input.
15480 *
15481 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15482 * @chainable
15483 */
15484 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15485 var
15486 value = this.getValue(),
15487 widget = this;
15488
15489 // Rebuild the radioSelect menu
15490 this.radioSelectWidget
15491 .clearItems()
15492 .addItems( options.map( function ( opt ) {
15493 var optValue = widget.cleanUpValue( opt.data );
15494 return new OO.ui.RadioOptionWidget( {
15495 data: optValue,
15496 label: opt.label !== undefined ? opt.label : optValue
15497 } );
15498 } ) );
15499
15500 // Restore the previous value, or reset to something sensible
15501 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15502 // Previous value is still available, ensure consistency with the radioSelect
15503 this.setValue( value );
15504 } else {
15505 // No longer valid, reset
15506 if ( options.length ) {
15507 this.setValue( options[ 0 ].data );
15508 }
15509 }
15510
15511 return this;
15512 };
15513
15514 /**
15515 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15516 * size of the field as well as its presentation. In addition, these widgets can be configured
15517 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15518 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15519 * which modifies incoming values rather than validating them.
15520 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15521 *
15522 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15523 *
15524 * @example
15525 * // Example of a text input widget
15526 * var textInput = new OO.ui.TextInputWidget( {
15527 * value: 'Text input'
15528 * } )
15529 * $( 'body' ).append( textInput.$element );
15530 *
15531 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15532 *
15533 * @class
15534 * @extends OO.ui.InputWidget
15535 * @mixins OO.ui.mixin.IconElement
15536 * @mixins OO.ui.mixin.IndicatorElement
15537 * @mixins OO.ui.mixin.PendingElement
15538 * @mixins OO.ui.mixin.LabelElement
15539 *
15540 * @constructor
15541 * @param {Object} [config] Configuration options
15542 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15543 * 'email' or 'url'. Ignored if `multiline` is true.
15544 *
15545 * Some values of `type` result in additional behaviors:
15546 *
15547 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15548 * empties the text field
15549 * @cfg {string} [placeholder] Placeholder text
15550 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15551 * instruct the browser to focus this widget.
15552 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15553 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15554 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15555 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15556 * specifies minimum number of rows to display.
15557 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15558 * Use the #maxRows config to specify a maximum number of displayed rows.
15559 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15560 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15561 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15562 * the value or placeholder text: `'before'` or `'after'`
15563 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15564 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15565 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15566 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15567 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15568 * value for it to be considered valid; when Function, a function receiving the value as parameter
15569 * that must return true, or promise resolving to true, for it to be considered valid.
15570 */
15571 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15572 // Configuration initialization
15573 config = $.extend( {
15574 type: 'text',
15575 labelPosition: 'after'
15576 }, config );
15577 if ( config.type === 'search' ) {
15578 if ( config.icon === undefined ) {
15579 config.icon = 'search';
15580 }
15581 // indicator: 'clear' is set dynamically later, depending on value
15582 }
15583 if ( config.required ) {
15584 if ( config.indicator === undefined ) {
15585 config.indicator = 'required';
15586 }
15587 }
15588
15589 // Parent constructor
15590 OO.ui.TextInputWidget.parent.call( this, config );
15591
15592 // Mixin constructors
15593 OO.ui.mixin.IconElement.call( this, config );
15594 OO.ui.mixin.IndicatorElement.call( this, config );
15595 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15596 OO.ui.mixin.LabelElement.call( this, config );
15597
15598 // Properties
15599 this.type = this.getSaneType( config );
15600 this.readOnly = false;
15601 this.multiline = !!config.multiline;
15602 this.autosize = !!config.autosize;
15603 this.minRows = config.rows !== undefined ? config.rows : '';
15604 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15605 this.validate = null;
15606 this.styleHeight = null;
15607
15608 // Clone for resizing
15609 if ( this.autosize ) {
15610 this.$clone = this.$input
15611 .clone()
15612 .insertAfter( this.$input )
15613 .attr( 'aria-hidden', 'true' )
15614 .addClass( 'oo-ui-element-hidden' );
15615 }
15616
15617 this.setValidation( config.validate );
15618 this.setLabelPosition( config.labelPosition );
15619
15620 // Events
15621 this.$input.on( {
15622 keypress: this.onKeyPress.bind( this ),
15623 blur: this.onBlur.bind( this )
15624 } );
15625 this.$input.one( {
15626 focus: this.onElementAttach.bind( this )
15627 } );
15628 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15629 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15630 this.on( 'labelChange', this.updatePosition.bind( this ) );
15631 this.connect( this, {
15632 change: 'onChange',
15633 disable: 'onDisable'
15634 } );
15635
15636 // Initialization
15637 this.$element
15638 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15639 .append( this.$icon, this.$indicator );
15640 this.setReadOnly( !!config.readOnly );
15641 this.updateSearchIndicator();
15642 if ( config.placeholder ) {
15643 this.$input.attr( 'placeholder', config.placeholder );
15644 }
15645 if ( config.maxLength !== undefined ) {
15646 this.$input.attr( 'maxlength', config.maxLength );
15647 }
15648 if ( config.autofocus ) {
15649 this.$input.attr( 'autofocus', 'autofocus' );
15650 }
15651 if ( config.required ) {
15652 this.$input.attr( 'required', 'required' );
15653 this.$input.attr( 'aria-required', 'true' );
15654 }
15655 if ( config.autocomplete === false ) {
15656 this.$input.attr( 'autocomplete', 'off' );
15657 // Turning off autocompletion also disables "form caching" when the user navigates to a
15658 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15659 $( window ).on( {
15660 beforeunload: function () {
15661 this.$input.removeAttr( 'autocomplete' );
15662 }.bind( this ),
15663 pageshow: function () {
15664 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15665 // whole page... it shouldn't hurt, though.
15666 this.$input.attr( 'autocomplete', 'off' );
15667 }.bind( this )
15668 } );
15669 }
15670 if ( this.multiline && config.rows ) {
15671 this.$input.attr( 'rows', config.rows );
15672 }
15673 if ( this.label || config.autosize ) {
15674 this.installParentChangeDetector();
15675 }
15676 };
15677
15678 /* Setup */
15679
15680 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15681 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15682 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15683 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15684 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15685
15686 /* Static Properties */
15687
15688 OO.ui.TextInputWidget.static.validationPatterns = {
15689 'non-empty': /.+/,
15690 integer: /^\d+$/
15691 };
15692
15693 /* Static Methods */
15694
15695 /**
15696 * @inheritdoc
15697 */
15698 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15699 var
15700 state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config ),
15701 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15702 state.$input = $input; // shortcut for performance, used in InputWidget
15703 if ( config.multiline ) {
15704 state.scrollTop = $input.scrollTop();
15705 }
15706 return state;
15707 };
15708
15709 /* Events */
15710
15711 /**
15712 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15713 *
15714 * Not emitted if the input is multiline.
15715 *
15716 * @event enter
15717 */
15718
15719 /**
15720 * A `resize` event is emitted when autosize is set and the widget resizes
15721 *
15722 * @event resize
15723 */
15724
15725 /* Methods */
15726
15727 /**
15728 * Handle icon mouse down events.
15729 *
15730 * @private
15731 * @param {jQuery.Event} e Mouse down event
15732 * @fires icon
15733 */
15734 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15735 if ( e.which === 1 ) {
15736 this.$input[ 0 ].focus();
15737 return false;
15738 }
15739 };
15740
15741 /**
15742 * Handle indicator mouse down events.
15743 *
15744 * @private
15745 * @param {jQuery.Event} e Mouse down event
15746 * @fires indicator
15747 */
15748 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15749 if ( e.which === 1 ) {
15750 if ( this.type === 'search' ) {
15751 // Clear the text field
15752 this.setValue( '' );
15753 }
15754 this.$input[ 0 ].focus();
15755 return false;
15756 }
15757 };
15758
15759 /**
15760 * Handle key press events.
15761 *
15762 * @private
15763 * @param {jQuery.Event} e Key press event
15764 * @fires enter If enter key is pressed and input is not multiline
15765 */
15766 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15767 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15768 this.emit( 'enter', e );
15769 }
15770 };
15771
15772 /**
15773 * Handle blur events.
15774 *
15775 * @private
15776 * @param {jQuery.Event} e Blur event
15777 */
15778 OO.ui.TextInputWidget.prototype.onBlur = function () {
15779 this.setValidityFlag();
15780 };
15781
15782 /**
15783 * Handle element attach events.
15784 *
15785 * @private
15786 * @param {jQuery.Event} e Element attach event
15787 */
15788 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15789 // Any previously calculated size is now probably invalid if we reattached elsewhere
15790 this.valCache = null;
15791 this.adjustSize();
15792 this.positionLabel();
15793 };
15794
15795 /**
15796 * Handle change events.
15797 *
15798 * @param {string} value
15799 * @private
15800 */
15801 OO.ui.TextInputWidget.prototype.onChange = function () {
15802 this.updateSearchIndicator();
15803 this.setValidityFlag();
15804 this.adjustSize();
15805 };
15806
15807 /**
15808 * Handle disable events.
15809 *
15810 * @param {boolean} disabled Element is disabled
15811 * @private
15812 */
15813 OO.ui.TextInputWidget.prototype.onDisable = function () {
15814 this.updateSearchIndicator();
15815 };
15816
15817 /**
15818 * Check if the input is {@link #readOnly read-only}.
15819 *
15820 * @return {boolean}
15821 */
15822 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15823 return this.readOnly;
15824 };
15825
15826 /**
15827 * Set the {@link #readOnly read-only} state of the input.
15828 *
15829 * @param {boolean} state Make input read-only
15830 * @chainable
15831 */
15832 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15833 this.readOnly = !!state;
15834 this.$input.prop( 'readOnly', this.readOnly );
15835 this.updateSearchIndicator();
15836 return this;
15837 };
15838
15839 /**
15840 * Support function for making #onElementAttach work across browsers.
15841 *
15842 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15843 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15844 *
15845 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15846 * first time that the element gets attached to the documented.
15847 */
15848 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15849 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15850 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15851 widget = this;
15852
15853 if ( MutationObserver ) {
15854 // The new way. If only it wasn't so ugly.
15855
15856 if ( this.$element.closest( 'html' ).length ) {
15857 // Widget is attached already, do nothing. This breaks the functionality of this function when
15858 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15859 // would require observation of the whole document, which would hurt performance of other,
15860 // more important code.
15861 return;
15862 }
15863
15864 // Find topmost node in the tree
15865 topmostNode = this.$element[ 0 ];
15866 while ( topmostNode.parentNode ) {
15867 topmostNode = topmostNode.parentNode;
15868 }
15869
15870 // We have no way to detect the $element being attached somewhere without observing the entire
15871 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15872 // parent node of $element, and instead detect when $element is removed from it (and thus
15873 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15874 // doesn't get attached, we end up back here and create the parent.
15875
15876 mutationObserver = new MutationObserver( function ( mutations ) {
15877 var i, j, removedNodes;
15878 for ( i = 0; i < mutations.length; i++ ) {
15879 removedNodes = mutations[ i ].removedNodes;
15880 for ( j = 0; j < removedNodes.length; j++ ) {
15881 if ( removedNodes[ j ] === topmostNode ) {
15882 setTimeout( onRemove, 0 );
15883 return;
15884 }
15885 }
15886 }
15887 } );
15888
15889 onRemove = function () {
15890 // If the node was attached somewhere else, report it
15891 if ( widget.$element.closest( 'html' ).length ) {
15892 widget.onElementAttach();
15893 }
15894 mutationObserver.disconnect();
15895 widget.installParentChangeDetector();
15896 };
15897
15898 // Create a fake parent and observe it
15899 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15900 mutationObserver.observe( fakeParentNode, { childList: true } );
15901 } else {
15902 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15903 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15904 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15905 }
15906 };
15907
15908 /**
15909 * Automatically adjust the size of the text input.
15910 *
15911 * This only affects #multiline inputs that are {@link #autosize autosized}.
15912 *
15913 * @chainable
15914 * @fires resize
15915 */
15916 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15917 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight, newHeight;
15918
15919 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15920 this.$clone
15921 .val( this.$input.val() )
15922 .attr( 'rows', this.minRows )
15923 // Set inline height property to 0 to measure scroll height
15924 .css( 'height', 0 );
15925
15926 this.$clone.removeClass( 'oo-ui-element-hidden' );
15927
15928 this.valCache = this.$input.val();
15929
15930 scrollHeight = this.$clone[ 0 ].scrollHeight;
15931
15932 // Remove inline height property to measure natural heights
15933 this.$clone.css( 'height', '' );
15934 innerHeight = this.$clone.innerHeight();
15935 outerHeight = this.$clone.outerHeight();
15936
15937 // Measure max rows height
15938 this.$clone
15939 .attr( 'rows', this.maxRows )
15940 .css( 'height', 'auto' )
15941 .val( '' );
15942 maxInnerHeight = this.$clone.innerHeight();
15943
15944 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15945 // Equals 1 on Blink-based browsers and 0 everywhere else
15946 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15947 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15948
15949 this.$clone.addClass( 'oo-ui-element-hidden' );
15950
15951 // Only apply inline height when expansion beyond natural height is needed
15952 // Use the difference between the inner and outer height as a buffer
15953 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
15954 if ( newHeight !== this.styleHeight ) {
15955 this.$input.css( 'height', newHeight );
15956 this.styleHeight = newHeight;
15957 this.emit( 'resize' );
15958 }
15959 }
15960 return this;
15961 };
15962
15963 /**
15964 * @inheritdoc
15965 * @protected
15966 */
15967 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15968 return config.multiline ?
15969 $( '<textarea>' ) :
15970 $( '<input type="' + this.getSaneType( config ) + '" />' );
15971 };
15972
15973 /**
15974 * Get sanitized value for 'type' for given config.
15975 *
15976 * @param {Object} config Configuration options
15977 * @return {string|null}
15978 * @private
15979 */
15980 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15981 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15982 config.type :
15983 'text';
15984 return config.multiline ? 'multiline' : type;
15985 };
15986
15987 /**
15988 * Check if the input supports multiple lines.
15989 *
15990 * @return {boolean}
15991 */
15992 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15993 return !!this.multiline;
15994 };
15995
15996 /**
15997 * Check if the input automatically adjusts its size.
15998 *
15999 * @return {boolean}
16000 */
16001 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16002 return !!this.autosize;
16003 };
16004
16005 /**
16006 * Focus the input and select a specified range within the text.
16007 *
16008 * @param {number} from Select from offset
16009 * @param {number} [to] Select to offset, defaults to from
16010 * @chainable
16011 */
16012 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16013 var textRange, isBackwards, start, end,
16014 element = this.$input[ 0 ];
16015
16016 to = to || from;
16017
16018 isBackwards = to < from;
16019 start = isBackwards ? to : from;
16020 end = isBackwards ? from : to;
16021
16022 this.focus();
16023
16024 if ( element.setSelectionRange ) {
16025 element.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16026 } else if ( element.createTextRange ) {
16027 // IE 8 and below
16028 textRange = element.createTextRange();
16029 textRange.collapse( true );
16030 textRange.moveStart( 'character', start );
16031 textRange.moveEnd( 'character', end - start );
16032 textRange.select();
16033 }
16034 return this;
16035 };
16036
16037 /**
16038 * Get the length of the text input value.
16039 *
16040 * This could differ from the length of #getValue if the
16041 * value gets filtered
16042 *
16043 * @return {number} Input length
16044 */
16045 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16046 return this.$input[ 0 ].value.length;
16047 };
16048
16049 /**
16050 * Focus the input and select the entire text.
16051 *
16052 * @chainable
16053 */
16054 OO.ui.TextInputWidget.prototype.select = function () {
16055 return this.selectRange( 0, this.getInputLength() );
16056 };
16057
16058 /**
16059 * Focus the input and move the cursor to the start.
16060 *
16061 * @chainable
16062 */
16063 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16064 return this.selectRange( 0 );
16065 };
16066
16067 /**
16068 * Focus the input and move the cursor to the end.
16069 *
16070 * @chainable
16071 */
16072 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16073 return this.selectRange( this.getInputLength() );
16074 };
16075
16076 /**
16077 * Set the validation pattern.
16078 *
16079 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16080 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16081 * value must contain only numbers).
16082 *
16083 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16084 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16085 */
16086 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16087 if ( validate instanceof RegExp || validate instanceof Function ) {
16088 this.validate = validate;
16089 } else {
16090 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16091 }
16092 };
16093
16094 /**
16095 * Sets the 'invalid' flag appropriately.
16096 *
16097 * @param {boolean} [isValid] Optionally override validation result
16098 */
16099 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16100 var widget = this,
16101 setFlag = function ( valid ) {
16102 if ( !valid ) {
16103 widget.$input.attr( 'aria-invalid', 'true' );
16104 } else {
16105 widget.$input.removeAttr( 'aria-invalid' );
16106 }
16107 widget.setFlags( { invalid: !valid } );
16108 };
16109
16110 if ( isValid !== undefined ) {
16111 setFlag( isValid );
16112 } else {
16113 this.getValidity().then( function () {
16114 setFlag( true );
16115 }, function () {
16116 setFlag( false );
16117 } );
16118 }
16119 };
16120
16121 /**
16122 * Check if a value is valid.
16123 *
16124 * This method returns a promise that resolves with a boolean `true` if the current value is
16125 * considered valid according to the supplied {@link #validate validation pattern}.
16126 *
16127 * @deprecated
16128 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16129 */
16130 OO.ui.TextInputWidget.prototype.isValid = function () {
16131 var result;
16132
16133 if ( this.validate instanceof Function ) {
16134 result = this.validate( this.getValue() );
16135 if ( $.isFunction( result.promise ) ) {
16136 return result.promise();
16137 } else {
16138 return $.Deferred().resolve( !!result ).promise();
16139 }
16140 } else {
16141 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16142 }
16143 };
16144
16145 /**
16146 * Get the validity of current value.
16147 *
16148 * This method returns a promise that resolves if the value is valid and rejects if
16149 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16150 *
16151 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16152 */
16153 OO.ui.TextInputWidget.prototype.getValidity = function () {
16154 var result, promise;
16155
16156 function rejectOrResolve( valid ) {
16157 if ( valid ) {
16158 return $.Deferred().resolve().promise();
16159 } else {
16160 return $.Deferred().reject().promise();
16161 }
16162 }
16163
16164 if ( this.validate instanceof Function ) {
16165 result = this.validate( this.getValue() );
16166
16167 if ( $.isFunction( result.promise ) ) {
16168 promise = $.Deferred();
16169
16170 result.then( function ( valid ) {
16171 if ( valid ) {
16172 promise.resolve();
16173 } else {
16174 promise.reject();
16175 }
16176 }, function () {
16177 promise.reject();
16178 } );
16179
16180 return promise.promise();
16181 } else {
16182 return rejectOrResolve( result );
16183 }
16184 } else {
16185 return rejectOrResolve( this.getValue().match( this.validate ) );
16186 }
16187 };
16188
16189 /**
16190 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16191 *
16192 * @param {string} labelPosition Label position, 'before' or 'after'
16193 * @chainable
16194 */
16195 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16196 this.labelPosition = labelPosition;
16197 this.updatePosition();
16198 return this;
16199 };
16200
16201 /**
16202 * Deprecated alias of #setLabelPosition
16203 *
16204 * @deprecated Use setLabelPosition instead.
16205 */
16206 OO.ui.TextInputWidget.prototype.setPosition =
16207 OO.ui.TextInputWidget.prototype.setLabelPosition;
16208
16209 /**
16210 * Update the position of the inline label.
16211 *
16212 * This method is called by #setLabelPosition, and can also be called on its own if
16213 * something causes the label to be mispositioned.
16214 *
16215 * @chainable
16216 */
16217 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16218 var after = this.labelPosition === 'after';
16219
16220 this.$element
16221 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16222 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16223
16224 this.positionLabel();
16225
16226 return this;
16227 };
16228
16229 /**
16230 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16231 * already empty or when it's not editable.
16232 */
16233 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16234 if ( this.type === 'search' ) {
16235 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16236 this.setIndicator( null );
16237 } else {
16238 this.setIndicator( 'clear' );
16239 }
16240 }
16241 };
16242
16243 /**
16244 * Position the label by setting the correct padding on the input.
16245 *
16246 * @private
16247 * @chainable
16248 */
16249 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16250 var after, rtl, property;
16251 // Clear old values
16252 this.$input
16253 // Clear old values if present
16254 .css( {
16255 'padding-right': '',
16256 'padding-left': ''
16257 } );
16258
16259 if ( this.label ) {
16260 this.$element.append( this.$label );
16261 } else {
16262 this.$label.detach();
16263 return;
16264 }
16265
16266 after = this.labelPosition === 'after';
16267 rtl = this.$element.css( 'direction' ) === 'rtl';
16268 property = after === rtl ? 'padding-left' : 'padding-right';
16269
16270 this.$input.css( property, this.$label.outerWidth( true ) );
16271
16272 return this;
16273 };
16274
16275 /**
16276 * @inheritdoc
16277 */
16278 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16279 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16280 if ( state.scrollTop !== undefined ) {
16281 this.$input.scrollTop( state.scrollTop );
16282 }
16283 };
16284
16285 /**
16286 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16287 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16288 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16289 *
16290 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16291 * option, that option will appear to be selected.
16292 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16293 * input field.
16294 *
16295 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16296 *
16297 * @example
16298 * // Example: A ComboBoxWidget.
16299 * var comboBox = new OO.ui.ComboBoxWidget( {
16300 * label: 'ComboBoxWidget',
16301 * input: { value: 'Option One' },
16302 * menu: {
16303 * items: [
16304 * new OO.ui.MenuOptionWidget( {
16305 * data: 'Option 1',
16306 * label: 'Option One'
16307 * } ),
16308 * new OO.ui.MenuOptionWidget( {
16309 * data: 'Option 2',
16310 * label: 'Option Two'
16311 * } ),
16312 * new OO.ui.MenuOptionWidget( {
16313 * data: 'Option 3',
16314 * label: 'Option Three'
16315 * } ),
16316 * new OO.ui.MenuOptionWidget( {
16317 * data: 'Option 4',
16318 * label: 'Option Four'
16319 * } ),
16320 * new OO.ui.MenuOptionWidget( {
16321 * data: 'Option 5',
16322 * label: 'Option Five'
16323 * } )
16324 * ]
16325 * }
16326 * } );
16327 * $( 'body' ).append( comboBox.$element );
16328 *
16329 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16330 *
16331 * @class
16332 * @extends OO.ui.Widget
16333 * @mixins OO.ui.mixin.TabIndexedElement
16334 *
16335 * @constructor
16336 * @param {Object} [config] Configuration options
16337 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16338 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16339 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16340 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16341 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16342 */
16343 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
16344 // Configuration initialization
16345 config = config || {};
16346
16347 // Parent constructor
16348 OO.ui.ComboBoxWidget.parent.call( this, config );
16349
16350 // Properties (must be set before TabIndexedElement constructor call)
16351 this.$indicator = this.$( '<span>' );
16352
16353 // Mixin constructors
16354 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
16355
16356 // Properties
16357 this.$overlay = config.$overlay || this.$element;
16358 this.input = new OO.ui.TextInputWidget( $.extend(
16359 {
16360 indicator: 'down',
16361 $indicator: this.$indicator,
16362 disabled: this.isDisabled()
16363 },
16364 config.input
16365 ) );
16366 this.input.$input.eq( 0 ).attr( {
16367 role: 'combobox',
16368 'aria-autocomplete': 'list'
16369 } );
16370 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16371 {
16372 widget: this,
16373 input: this.input,
16374 $container: this.input.$element,
16375 disabled: this.isDisabled()
16376 },
16377 config.menu
16378 ) );
16379
16380 // Events
16381 this.$indicator.on( {
16382 click: this.onClick.bind( this ),
16383 keypress: this.onKeyPress.bind( this )
16384 } );
16385 this.input.connect( this, {
16386 change: 'onInputChange',
16387 enter: 'onInputEnter'
16388 } );
16389 this.menu.connect( this, {
16390 choose: 'onMenuChoose',
16391 add: 'onMenuItemsChange',
16392 remove: 'onMenuItemsChange'
16393 } );
16394
16395 // Initialization
16396 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
16397 this.$overlay.append( this.menu.$element );
16398 this.onMenuItemsChange();
16399 };
16400
16401 /* Setup */
16402
16403 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16404 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16405
16406 /* Methods */
16407
16408 /**
16409 * Get the combobox's menu.
16410 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16411 */
16412 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16413 return this.menu;
16414 };
16415
16416 /**
16417 * Get the combobox's text input widget.
16418 * @return {OO.ui.TextInputWidget} Text input widget
16419 */
16420 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16421 return this.input;
16422 };
16423
16424 /**
16425 * Handle input change events.
16426 *
16427 * @private
16428 * @param {string} value New value
16429 */
16430 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16431 var match = this.menu.getItemFromData( value );
16432
16433 this.menu.selectItem( match );
16434 if ( this.menu.getHighlightedItem() ) {
16435 this.menu.highlightItem( match );
16436 }
16437
16438 if ( !this.isDisabled() ) {
16439 this.menu.toggle( true );
16440 }
16441 };
16442
16443 /**
16444 * Handle mouse click events.
16445 *
16446 * @private
16447 * @param {jQuery.Event} e Mouse click event
16448 */
16449 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16450 if ( !this.isDisabled() && e.which === 1 ) {
16451 this.menu.toggle();
16452 this.input.$input[ 0 ].focus();
16453 }
16454 return false;
16455 };
16456
16457 /**
16458 * Handle key press events.
16459 *
16460 * @private
16461 * @param {jQuery.Event} e Key press event
16462 */
16463 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16464 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16465 this.menu.toggle();
16466 this.input.$input[ 0 ].focus();
16467 return false;
16468 }
16469 };
16470
16471 /**
16472 * Handle input enter events.
16473 *
16474 * @private
16475 */
16476 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16477 if ( !this.isDisabled() ) {
16478 this.menu.toggle( false );
16479 }
16480 };
16481
16482 /**
16483 * Handle menu choose events.
16484 *
16485 * @private
16486 * @param {OO.ui.OptionWidget} item Chosen item
16487 */
16488 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16489 this.input.setValue( item.getData() );
16490 };
16491
16492 /**
16493 * Handle menu item change events.
16494 *
16495 * @private
16496 */
16497 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16498 var match = this.menu.getItemFromData( this.input.getValue() );
16499 this.menu.selectItem( match );
16500 if ( this.menu.getHighlightedItem() ) {
16501 this.menu.highlightItem( match );
16502 }
16503 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16504 };
16505
16506 /**
16507 * @inheritdoc
16508 */
16509 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16510 // Parent method
16511 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16512
16513 if ( this.input ) {
16514 this.input.setDisabled( this.isDisabled() );
16515 }
16516 if ( this.menu ) {
16517 this.menu.setDisabled( this.isDisabled() );
16518 }
16519
16520 return this;
16521 };
16522
16523 /**
16524 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16525 * be configured with a `label` option that is set to a string, a label node, or a function:
16526 *
16527 * - String: a plaintext string
16528 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16529 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16530 * - Function: a function that will produce a string in the future. Functions are used
16531 * in cases where the value of the label is not currently defined.
16532 *
16533 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16534 * will come into focus when the label is clicked.
16535 *
16536 * @example
16537 * // Examples of LabelWidgets
16538 * var label1 = new OO.ui.LabelWidget( {
16539 * label: 'plaintext label'
16540 * } );
16541 * var label2 = new OO.ui.LabelWidget( {
16542 * label: $( '<a href="default.html">jQuery label</a>' )
16543 * } );
16544 * // Create a fieldset layout with fields for each example
16545 * var fieldset = new OO.ui.FieldsetLayout();
16546 * fieldset.addItems( [
16547 * new OO.ui.FieldLayout( label1 ),
16548 * new OO.ui.FieldLayout( label2 )
16549 * ] );
16550 * $( 'body' ).append( fieldset.$element );
16551 *
16552 * @class
16553 * @extends OO.ui.Widget
16554 * @mixins OO.ui.mixin.LabelElement
16555 *
16556 * @constructor
16557 * @param {Object} [config] Configuration options
16558 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16559 * Clicking the label will focus the specified input field.
16560 */
16561 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16562 // Configuration initialization
16563 config = config || {};
16564
16565 // Parent constructor
16566 OO.ui.LabelWidget.parent.call( this, config );
16567
16568 // Mixin constructors
16569 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16570 OO.ui.mixin.TitledElement.call( this, config );
16571
16572 // Properties
16573 this.input = config.input;
16574
16575 // Events
16576 if ( this.input instanceof OO.ui.InputWidget ) {
16577 this.$element.on( 'click', this.onClick.bind( this ) );
16578 }
16579
16580 // Initialization
16581 this.$element.addClass( 'oo-ui-labelWidget' );
16582 };
16583
16584 /* Setup */
16585
16586 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16587 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16588 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16589
16590 /* Static Properties */
16591
16592 OO.ui.LabelWidget.static.tagName = 'span';
16593
16594 /* Methods */
16595
16596 /**
16597 * Handles label mouse click events.
16598 *
16599 * @private
16600 * @param {jQuery.Event} e Mouse click event
16601 */
16602 OO.ui.LabelWidget.prototype.onClick = function () {
16603 this.input.simulateLabelClick();
16604 return false;
16605 };
16606
16607 /**
16608 * OptionWidgets are special elements that can be selected and configured with data. The
16609 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16610 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16611 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16612 *
16613 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16614 *
16615 * @class
16616 * @extends OO.ui.Widget
16617 * @mixins OO.ui.mixin.LabelElement
16618 * @mixins OO.ui.mixin.FlaggedElement
16619 *
16620 * @constructor
16621 * @param {Object} [config] Configuration options
16622 */
16623 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16624 // Configuration initialization
16625 config = config || {};
16626
16627 // Parent constructor
16628 OO.ui.OptionWidget.parent.call( this, config );
16629
16630 // Mixin constructors
16631 OO.ui.mixin.ItemWidget.call( this );
16632 OO.ui.mixin.LabelElement.call( this, config );
16633 OO.ui.mixin.FlaggedElement.call( this, config );
16634
16635 // Properties
16636 this.selected = false;
16637 this.highlighted = false;
16638 this.pressed = false;
16639
16640 // Initialization
16641 this.$element
16642 .data( 'oo-ui-optionWidget', this )
16643 .attr( 'role', 'option' )
16644 .attr( 'aria-selected', 'false' )
16645 .addClass( 'oo-ui-optionWidget' )
16646 .append( this.$label );
16647 };
16648
16649 /* Setup */
16650
16651 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16652 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16653 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16654 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16655
16656 /* Static Properties */
16657
16658 OO.ui.OptionWidget.static.selectable = true;
16659
16660 OO.ui.OptionWidget.static.highlightable = true;
16661
16662 OO.ui.OptionWidget.static.pressable = true;
16663
16664 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16665
16666 /* Methods */
16667
16668 /**
16669 * Check if the option can be selected.
16670 *
16671 * @return {boolean} Item is selectable
16672 */
16673 OO.ui.OptionWidget.prototype.isSelectable = function () {
16674 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16675 };
16676
16677 /**
16678 * Check if the option can be highlighted. A highlight indicates that the option
16679 * may be selected when a user presses enter or clicks. Disabled items cannot
16680 * be highlighted.
16681 *
16682 * @return {boolean} Item is highlightable
16683 */
16684 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16685 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16686 };
16687
16688 /**
16689 * Check if the option can be pressed. The pressed state occurs when a user mouses
16690 * down on an item, but has not yet let go of the mouse.
16691 *
16692 * @return {boolean} Item is pressable
16693 */
16694 OO.ui.OptionWidget.prototype.isPressable = function () {
16695 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16696 };
16697
16698 /**
16699 * Check if the option is selected.
16700 *
16701 * @return {boolean} Item is selected
16702 */
16703 OO.ui.OptionWidget.prototype.isSelected = function () {
16704 return this.selected;
16705 };
16706
16707 /**
16708 * Check if the option is highlighted. A highlight indicates that the
16709 * item may be selected when a user presses enter or clicks.
16710 *
16711 * @return {boolean} Item is highlighted
16712 */
16713 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16714 return this.highlighted;
16715 };
16716
16717 /**
16718 * Check if the option is pressed. The pressed state occurs when a user mouses
16719 * down on an item, but has not yet let go of the mouse. The item may appear
16720 * selected, but it will not be selected until the user releases the mouse.
16721 *
16722 * @return {boolean} Item is pressed
16723 */
16724 OO.ui.OptionWidget.prototype.isPressed = function () {
16725 return this.pressed;
16726 };
16727
16728 /**
16729 * Set the option’s selected state. In general, all modifications to the selection
16730 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16731 * method instead of this method.
16732 *
16733 * @param {boolean} [state=false] Select option
16734 * @chainable
16735 */
16736 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16737 if ( this.constructor.static.selectable ) {
16738 this.selected = !!state;
16739 this.$element
16740 .toggleClass( 'oo-ui-optionWidget-selected', state )
16741 .attr( 'aria-selected', state.toString() );
16742 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16743 this.scrollElementIntoView();
16744 }
16745 this.updateThemeClasses();
16746 }
16747 return this;
16748 };
16749
16750 /**
16751 * Set the option’s highlighted state. In general, all programmatic
16752 * modifications to the highlight should be handled by the
16753 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16754 * method instead of this method.
16755 *
16756 * @param {boolean} [state=false] Highlight option
16757 * @chainable
16758 */
16759 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16760 if ( this.constructor.static.highlightable ) {
16761 this.highlighted = !!state;
16762 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16763 this.updateThemeClasses();
16764 }
16765 return this;
16766 };
16767
16768 /**
16769 * Set the option’s pressed state. In general, all
16770 * programmatic modifications to the pressed state should be handled by the
16771 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16772 * method instead of this method.
16773 *
16774 * @param {boolean} [state=false] Press option
16775 * @chainable
16776 */
16777 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16778 if ( this.constructor.static.pressable ) {
16779 this.pressed = !!state;
16780 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16781 this.updateThemeClasses();
16782 }
16783 return this;
16784 };
16785
16786 /**
16787 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16788 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16789 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16790 * options. For more information about options and selects, please see the
16791 * [OOjs UI documentation on MediaWiki][1].
16792 *
16793 * @example
16794 * // Decorated options in a select widget
16795 * var select = new OO.ui.SelectWidget( {
16796 * items: [
16797 * new OO.ui.DecoratedOptionWidget( {
16798 * data: 'a',
16799 * label: 'Option with icon',
16800 * icon: 'help'
16801 * } ),
16802 * new OO.ui.DecoratedOptionWidget( {
16803 * data: 'b',
16804 * label: 'Option with indicator',
16805 * indicator: 'next'
16806 * } )
16807 * ]
16808 * } );
16809 * $( 'body' ).append( select.$element );
16810 *
16811 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16812 *
16813 * @class
16814 * @extends OO.ui.OptionWidget
16815 * @mixins OO.ui.mixin.IconElement
16816 * @mixins OO.ui.mixin.IndicatorElement
16817 *
16818 * @constructor
16819 * @param {Object} [config] Configuration options
16820 */
16821 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16822 // Parent constructor
16823 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16824
16825 // Mixin constructors
16826 OO.ui.mixin.IconElement.call( this, config );
16827 OO.ui.mixin.IndicatorElement.call( this, config );
16828
16829 // Initialization
16830 this.$element
16831 .addClass( 'oo-ui-decoratedOptionWidget' )
16832 .prepend( this.$icon )
16833 .append( this.$indicator );
16834 };
16835
16836 /* Setup */
16837
16838 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16839 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16840 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16841
16842 /**
16843 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16844 * can be selected and configured with data. The class is
16845 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16846 * [OOjs UI documentation on MediaWiki] [1] for more information.
16847 *
16848 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16849 *
16850 * @class
16851 * @extends OO.ui.DecoratedOptionWidget
16852 * @mixins OO.ui.mixin.ButtonElement
16853 * @mixins OO.ui.mixin.TabIndexedElement
16854 * @mixins OO.ui.mixin.TitledElement
16855 *
16856 * @constructor
16857 * @param {Object} [config] Configuration options
16858 */
16859 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16860 // Configuration initialization
16861 config = config || {};
16862
16863 // Parent constructor
16864 OO.ui.ButtonOptionWidget.parent.call( this, config );
16865
16866 // Mixin constructors
16867 OO.ui.mixin.ButtonElement.call( this, config );
16868 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16869 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16870 $tabIndexed: this.$button,
16871 tabIndex: -1
16872 } ) );
16873
16874 // Initialization
16875 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16876 this.$button.append( this.$element.contents() );
16877 this.$element.append( this.$button );
16878 };
16879
16880 /* Setup */
16881
16882 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16883 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16884 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16885 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16886
16887 /* Static Properties */
16888
16889 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16890 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16891
16892 OO.ui.ButtonOptionWidget.static.highlightable = false;
16893
16894 /* Methods */
16895
16896 /**
16897 * @inheritdoc
16898 */
16899 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16900 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16901
16902 if ( this.constructor.static.selectable ) {
16903 this.setActive( state );
16904 }
16905
16906 return this;
16907 };
16908
16909 /**
16910 * RadioOptionWidget is an option widget that looks like a radio button.
16911 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16912 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16913 *
16914 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16915 *
16916 * @class
16917 * @extends OO.ui.OptionWidget
16918 *
16919 * @constructor
16920 * @param {Object} [config] Configuration options
16921 */
16922 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16923 // Configuration initialization
16924 config = config || {};
16925
16926 // Properties (must be done before parent constructor which calls #setDisabled)
16927 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16928
16929 // Parent constructor
16930 OO.ui.RadioOptionWidget.parent.call( this, config );
16931
16932 // Events
16933 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16934
16935 // Initialization
16936 // Remove implicit role, we're handling it ourselves
16937 this.radio.$input.attr( 'role', 'presentation' );
16938 this.$element
16939 .addClass( 'oo-ui-radioOptionWidget' )
16940 .attr( 'role', 'radio' )
16941 .attr( 'aria-checked', 'false' )
16942 .removeAttr( 'aria-selected' )
16943 .prepend( this.radio.$element );
16944 };
16945
16946 /* Setup */
16947
16948 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16949
16950 /* Static Properties */
16951
16952 OO.ui.RadioOptionWidget.static.highlightable = false;
16953
16954 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16955
16956 OO.ui.RadioOptionWidget.static.pressable = false;
16957
16958 OO.ui.RadioOptionWidget.static.tagName = 'label';
16959
16960 /* Methods */
16961
16962 /**
16963 * @param {jQuery.Event} e Focus event
16964 * @private
16965 */
16966 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16967 this.radio.$input.blur();
16968 this.$element.parent().focus();
16969 };
16970
16971 /**
16972 * @inheritdoc
16973 */
16974 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16975 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16976
16977 this.radio.setSelected( state );
16978 this.$element
16979 .attr( 'aria-checked', state.toString() )
16980 .removeAttr( 'aria-selected' );
16981
16982 return this;
16983 };
16984
16985 /**
16986 * @inheritdoc
16987 */
16988 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16989 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16990
16991 this.radio.setDisabled( this.isDisabled() );
16992
16993 return this;
16994 };
16995
16996 /**
16997 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16998 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16999 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17000 *
17001 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17002 *
17003 * @class
17004 * @extends OO.ui.DecoratedOptionWidget
17005 *
17006 * @constructor
17007 * @param {Object} [config] Configuration options
17008 */
17009 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17010 // Configuration initialization
17011 config = $.extend( { icon: 'check' }, config );
17012
17013 // Parent constructor
17014 OO.ui.MenuOptionWidget.parent.call( this, config );
17015
17016 // Initialization
17017 this.$element
17018 .attr( 'role', 'menuitem' )
17019 .addClass( 'oo-ui-menuOptionWidget' );
17020 };
17021
17022 /* Setup */
17023
17024 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17025
17026 /* Static Properties */
17027
17028 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17029
17030 /**
17031 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17032 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17033 *
17034 * @example
17035 * var myDropdown = new OO.ui.DropdownWidget( {
17036 * menu: {
17037 * items: [
17038 * new OO.ui.MenuSectionOptionWidget( {
17039 * label: 'Dogs'
17040 * } ),
17041 * new OO.ui.MenuOptionWidget( {
17042 * data: 'corgi',
17043 * label: 'Welsh Corgi'
17044 * } ),
17045 * new OO.ui.MenuOptionWidget( {
17046 * data: 'poodle',
17047 * label: 'Standard Poodle'
17048 * } ),
17049 * new OO.ui.MenuSectionOptionWidget( {
17050 * label: 'Cats'
17051 * } ),
17052 * new OO.ui.MenuOptionWidget( {
17053 * data: 'lion',
17054 * label: 'Lion'
17055 * } )
17056 * ]
17057 * }
17058 * } );
17059 * $( 'body' ).append( myDropdown.$element );
17060 *
17061 * @class
17062 * @extends OO.ui.DecoratedOptionWidget
17063 *
17064 * @constructor
17065 * @param {Object} [config] Configuration options
17066 */
17067 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17068 // Parent constructor
17069 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17070
17071 // Initialization
17072 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17073 };
17074
17075 /* Setup */
17076
17077 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17078
17079 /* Static Properties */
17080
17081 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17082
17083 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17084
17085 /**
17086 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17087 *
17088 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17089 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17090 * for an example.
17091 *
17092 * @class
17093 * @extends OO.ui.DecoratedOptionWidget
17094 *
17095 * @constructor
17096 * @param {Object} [config] Configuration options
17097 * @cfg {number} [level] Indentation level
17098 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17099 */
17100 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17101 // Configuration initialization
17102 config = config || {};
17103
17104 // Parent constructor
17105 OO.ui.OutlineOptionWidget.parent.call( this, config );
17106
17107 // Properties
17108 this.level = 0;
17109 this.movable = !!config.movable;
17110 this.removable = !!config.removable;
17111
17112 // Initialization
17113 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17114 this.setLevel( config.level );
17115 };
17116
17117 /* Setup */
17118
17119 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17120
17121 /* Static Properties */
17122
17123 OO.ui.OutlineOptionWidget.static.highlightable = false;
17124
17125 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17126
17127 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17128
17129 OO.ui.OutlineOptionWidget.static.levels = 3;
17130
17131 /* Methods */
17132
17133 /**
17134 * Check if item is movable.
17135 *
17136 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17137 *
17138 * @return {boolean} Item is movable
17139 */
17140 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17141 return this.movable;
17142 };
17143
17144 /**
17145 * Check if item is removable.
17146 *
17147 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17148 *
17149 * @return {boolean} Item is removable
17150 */
17151 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17152 return this.removable;
17153 };
17154
17155 /**
17156 * Get indentation level.
17157 *
17158 * @return {number} Indentation level
17159 */
17160 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17161 return this.level;
17162 };
17163
17164 /**
17165 * Set movability.
17166 *
17167 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17168 *
17169 * @param {boolean} movable Item is movable
17170 * @chainable
17171 */
17172 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17173 this.movable = !!movable;
17174 this.updateThemeClasses();
17175 return this;
17176 };
17177
17178 /**
17179 * Set removability.
17180 *
17181 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17182 *
17183 * @param {boolean} movable Item is removable
17184 * @chainable
17185 */
17186 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17187 this.removable = !!removable;
17188 this.updateThemeClasses();
17189 return this;
17190 };
17191
17192 /**
17193 * Set indentation level.
17194 *
17195 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17196 * @chainable
17197 */
17198 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17199 var levels = this.constructor.static.levels,
17200 levelClass = this.constructor.static.levelClass,
17201 i = levels;
17202
17203 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17204 while ( i-- ) {
17205 if ( this.level === i ) {
17206 this.$element.addClass( levelClass + i );
17207 } else {
17208 this.$element.removeClass( levelClass + i );
17209 }
17210 }
17211 this.updateThemeClasses();
17212
17213 return this;
17214 };
17215
17216 /**
17217 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17218 *
17219 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17220 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17221 * for an example.
17222 *
17223 * @class
17224 * @extends OO.ui.OptionWidget
17225 *
17226 * @constructor
17227 * @param {Object} [config] Configuration options
17228 */
17229 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17230 // Configuration initialization
17231 config = config || {};
17232
17233 // Parent constructor
17234 OO.ui.TabOptionWidget.parent.call( this, config );
17235
17236 // Initialization
17237 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17238 };
17239
17240 /* Setup */
17241
17242 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17243
17244 /* Static Properties */
17245
17246 OO.ui.TabOptionWidget.static.highlightable = false;
17247
17248 /**
17249 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17250 * By default, each popup has an anchor that points toward its origin.
17251 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17252 *
17253 * @example
17254 * // A popup widget.
17255 * var popup = new OO.ui.PopupWidget( {
17256 * $content: $( '<p>Hi there!</p>' ),
17257 * padded: true,
17258 * width: 300
17259 * } );
17260 *
17261 * $( 'body' ).append( popup.$element );
17262 * // To display the popup, toggle the visibility to 'true'.
17263 * popup.toggle( true );
17264 *
17265 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17266 *
17267 * @class
17268 * @extends OO.ui.Widget
17269 * @mixins OO.ui.mixin.LabelElement
17270 * @mixins OO.ui.mixin.ClippableElement
17271 *
17272 * @constructor
17273 * @param {Object} [config] Configuration options
17274 * @cfg {number} [width=320] Width of popup in pixels
17275 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17276 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17277 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17278 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17279 * popup is leaning towards the right of the screen.
17280 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17281 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17282 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17283 * sentence in the given language.
17284 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17285 * See the [OOjs UI docs on MediaWiki][3] for an example.
17286 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17287 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17288 * @cfg {jQuery} [$content] Content to append to the popup's body
17289 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17290 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17291 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17292 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17293 * for an example.
17294 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17295 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17296 * button.
17297 * @cfg {boolean} [padded] Add padding to the popup's body
17298 */
17299 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17300 // Configuration initialization
17301 config = config || {};
17302
17303 // Parent constructor
17304 OO.ui.PopupWidget.parent.call( this, config );
17305
17306 // Properties (must be set before ClippableElement constructor call)
17307 this.$body = $( '<div>' );
17308 this.$popup = $( '<div>' );
17309
17310 // Mixin constructors
17311 OO.ui.mixin.LabelElement.call( this, config );
17312 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17313 $clippable: this.$body,
17314 $clippableContainer: this.$popup
17315 } ) );
17316
17317 // Properties
17318 this.$head = $( '<div>' );
17319 this.$footer = $( '<div>' );
17320 this.$anchor = $( '<div>' );
17321 // If undefined, will be computed lazily in updateDimensions()
17322 this.$container = config.$container;
17323 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17324 this.autoClose = !!config.autoClose;
17325 this.$autoCloseIgnore = config.$autoCloseIgnore;
17326 this.transitionTimeout = null;
17327 this.anchor = null;
17328 this.width = config.width !== undefined ? config.width : 320;
17329 this.height = config.height !== undefined ? config.height : null;
17330 this.setAlignment( config.align );
17331 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17332 this.onMouseDownHandler = this.onMouseDown.bind( this );
17333 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17334
17335 // Events
17336 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17337
17338 // Initialization
17339 this.toggleAnchor( config.anchor === undefined || config.anchor );
17340 this.$body.addClass( 'oo-ui-popupWidget-body' );
17341 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17342 this.$head
17343 .addClass( 'oo-ui-popupWidget-head' )
17344 .append( this.$label, this.closeButton.$element );
17345 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17346 if ( !config.head ) {
17347 this.$head.addClass( 'oo-ui-element-hidden' );
17348 }
17349 if ( !config.$footer ) {
17350 this.$footer.addClass( 'oo-ui-element-hidden' );
17351 }
17352 this.$popup
17353 .addClass( 'oo-ui-popupWidget-popup' )
17354 .append( this.$head, this.$body, this.$footer );
17355 this.$element
17356 .addClass( 'oo-ui-popupWidget' )
17357 .append( this.$popup, this.$anchor );
17358 // Move content, which was added to #$element by OO.ui.Widget, to the body
17359 if ( config.$content instanceof jQuery ) {
17360 this.$body.append( config.$content );
17361 }
17362 if ( config.$footer instanceof jQuery ) {
17363 this.$footer.append( config.$footer );
17364 }
17365 if ( config.padded ) {
17366 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17367 }
17368
17369 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17370 // that reference properties not initialized at that time of parent class construction
17371 // TODO: Find a better way to handle post-constructor setup
17372 this.visible = false;
17373 this.$element.addClass( 'oo-ui-element-hidden' );
17374 };
17375
17376 /* Setup */
17377
17378 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17379 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17380 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17381
17382 /* Methods */
17383
17384 /**
17385 * Handles mouse down events.
17386 *
17387 * @private
17388 * @param {MouseEvent} e Mouse down event
17389 */
17390 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17391 if (
17392 this.isVisible() &&
17393 !$.contains( this.$element[ 0 ], e.target ) &&
17394 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17395 ) {
17396 this.toggle( false );
17397 }
17398 };
17399
17400 /**
17401 * Bind mouse down listener.
17402 *
17403 * @private
17404 */
17405 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17406 // Capture clicks outside popup
17407 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17408 };
17409
17410 /**
17411 * Handles close button click events.
17412 *
17413 * @private
17414 */
17415 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17416 if ( this.isVisible() ) {
17417 this.toggle( false );
17418 }
17419 };
17420
17421 /**
17422 * Unbind mouse down listener.
17423 *
17424 * @private
17425 */
17426 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17427 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17428 };
17429
17430 /**
17431 * Handles key down events.
17432 *
17433 * @private
17434 * @param {KeyboardEvent} e Key down event
17435 */
17436 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17437 if (
17438 e.which === OO.ui.Keys.ESCAPE &&
17439 this.isVisible()
17440 ) {
17441 this.toggle( false );
17442 e.preventDefault();
17443 e.stopPropagation();
17444 }
17445 };
17446
17447 /**
17448 * Bind key down listener.
17449 *
17450 * @private
17451 */
17452 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17453 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17454 };
17455
17456 /**
17457 * Unbind key down listener.
17458 *
17459 * @private
17460 */
17461 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17462 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17463 };
17464
17465 /**
17466 * Show, hide, or toggle the visibility of the anchor.
17467 *
17468 * @param {boolean} [show] Show anchor, omit to toggle
17469 */
17470 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17471 show = show === undefined ? !this.anchored : !!show;
17472
17473 if ( this.anchored !== show ) {
17474 if ( show ) {
17475 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17476 } else {
17477 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17478 }
17479 this.anchored = show;
17480 }
17481 };
17482
17483 /**
17484 * Check if the anchor is visible.
17485 *
17486 * @return {boolean} Anchor is visible
17487 */
17488 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17489 return this.anchor;
17490 };
17491
17492 /**
17493 * @inheritdoc
17494 */
17495 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17496 var change;
17497 show = show === undefined ? !this.isVisible() : !!show;
17498
17499 change = show !== this.isVisible();
17500
17501 // Parent method
17502 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17503
17504 if ( change ) {
17505 if ( show ) {
17506 if ( this.autoClose ) {
17507 this.bindMouseDownListener();
17508 this.bindKeyDownListener();
17509 }
17510 this.updateDimensions();
17511 this.toggleClipping( true );
17512 } else {
17513 this.toggleClipping( false );
17514 if ( this.autoClose ) {
17515 this.unbindMouseDownListener();
17516 this.unbindKeyDownListener();
17517 }
17518 }
17519 }
17520
17521 return this;
17522 };
17523
17524 /**
17525 * Set the size of the popup.
17526 *
17527 * Changing the size may also change the popup's position depending on the alignment.
17528 *
17529 * @param {number} width Width in pixels
17530 * @param {number} height Height in pixels
17531 * @param {boolean} [transition=false] Use a smooth transition
17532 * @chainable
17533 */
17534 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17535 this.width = width;
17536 this.height = height !== undefined ? height : null;
17537 if ( this.isVisible() ) {
17538 this.updateDimensions( transition );
17539 }
17540 };
17541
17542 /**
17543 * Update the size and position.
17544 *
17545 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17546 * be called automatically.
17547 *
17548 * @param {boolean} [transition=false] Use a smooth transition
17549 * @chainable
17550 */
17551 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17552 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17553 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17554 align = this.align,
17555 widget = this;
17556
17557 if ( !this.$container ) {
17558 // Lazy-initialize $container if not specified in constructor
17559 this.$container = $( this.getClosestScrollableElementContainer() );
17560 }
17561
17562 // Set height and width before measuring things, since it might cause our measurements
17563 // to change (e.g. due to scrollbars appearing or disappearing)
17564 this.$popup.css( {
17565 width: this.width,
17566 height: this.height !== null ? this.height : 'auto'
17567 } );
17568
17569 // If we are in RTL, we need to flip the alignment, unless it is center
17570 if ( align === 'forwards' || align === 'backwards' ) {
17571 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17572 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17573 } else {
17574 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17575 }
17576
17577 }
17578
17579 // Compute initial popupOffset based on alignment
17580 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17581
17582 // Figure out if this will cause the popup to go beyond the edge of the container
17583 originOffset = this.$element.offset().left;
17584 containerLeft = this.$container.offset().left;
17585 containerWidth = this.$container.innerWidth();
17586 containerRight = containerLeft + containerWidth;
17587 popupLeft = popupOffset - this.containerPadding;
17588 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17589 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17590 overlapRight = containerRight - ( originOffset + popupRight );
17591
17592 // Adjust offset to make the popup not go beyond the edge, if needed
17593 if ( overlapRight < 0 ) {
17594 popupOffset += overlapRight;
17595 } else if ( overlapLeft < 0 ) {
17596 popupOffset -= overlapLeft;
17597 }
17598
17599 // Adjust offset to avoid anchor being rendered too close to the edge
17600 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17601 // TODO: Find a measurement that works for CSS anchors and image anchors
17602 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17603 if ( popupOffset + this.width < anchorWidth ) {
17604 popupOffset = anchorWidth - this.width;
17605 } else if ( -popupOffset < anchorWidth ) {
17606 popupOffset = -anchorWidth;
17607 }
17608
17609 // Prevent transition from being interrupted
17610 clearTimeout( this.transitionTimeout );
17611 if ( transition ) {
17612 // Enable transition
17613 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17614 }
17615
17616 // Position body relative to anchor
17617 this.$popup.css( 'margin-left', popupOffset );
17618
17619 if ( transition ) {
17620 // Prevent transitioning after transition is complete
17621 this.transitionTimeout = setTimeout( function () {
17622 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17623 }, 200 );
17624 } else {
17625 // Prevent transitioning immediately
17626 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17627 }
17628
17629 // Reevaluate clipping state since we've relocated and resized the popup
17630 this.clip();
17631
17632 return this;
17633 };
17634
17635 /**
17636 * Set popup alignment
17637 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17638 * `backwards` or `forwards`.
17639 */
17640 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17641 // Validate alignment and transform deprecated values
17642 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17643 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17644 } else {
17645 this.align = 'center';
17646 }
17647 };
17648
17649 /**
17650 * Get popup alignment
17651 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17652 * `backwards` or `forwards`.
17653 */
17654 OO.ui.PopupWidget.prototype.getAlignment = function () {
17655 return this.align;
17656 };
17657
17658 /**
17659 * Progress bars visually display the status of an operation, such as a download,
17660 * and can be either determinate or indeterminate:
17661 *
17662 * - **determinate** process bars show the percent of an operation that is complete.
17663 *
17664 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17665 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17666 * not use percentages.
17667 *
17668 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17669 *
17670 * @example
17671 * // Examples of determinate and indeterminate progress bars.
17672 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17673 * progress: 33
17674 * } );
17675 * var progressBar2 = new OO.ui.ProgressBarWidget();
17676 *
17677 * // Create a FieldsetLayout to layout progress bars
17678 * var fieldset = new OO.ui.FieldsetLayout;
17679 * fieldset.addItems( [
17680 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17681 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17682 * ] );
17683 * $( 'body' ).append( fieldset.$element );
17684 *
17685 * @class
17686 * @extends OO.ui.Widget
17687 *
17688 * @constructor
17689 * @param {Object} [config] Configuration options
17690 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17691 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17692 * By default, the progress bar is indeterminate.
17693 */
17694 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17695 // Configuration initialization
17696 config = config || {};
17697
17698 // Parent constructor
17699 OO.ui.ProgressBarWidget.parent.call( this, config );
17700
17701 // Properties
17702 this.$bar = $( '<div>' );
17703 this.progress = null;
17704
17705 // Initialization
17706 this.setProgress( config.progress !== undefined ? config.progress : false );
17707 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17708 this.$element
17709 .attr( {
17710 role: 'progressbar',
17711 'aria-valuemin': 0,
17712 'aria-valuemax': 100
17713 } )
17714 .addClass( 'oo-ui-progressBarWidget' )
17715 .append( this.$bar );
17716 };
17717
17718 /* Setup */
17719
17720 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17721
17722 /* Static Properties */
17723
17724 OO.ui.ProgressBarWidget.static.tagName = 'div';
17725
17726 /* Methods */
17727
17728 /**
17729 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17730 *
17731 * @return {number|boolean} Progress percent
17732 */
17733 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17734 return this.progress;
17735 };
17736
17737 /**
17738 * Set the percent of the process completed or `false` for an indeterminate process.
17739 *
17740 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17741 */
17742 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17743 this.progress = progress;
17744
17745 if ( progress !== false ) {
17746 this.$bar.css( 'width', this.progress + '%' );
17747 this.$element.attr( 'aria-valuenow', this.progress );
17748 } else {
17749 this.$bar.css( 'width', '' );
17750 this.$element.removeAttr( 'aria-valuenow' );
17751 }
17752 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17753 };
17754
17755 /**
17756 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17757 * and a menu of search results, which is displayed beneath the query
17758 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17759 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17760 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17761 *
17762 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17763 * the [OOjs UI demos][1] for an example.
17764 *
17765 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17766 *
17767 * @class
17768 * @extends OO.ui.Widget
17769 *
17770 * @constructor
17771 * @param {Object} [config] Configuration options
17772 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17773 * @cfg {string} [value] Initial query value
17774 */
17775 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17776 // Configuration initialization
17777 config = config || {};
17778
17779 // Parent constructor
17780 OO.ui.SearchWidget.parent.call( this, config );
17781
17782 // Properties
17783 this.query = new OO.ui.TextInputWidget( {
17784 icon: 'search',
17785 placeholder: config.placeholder,
17786 value: config.value
17787 } );
17788 this.results = new OO.ui.SelectWidget();
17789 this.$query = $( '<div>' );
17790 this.$results = $( '<div>' );
17791
17792 // Events
17793 this.query.connect( this, {
17794 change: 'onQueryChange',
17795 enter: 'onQueryEnter'
17796 } );
17797 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17798
17799 // Initialization
17800 this.$query
17801 .addClass( 'oo-ui-searchWidget-query' )
17802 .append( this.query.$element );
17803 this.$results
17804 .addClass( 'oo-ui-searchWidget-results' )
17805 .append( this.results.$element );
17806 this.$element
17807 .addClass( 'oo-ui-searchWidget' )
17808 .append( this.$results, this.$query );
17809 };
17810
17811 /* Setup */
17812
17813 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17814
17815 /* Methods */
17816
17817 /**
17818 * Handle query key down events.
17819 *
17820 * @private
17821 * @param {jQuery.Event} e Key down event
17822 */
17823 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17824 var highlightedItem, nextItem,
17825 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17826
17827 if ( dir ) {
17828 highlightedItem = this.results.getHighlightedItem();
17829 if ( !highlightedItem ) {
17830 highlightedItem = this.results.getSelectedItem();
17831 }
17832 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17833 this.results.highlightItem( nextItem );
17834 nextItem.scrollElementIntoView();
17835 }
17836 };
17837
17838 /**
17839 * Handle select widget select events.
17840 *
17841 * Clears existing results. Subclasses should repopulate items according to new query.
17842 *
17843 * @private
17844 * @param {string} value New value
17845 */
17846 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17847 // Reset
17848 this.results.clearItems();
17849 };
17850
17851 /**
17852 * Handle select widget enter key events.
17853 *
17854 * Chooses highlighted item.
17855 *
17856 * @private
17857 * @param {string} value New value
17858 */
17859 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17860 var highlightedItem = this.results.getHighlightedItem();
17861 if ( highlightedItem ) {
17862 this.results.chooseItem( highlightedItem );
17863 }
17864 };
17865
17866 /**
17867 * Get the query input.
17868 *
17869 * @return {OO.ui.TextInputWidget} Query input
17870 */
17871 OO.ui.SearchWidget.prototype.getQuery = function () {
17872 return this.query;
17873 };
17874
17875 /**
17876 * Get the search results menu.
17877 *
17878 * @return {OO.ui.SelectWidget} Menu of search results
17879 */
17880 OO.ui.SearchWidget.prototype.getResults = function () {
17881 return this.results;
17882 };
17883
17884 /**
17885 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17886 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17887 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17888 * menu selects}.
17889 *
17890 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17891 * information, please see the [OOjs UI documentation on MediaWiki][1].
17892 *
17893 * @example
17894 * // Example of a select widget with three options
17895 * var select = new OO.ui.SelectWidget( {
17896 * items: [
17897 * new OO.ui.OptionWidget( {
17898 * data: 'a',
17899 * label: 'Option One',
17900 * } ),
17901 * new OO.ui.OptionWidget( {
17902 * data: 'b',
17903 * label: 'Option Two',
17904 * } ),
17905 * new OO.ui.OptionWidget( {
17906 * data: 'c',
17907 * label: 'Option Three',
17908 * } )
17909 * ]
17910 * } );
17911 * $( 'body' ).append( select.$element );
17912 *
17913 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17914 *
17915 * @abstract
17916 * @class
17917 * @extends OO.ui.Widget
17918 * @mixins OO.ui.mixin.GroupWidget
17919 *
17920 * @constructor
17921 * @param {Object} [config] Configuration options
17922 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17923 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17924 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17925 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17926 */
17927 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17928 // Configuration initialization
17929 config = config || {};
17930
17931 // Parent constructor
17932 OO.ui.SelectWidget.parent.call( this, config );
17933
17934 // Mixin constructors
17935 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17936
17937 // Properties
17938 this.pressed = false;
17939 this.selecting = null;
17940 this.onMouseUpHandler = this.onMouseUp.bind( this );
17941 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17942 this.onKeyDownHandler = this.onKeyDown.bind( this );
17943 this.onKeyPressHandler = this.onKeyPress.bind( this );
17944 this.keyPressBuffer = '';
17945 this.keyPressBufferTimer = null;
17946
17947 // Events
17948 this.connect( this, {
17949 toggle: 'onToggle'
17950 } );
17951 this.$element.on( {
17952 mousedown: this.onMouseDown.bind( this ),
17953 mouseover: this.onMouseOver.bind( this ),
17954 mouseleave: this.onMouseLeave.bind( this )
17955 } );
17956
17957 // Initialization
17958 this.$element
17959 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17960 .attr( 'role', 'listbox' );
17961 if ( Array.isArray( config.items ) ) {
17962 this.addItems( config.items );
17963 }
17964 };
17965
17966 /* Setup */
17967
17968 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17969
17970 // Need to mixin base class as well
17971 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17972 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17973
17974 /* Static */
17975 OO.ui.SelectWidget.static.passAllFilter = function () {
17976 return true;
17977 };
17978
17979 /* Events */
17980
17981 /**
17982 * @event highlight
17983 *
17984 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17985 *
17986 * @param {OO.ui.OptionWidget|null} item Highlighted item
17987 */
17988
17989 /**
17990 * @event press
17991 *
17992 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17993 * pressed state of an option.
17994 *
17995 * @param {OO.ui.OptionWidget|null} item Pressed item
17996 */
17997
17998 /**
17999 * @event select
18000 *
18001 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18002 *
18003 * @param {OO.ui.OptionWidget|null} item Selected item
18004 */
18005
18006 /**
18007 * @event choose
18008 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18009 * @param {OO.ui.OptionWidget} item Chosen item
18010 */
18011
18012 /**
18013 * @event add
18014 *
18015 * An `add` event is emitted when options are added to the select with the #addItems method.
18016 *
18017 * @param {OO.ui.OptionWidget[]} items Added items
18018 * @param {number} index Index of insertion point
18019 */
18020
18021 /**
18022 * @event remove
18023 *
18024 * A `remove` event is emitted when options are removed from the select with the #clearItems
18025 * or #removeItems methods.
18026 *
18027 * @param {OO.ui.OptionWidget[]} items Removed items
18028 */
18029
18030 /* Methods */
18031
18032 /**
18033 * Handle mouse down events.
18034 *
18035 * @private
18036 * @param {jQuery.Event} e Mouse down event
18037 */
18038 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18039 var item;
18040
18041 if ( !this.isDisabled() && e.which === 1 ) {
18042 this.togglePressed( true );
18043 item = this.getTargetItem( e );
18044 if ( item && item.isSelectable() ) {
18045 this.pressItem( item );
18046 this.selecting = item;
18047 OO.ui.addCaptureEventListener(
18048 this.getElementDocument(),
18049 'mouseup',
18050 this.onMouseUpHandler
18051 );
18052 OO.ui.addCaptureEventListener(
18053 this.getElementDocument(),
18054 'mousemove',
18055 this.onMouseMoveHandler
18056 );
18057 }
18058 }
18059 return false;
18060 };
18061
18062 /**
18063 * Handle mouse up events.
18064 *
18065 * @private
18066 * @param {jQuery.Event} e Mouse up event
18067 */
18068 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18069 var item;
18070
18071 this.togglePressed( false );
18072 if ( !this.selecting ) {
18073 item = this.getTargetItem( e );
18074 if ( item && item.isSelectable() ) {
18075 this.selecting = item;
18076 }
18077 }
18078 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
18079 this.pressItem( null );
18080 this.chooseItem( this.selecting );
18081 this.selecting = null;
18082 }
18083
18084 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18085 this.onMouseUpHandler );
18086 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18087 this.onMouseMoveHandler );
18088
18089 return false;
18090 };
18091
18092 /**
18093 * Handle mouse move events.
18094 *
18095 * @private
18096 * @param {jQuery.Event} e Mouse move event
18097 */
18098 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18099 var item;
18100
18101 if ( !this.isDisabled() && this.pressed ) {
18102 item = this.getTargetItem( e );
18103 if ( item && item !== this.selecting && item.isSelectable() ) {
18104 this.pressItem( item );
18105 this.selecting = item;
18106 }
18107 }
18108 return false;
18109 };
18110
18111 /**
18112 * Handle mouse over events.
18113 *
18114 * @private
18115 * @param {jQuery.Event} e Mouse over event
18116 */
18117 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18118 var item;
18119
18120 if ( !this.isDisabled() ) {
18121 item = this.getTargetItem( e );
18122 this.highlightItem( item && item.isHighlightable() ? item : null );
18123 }
18124 return false;
18125 };
18126
18127 /**
18128 * Handle mouse leave events.
18129 *
18130 * @private
18131 * @param {jQuery.Event} e Mouse over event
18132 */
18133 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18134 if ( !this.isDisabled() ) {
18135 this.highlightItem( null );
18136 }
18137 return false;
18138 };
18139
18140 /**
18141 * Handle key down events.
18142 *
18143 * @protected
18144 * @param {jQuery.Event} e Key down event
18145 */
18146 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18147 var nextItem,
18148 handled = false,
18149 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18150
18151 if ( !this.isDisabled() && this.isVisible() ) {
18152 switch ( e.keyCode ) {
18153 case OO.ui.Keys.ENTER:
18154 if ( currentItem && currentItem.constructor.static.highlightable ) {
18155 // Was only highlighted, now let's select it. No-op if already selected.
18156 this.chooseItem( currentItem );
18157 handled = true;
18158 }
18159 break;
18160 case OO.ui.Keys.UP:
18161 case OO.ui.Keys.LEFT:
18162 this.clearKeyPressBuffer();
18163 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18164 handled = true;
18165 break;
18166 case OO.ui.Keys.DOWN:
18167 case OO.ui.Keys.RIGHT:
18168 this.clearKeyPressBuffer();
18169 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18170 handled = true;
18171 break;
18172 case OO.ui.Keys.ESCAPE:
18173 case OO.ui.Keys.TAB:
18174 if ( currentItem && currentItem.constructor.static.highlightable ) {
18175 currentItem.setHighlighted( false );
18176 }
18177 this.unbindKeyDownListener();
18178 this.unbindKeyPressListener();
18179 // Don't prevent tabbing away / defocusing
18180 handled = false;
18181 break;
18182 }
18183
18184 if ( nextItem ) {
18185 if ( nextItem.constructor.static.highlightable ) {
18186 this.highlightItem( nextItem );
18187 } else {
18188 this.chooseItem( nextItem );
18189 }
18190 nextItem.scrollElementIntoView();
18191 }
18192
18193 if ( handled ) {
18194 // Can't just return false, because e is not always a jQuery event
18195 e.preventDefault();
18196 e.stopPropagation();
18197 }
18198 }
18199 };
18200
18201 /**
18202 * Bind key down listener.
18203 *
18204 * @protected
18205 */
18206 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18207 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18208 };
18209
18210 /**
18211 * Unbind key down listener.
18212 *
18213 * @protected
18214 */
18215 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18216 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18217 };
18218
18219 /**
18220 * Clear the key-press buffer
18221 *
18222 * @protected
18223 */
18224 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18225 if ( this.keyPressBufferTimer ) {
18226 clearTimeout( this.keyPressBufferTimer );
18227 this.keyPressBufferTimer = null;
18228 }
18229 this.keyPressBuffer = '';
18230 };
18231
18232 /**
18233 * Handle key press events.
18234 *
18235 * @protected
18236 * @param {jQuery.Event} e Key press event
18237 */
18238 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18239 var c, filter, item;
18240
18241 if ( !e.charCode ) {
18242 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18243 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18244 return false;
18245 }
18246 return;
18247 }
18248 if ( String.fromCodePoint ) {
18249 c = String.fromCodePoint( e.charCode );
18250 } else {
18251 c = String.fromCharCode( e.charCode );
18252 }
18253
18254 if ( this.keyPressBufferTimer ) {
18255 clearTimeout( this.keyPressBufferTimer );
18256 }
18257 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18258
18259 item = this.getHighlightedItem() || this.getSelectedItem();
18260
18261 if ( this.keyPressBuffer === c ) {
18262 // Common (if weird) special case: typing "xxxx" will cycle through all
18263 // the items beginning with "x".
18264 if ( item ) {
18265 item = this.getRelativeSelectableItem( item, 1 );
18266 }
18267 } else {
18268 this.keyPressBuffer += c;
18269 }
18270
18271 filter = this.getItemMatcher( this.keyPressBuffer, false );
18272 if ( !item || !filter( item ) ) {
18273 item = this.getRelativeSelectableItem( item, 1, filter );
18274 }
18275 if ( item ) {
18276 if ( item.constructor.static.highlightable ) {
18277 this.highlightItem( item );
18278 } else {
18279 this.chooseItem( item );
18280 }
18281 item.scrollElementIntoView();
18282 }
18283
18284 return false;
18285 };
18286
18287 /**
18288 * Get a matcher for the specific string
18289 *
18290 * @protected
18291 * @param {string} s String to match against items
18292 * @param {boolean} [exact=false] Only accept exact matches
18293 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18294 */
18295 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18296 var re;
18297
18298 if ( s.normalize ) {
18299 s = s.normalize();
18300 }
18301 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18302 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18303 if ( exact ) {
18304 re += '\\s*$';
18305 }
18306 re = new RegExp( re, 'i' );
18307 return function ( item ) {
18308 var l = item.getLabel();
18309 if ( typeof l !== 'string' ) {
18310 l = item.$label.text();
18311 }
18312 if ( l.normalize ) {
18313 l = l.normalize();
18314 }
18315 return re.test( l );
18316 };
18317 };
18318
18319 /**
18320 * Bind key press listener.
18321 *
18322 * @protected
18323 */
18324 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18325 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18326 };
18327
18328 /**
18329 * Unbind key down listener.
18330 *
18331 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18332 * implementation.
18333 *
18334 * @protected
18335 */
18336 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18337 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18338 this.clearKeyPressBuffer();
18339 };
18340
18341 /**
18342 * Visibility change handler
18343 *
18344 * @protected
18345 * @param {boolean} visible
18346 */
18347 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18348 if ( !visible ) {
18349 this.clearKeyPressBuffer();
18350 }
18351 };
18352
18353 /**
18354 * Get the closest item to a jQuery.Event.
18355 *
18356 * @private
18357 * @param {jQuery.Event} e
18358 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18359 */
18360 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18361 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18362 };
18363
18364 /**
18365 * Get selected item.
18366 *
18367 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18368 */
18369 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18370 var i, len;
18371
18372 for ( i = 0, len = this.items.length; i < len; i++ ) {
18373 if ( this.items[ i ].isSelected() ) {
18374 return this.items[ i ];
18375 }
18376 }
18377 return null;
18378 };
18379
18380 /**
18381 * Get highlighted item.
18382 *
18383 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18384 */
18385 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18386 var i, len;
18387
18388 for ( i = 0, len = this.items.length; i < len; i++ ) {
18389 if ( this.items[ i ].isHighlighted() ) {
18390 return this.items[ i ];
18391 }
18392 }
18393 return null;
18394 };
18395
18396 /**
18397 * Toggle pressed state.
18398 *
18399 * Press is a state that occurs when a user mouses down on an item, but
18400 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18401 * until the user releases the mouse.
18402 *
18403 * @param {boolean} pressed An option is being pressed
18404 */
18405 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18406 if ( pressed === undefined ) {
18407 pressed = !this.pressed;
18408 }
18409 if ( pressed !== this.pressed ) {
18410 this.$element
18411 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18412 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18413 this.pressed = pressed;
18414 }
18415 };
18416
18417 /**
18418 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18419 * and any existing highlight will be removed. The highlight is mutually exclusive.
18420 *
18421 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18422 * @fires highlight
18423 * @chainable
18424 */
18425 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18426 var i, len, highlighted,
18427 changed = false;
18428
18429 for ( i = 0, len = this.items.length; i < len; i++ ) {
18430 highlighted = this.items[ i ] === item;
18431 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18432 this.items[ i ].setHighlighted( highlighted );
18433 changed = true;
18434 }
18435 }
18436 if ( changed ) {
18437 this.emit( 'highlight', item );
18438 }
18439
18440 return this;
18441 };
18442
18443 /**
18444 * Fetch an item by its label.
18445 *
18446 * @param {string} label Label of the item to select.
18447 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18448 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18449 */
18450 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18451 var i, item, found,
18452 len = this.items.length,
18453 filter = this.getItemMatcher( label, true );
18454
18455 for ( i = 0; i < len; i++ ) {
18456 item = this.items[ i ];
18457 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18458 return item;
18459 }
18460 }
18461
18462 if ( prefix ) {
18463 found = null;
18464 filter = this.getItemMatcher( label, false );
18465 for ( i = 0; i < len; i++ ) {
18466 item = this.items[ i ];
18467 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18468 if ( found ) {
18469 return null;
18470 }
18471 found = item;
18472 }
18473 }
18474 if ( found ) {
18475 return found;
18476 }
18477 }
18478
18479 return null;
18480 };
18481
18482 /**
18483 * Programmatically select an option by its label. If the item does not exist,
18484 * all options will be deselected.
18485 *
18486 * @param {string} [label] Label of the item to select.
18487 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18488 * @fires select
18489 * @chainable
18490 */
18491 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18492 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18493 if ( label === undefined || !itemFromLabel ) {
18494 return this.selectItem();
18495 }
18496 return this.selectItem( itemFromLabel );
18497 };
18498
18499 /**
18500 * Programmatically select an option by its data. If the `data` parameter is omitted,
18501 * or if the item does not exist, all options will be deselected.
18502 *
18503 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18504 * @fires select
18505 * @chainable
18506 */
18507 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18508 var itemFromData = this.getItemFromData( data );
18509 if ( data === undefined || !itemFromData ) {
18510 return this.selectItem();
18511 }
18512 return this.selectItem( itemFromData );
18513 };
18514
18515 /**
18516 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18517 * all options will be deselected.
18518 *
18519 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18520 * @fires select
18521 * @chainable
18522 */
18523 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18524 var i, len, selected,
18525 changed = false;
18526
18527 for ( i = 0, len = this.items.length; i < len; i++ ) {
18528 selected = this.items[ i ] === item;
18529 if ( this.items[ i ].isSelected() !== selected ) {
18530 this.items[ i ].setSelected( selected );
18531 changed = true;
18532 }
18533 }
18534 if ( changed ) {
18535 this.emit( 'select', item );
18536 }
18537
18538 return this;
18539 };
18540
18541 /**
18542 * Press an item.
18543 *
18544 * Press is a state that occurs when a user mouses down on an item, but has not
18545 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18546 * releases the mouse.
18547 *
18548 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18549 * @fires press
18550 * @chainable
18551 */
18552 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18553 var i, len, pressed,
18554 changed = false;
18555
18556 for ( i = 0, len = this.items.length; i < len; i++ ) {
18557 pressed = this.items[ i ] === item;
18558 if ( this.items[ i ].isPressed() !== pressed ) {
18559 this.items[ i ].setPressed( pressed );
18560 changed = true;
18561 }
18562 }
18563 if ( changed ) {
18564 this.emit( 'press', item );
18565 }
18566
18567 return this;
18568 };
18569
18570 /**
18571 * Choose an item.
18572 *
18573 * Note that ‘choose’ should never be modified programmatically. A user can choose
18574 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18575 * use the #selectItem method.
18576 *
18577 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18578 * when users choose an item with the keyboard or mouse.
18579 *
18580 * @param {OO.ui.OptionWidget} item Item to choose
18581 * @fires choose
18582 * @chainable
18583 */
18584 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18585 if ( item ) {
18586 this.selectItem( item );
18587 this.emit( 'choose', item );
18588 }
18589
18590 return this;
18591 };
18592
18593 /**
18594 * Get an option by its position relative to the specified item (or to the start of the option array,
18595 * if item is `null`). The direction in which to search through the option array is specified with a
18596 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18597 * `null` if there are no options in the array.
18598 *
18599 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18600 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18601 * @param {Function} filter Only consider items for which this function returns
18602 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18603 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18604 */
18605 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18606 var currentIndex, nextIndex, i,
18607 increase = direction > 0 ? 1 : -1,
18608 len = this.items.length;
18609
18610 if ( !$.isFunction( filter ) ) {
18611 filter = OO.ui.SelectWidget.static.passAllFilter;
18612 }
18613
18614 if ( item instanceof OO.ui.OptionWidget ) {
18615 currentIndex = this.items.indexOf( item );
18616 nextIndex = ( currentIndex + increase + len ) % len;
18617 } else {
18618 // If no item is selected and moving forward, start at the beginning.
18619 // If moving backward, start at the end.
18620 nextIndex = direction > 0 ? 0 : len - 1;
18621 }
18622
18623 for ( i = 0; i < len; i++ ) {
18624 item = this.items[ nextIndex ];
18625 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18626 return item;
18627 }
18628 nextIndex = ( nextIndex + increase + len ) % len;
18629 }
18630 return null;
18631 };
18632
18633 /**
18634 * Get the next selectable item or `null` if there are no selectable items.
18635 * Disabled options and menu-section markers and breaks are not selectable.
18636 *
18637 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18638 */
18639 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18640 var i, len, item;
18641
18642 for ( i = 0, len = this.items.length; i < len; i++ ) {
18643 item = this.items[ i ];
18644 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18645 return item;
18646 }
18647 }
18648
18649 return null;
18650 };
18651
18652 /**
18653 * Add an array of options to the select. Optionally, an index number can be used to
18654 * specify an insertion point.
18655 *
18656 * @param {OO.ui.OptionWidget[]} items Items to add
18657 * @param {number} [index] Index to insert items after
18658 * @fires add
18659 * @chainable
18660 */
18661 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18662 // Mixin method
18663 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18664
18665 // Always provide an index, even if it was omitted
18666 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18667
18668 return this;
18669 };
18670
18671 /**
18672 * Remove the specified array of options from the select. Options will be detached
18673 * from the DOM, not removed, so they can be reused later. To remove all options from
18674 * the select, you may wish to use the #clearItems method instead.
18675 *
18676 * @param {OO.ui.OptionWidget[]} items Items to remove
18677 * @fires remove
18678 * @chainable
18679 */
18680 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18681 var i, len, item;
18682
18683 // Deselect items being removed
18684 for ( i = 0, len = items.length; i < len; i++ ) {
18685 item = items[ i ];
18686 if ( item.isSelected() ) {
18687 this.selectItem( null );
18688 }
18689 }
18690
18691 // Mixin method
18692 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18693
18694 this.emit( 'remove', items );
18695
18696 return this;
18697 };
18698
18699 /**
18700 * Clear all options from the select. Options will be detached from the DOM, not removed,
18701 * so that they can be reused later. To remove a subset of options from the select, use
18702 * the #removeItems method.
18703 *
18704 * @fires remove
18705 * @chainable
18706 */
18707 OO.ui.SelectWidget.prototype.clearItems = function () {
18708 var items = this.items.slice();
18709
18710 // Mixin method
18711 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18712
18713 // Clear selection
18714 this.selectItem( null );
18715
18716 this.emit( 'remove', items );
18717
18718 return this;
18719 };
18720
18721 /**
18722 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18723 * button options and is used together with
18724 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18725 * highlighting, choosing, and selecting mutually exclusive options. Please see
18726 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18727 *
18728 * @example
18729 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18730 * var option1 = new OO.ui.ButtonOptionWidget( {
18731 * data: 1,
18732 * label: 'Option 1',
18733 * title: 'Button option 1'
18734 * } );
18735 *
18736 * var option2 = new OO.ui.ButtonOptionWidget( {
18737 * data: 2,
18738 * label: 'Option 2',
18739 * title: 'Button option 2'
18740 * } );
18741 *
18742 * var option3 = new OO.ui.ButtonOptionWidget( {
18743 * data: 3,
18744 * label: 'Option 3',
18745 * title: 'Button option 3'
18746 * } );
18747 *
18748 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18749 * items: [ option1, option2, option3 ]
18750 * } );
18751 * $( 'body' ).append( buttonSelect.$element );
18752 *
18753 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18754 *
18755 * @class
18756 * @extends OO.ui.SelectWidget
18757 * @mixins OO.ui.mixin.TabIndexedElement
18758 *
18759 * @constructor
18760 * @param {Object} [config] Configuration options
18761 */
18762 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18763 // Parent constructor
18764 OO.ui.ButtonSelectWidget.parent.call( this, config );
18765
18766 // Mixin constructors
18767 OO.ui.mixin.TabIndexedElement.call( this, config );
18768
18769 // Events
18770 this.$element.on( {
18771 focus: this.bindKeyDownListener.bind( this ),
18772 blur: this.unbindKeyDownListener.bind( this )
18773 } );
18774
18775 // Initialization
18776 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18777 };
18778
18779 /* Setup */
18780
18781 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18782 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18783
18784 /**
18785 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18786 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18787 * an interface for adding, removing and selecting options.
18788 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18789 *
18790 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18791 * OO.ui.RadioSelectInputWidget instead.
18792 *
18793 * @example
18794 * // A RadioSelectWidget with RadioOptions.
18795 * var option1 = new OO.ui.RadioOptionWidget( {
18796 * data: 'a',
18797 * label: 'Selected radio option'
18798 * } );
18799 *
18800 * var option2 = new OO.ui.RadioOptionWidget( {
18801 * data: 'b',
18802 * label: 'Unselected radio option'
18803 * } );
18804 *
18805 * var radioSelect=new OO.ui.RadioSelectWidget( {
18806 * items: [ option1, option2 ]
18807 * } );
18808 *
18809 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18810 * radioSelect.selectItem( option1 );
18811 *
18812 * $( 'body' ).append( radioSelect.$element );
18813 *
18814 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18815
18816 *
18817 * @class
18818 * @extends OO.ui.SelectWidget
18819 * @mixins OO.ui.mixin.TabIndexedElement
18820 *
18821 * @constructor
18822 * @param {Object} [config] Configuration options
18823 */
18824 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18825 // Parent constructor
18826 OO.ui.RadioSelectWidget.parent.call( this, config );
18827
18828 // Mixin constructors
18829 OO.ui.mixin.TabIndexedElement.call( this, config );
18830
18831 // Events
18832 this.$element.on( {
18833 focus: this.bindKeyDownListener.bind( this ),
18834 blur: this.unbindKeyDownListener.bind( this )
18835 } );
18836
18837 // Initialization
18838 this.$element
18839 .addClass( 'oo-ui-radioSelectWidget' )
18840 .attr( 'role', 'radiogroup' );
18841 };
18842
18843 /* Setup */
18844
18845 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18846 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18847
18848 /**
18849 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18850 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18851 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18852 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18853 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18854 * and customized to be opened, closed, and displayed as needed.
18855 *
18856 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18857 * mouse outside the menu.
18858 *
18859 * Menus also have support for keyboard interaction:
18860 *
18861 * - Enter/Return key: choose and select a menu option
18862 * - Up-arrow key: highlight the previous menu option
18863 * - Down-arrow key: highlight the next menu option
18864 * - Esc key: hide the menu
18865 *
18866 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18868 *
18869 * @class
18870 * @extends OO.ui.SelectWidget
18871 * @mixins OO.ui.mixin.ClippableElement
18872 *
18873 * @constructor
18874 * @param {Object} [config] Configuration options
18875 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18876 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18877 * and {@link OO.ui.mixin.LookupElement LookupElement}
18878 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18879 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18880 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18881 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18882 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18883 * that button, unless the button (or its parent widget) is passed in here.
18884 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18885 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18886 */
18887 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18888 // Configuration initialization
18889 config = config || {};
18890
18891 // Parent constructor
18892 OO.ui.MenuSelectWidget.parent.call( this, config );
18893
18894 // Mixin constructors
18895 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18896
18897 // Properties
18898 this.newItems = null;
18899 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18900 this.filterFromInput = !!config.filterFromInput;
18901 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18902 this.$widget = config.widget ? config.widget.$element : null;
18903 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18904 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18905
18906 // Initialization
18907 this.$element
18908 .addClass( 'oo-ui-menuSelectWidget' )
18909 .attr( 'role', 'menu' );
18910
18911 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18912 // that reference properties not initialized at that time of parent class construction
18913 // TODO: Find a better way to handle post-constructor setup
18914 this.visible = false;
18915 this.$element.addClass( 'oo-ui-element-hidden' );
18916 };
18917
18918 /* Setup */
18919
18920 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18921 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18922
18923 /* Methods */
18924
18925 /**
18926 * Handles document mouse down events.
18927 *
18928 * @protected
18929 * @param {jQuery.Event} e Key down event
18930 */
18931 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18932 if (
18933 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18934 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18935 ) {
18936 this.toggle( false );
18937 }
18938 };
18939
18940 /**
18941 * @inheritdoc
18942 */
18943 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18944 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18945
18946 if ( !this.isDisabled() && this.isVisible() ) {
18947 switch ( e.keyCode ) {
18948 case OO.ui.Keys.LEFT:
18949 case OO.ui.Keys.RIGHT:
18950 // Do nothing if a text field is associated, arrow keys will be handled natively
18951 if ( !this.$input ) {
18952 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18953 }
18954 break;
18955 case OO.ui.Keys.ESCAPE:
18956 case OO.ui.Keys.TAB:
18957 if ( currentItem ) {
18958 currentItem.setHighlighted( false );
18959 }
18960 this.toggle( false );
18961 // Don't prevent tabbing away, prevent defocusing
18962 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18963 e.preventDefault();
18964 e.stopPropagation();
18965 }
18966 break;
18967 default:
18968 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18969 return;
18970 }
18971 }
18972 };
18973
18974 /**
18975 * Update menu item visibility after input changes.
18976 * @protected
18977 */
18978 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18979 var i, item,
18980 len = this.items.length,
18981 showAll = !this.isVisible(),
18982 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18983
18984 for ( i = 0; i < len; i++ ) {
18985 item = this.items[ i ];
18986 if ( item instanceof OO.ui.OptionWidget ) {
18987 item.toggle( showAll || filter( item ) );
18988 }
18989 }
18990
18991 // Reevaluate clipping
18992 this.clip();
18993 };
18994
18995 /**
18996 * @inheritdoc
18997 */
18998 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18999 if ( this.$input ) {
19000 this.$input.on( 'keydown', this.onKeyDownHandler );
19001 } else {
19002 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19003 }
19004 };
19005
19006 /**
19007 * @inheritdoc
19008 */
19009 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19010 if ( this.$input ) {
19011 this.$input.off( 'keydown', this.onKeyDownHandler );
19012 } else {
19013 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19014 }
19015 };
19016
19017 /**
19018 * @inheritdoc
19019 */
19020 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19021 if ( this.$input ) {
19022 if ( this.filterFromInput ) {
19023 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19024 }
19025 } else {
19026 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19027 }
19028 };
19029
19030 /**
19031 * @inheritdoc
19032 */
19033 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19034 if ( this.$input ) {
19035 if ( this.filterFromInput ) {
19036 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19037 this.updateItemVisibility();
19038 }
19039 } else {
19040 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19041 }
19042 };
19043
19044 /**
19045 * Choose an item.
19046 *
19047 * When a user chooses an item, the menu is closed.
19048 *
19049 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19050 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19051 * @param {OO.ui.OptionWidget} item Item to choose
19052 * @chainable
19053 */
19054 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19055 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19056 this.toggle( false );
19057 return this;
19058 };
19059
19060 /**
19061 * @inheritdoc
19062 */
19063 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19064 var i, len, item;
19065
19066 // Parent method
19067 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19068
19069 // Auto-initialize
19070 if ( !this.newItems ) {
19071 this.newItems = [];
19072 }
19073
19074 for ( i = 0, len = items.length; i < len; i++ ) {
19075 item = items[ i ];
19076 if ( this.isVisible() ) {
19077 // Defer fitting label until item has been attached
19078 item.fitLabel();
19079 } else {
19080 this.newItems.push( item );
19081 }
19082 }
19083
19084 // Reevaluate clipping
19085 this.clip();
19086
19087 return this;
19088 };
19089
19090 /**
19091 * @inheritdoc
19092 */
19093 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19094 // Parent method
19095 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19096
19097 // Reevaluate clipping
19098 this.clip();
19099
19100 return this;
19101 };
19102
19103 /**
19104 * @inheritdoc
19105 */
19106 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19107 // Parent method
19108 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19109
19110 // Reevaluate clipping
19111 this.clip();
19112
19113 return this;
19114 };
19115
19116 /**
19117 * @inheritdoc
19118 */
19119 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19120 var i, len, change;
19121
19122 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19123 change = visible !== this.isVisible();
19124
19125 // Parent method
19126 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19127
19128 if ( change ) {
19129 if ( visible ) {
19130 this.bindKeyDownListener();
19131 this.bindKeyPressListener();
19132
19133 if ( this.newItems && this.newItems.length ) {
19134 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19135 this.newItems[ i ].fitLabel();
19136 }
19137 this.newItems = null;
19138 }
19139 this.toggleClipping( true );
19140
19141 // Auto-hide
19142 if ( this.autoHide ) {
19143 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19144 }
19145 } else {
19146 this.unbindKeyDownListener();
19147 this.unbindKeyPressListener();
19148 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19149 this.toggleClipping( false );
19150 }
19151 }
19152
19153 return this;
19154 };
19155
19156 /**
19157 * FloatingMenuSelectWidget is a menu that will stick under a specified
19158 * container, even when it is inserted elsewhere in the document (for example,
19159 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19160 * menu from being clipped too aggresively.
19161 *
19162 * The menu's position is automatically calculated and maintained when the menu
19163 * is toggled or the window is resized.
19164 *
19165 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
19166 *
19167 * @class
19168 * @extends OO.ui.MenuSelectWidget
19169 * @mixins OO.ui.mixin.FloatableElement
19170 *
19171 * @constructor
19172 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19173 * Deprecated, omit this parameter and specify `$container` instead.
19174 * @param {Object} [config] Configuration options
19175 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19176 */
19177 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19178 // Allow 'inputWidget' parameter and config for backwards compatibility
19179 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19180 config = inputWidget;
19181 inputWidget = config.inputWidget;
19182 }
19183
19184 // Configuration initialization
19185 config = config || {};
19186
19187 // Parent constructor
19188 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19189
19190 // Properties (must be set before mixin constructors)
19191 this.inputWidget = inputWidget; // For backwards compatibility
19192 this.$container = config.$container || this.inputWidget.$element;
19193
19194 // Mixins constructors
19195 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19196
19197 // Initialization
19198 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19199 // For backwards compatibility
19200 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19201 };
19202
19203 /* Setup */
19204
19205 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19206 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19207
19208 // For backwards compatibility
19209 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19210
19211 /* Methods */
19212
19213 /**
19214 * @inheritdoc
19215 */
19216 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19217 var change;
19218 visible = visible === undefined ? !this.isVisible() : !!visible;
19219 change = visible !== this.isVisible();
19220
19221 if ( change && visible ) {
19222 // Make sure the width is set before the parent method runs.
19223 this.setIdealSize( this.$container.width() );
19224 }
19225
19226 // Parent method
19227 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19228 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19229
19230 if ( change ) {
19231 this.togglePositioning( this.isVisible() );
19232 }
19233
19234 return this;
19235 };
19236
19237 /**
19238 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19239 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19240 *
19241 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19242 *
19243 * @class
19244 * @extends OO.ui.SelectWidget
19245 * @mixins OO.ui.mixin.TabIndexedElement
19246 *
19247 * @constructor
19248 * @param {Object} [config] Configuration options
19249 */
19250 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19251 // Parent constructor
19252 OO.ui.OutlineSelectWidget.parent.call( this, config );
19253
19254 // Mixin constructors
19255 OO.ui.mixin.TabIndexedElement.call( this, config );
19256
19257 // Events
19258 this.$element.on( {
19259 focus: this.bindKeyDownListener.bind( this ),
19260 blur: this.unbindKeyDownListener.bind( this )
19261 } );
19262
19263 // Initialization
19264 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19265 };
19266
19267 /* Setup */
19268
19269 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19270 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19271
19272 /**
19273 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19274 *
19275 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19276 *
19277 * @class
19278 * @extends OO.ui.SelectWidget
19279 * @mixins OO.ui.mixin.TabIndexedElement
19280 *
19281 * @constructor
19282 * @param {Object} [config] Configuration options
19283 */
19284 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19285 // Parent constructor
19286 OO.ui.TabSelectWidget.parent.call( this, config );
19287
19288 // Mixin constructors
19289 OO.ui.mixin.TabIndexedElement.call( this, config );
19290
19291 // Events
19292 this.$element.on( {
19293 focus: this.bindKeyDownListener.bind( this ),
19294 blur: this.unbindKeyDownListener.bind( this )
19295 } );
19296
19297 // Initialization
19298 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19299 };
19300
19301 /* Setup */
19302
19303 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19304 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19305
19306 /**
19307 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19308 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19309 * (to adjust the value in increments) to allow the user to enter a number.
19310 *
19311 * @example
19312 * // Example: A NumberInputWidget.
19313 * var numberInput = new OO.ui.NumberInputWidget( {
19314 * label: 'NumberInputWidget',
19315 * input: { value: 5, min: 1, max: 10 }
19316 * } );
19317 * $( 'body' ).append( numberInput.$element );
19318 *
19319 * @class
19320 * @extends OO.ui.Widget
19321 *
19322 * @constructor
19323 * @param {Object} [config] Configuration options
19324 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19325 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19326 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19327 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19328 * @cfg {number} [min=-Infinity] Minimum allowed value
19329 * @cfg {number} [max=Infinity] Maximum allowed value
19330 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19331 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19332 */
19333 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19334 // Configuration initialization
19335 config = $.extend( {
19336 isInteger: false,
19337 min: -Infinity,
19338 max: Infinity,
19339 step: 1,
19340 pageStep: null
19341 }, config );
19342
19343 // Parent constructor
19344 OO.ui.NumberInputWidget.parent.call( this, config );
19345
19346 // Properties
19347 this.input = new OO.ui.TextInputWidget( $.extend(
19348 {
19349 disabled: this.isDisabled()
19350 },
19351 config.input
19352 ) );
19353 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19354 {
19355 disabled: this.isDisabled(),
19356 tabIndex: -1
19357 },
19358 config.minusButton,
19359 {
19360 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19361 label: '−'
19362 }
19363 ) );
19364 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19365 {
19366 disabled: this.isDisabled(),
19367 tabIndex: -1
19368 },
19369 config.plusButton,
19370 {
19371 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19372 label: '+'
19373 }
19374 ) );
19375
19376 // Events
19377 this.input.connect( this, {
19378 change: this.emit.bind( this, 'change' ),
19379 enter: this.emit.bind( this, 'enter' )
19380 } );
19381 this.input.$input.on( {
19382 keydown: this.onKeyDown.bind( this ),
19383 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19384 } );
19385 this.plusButton.connect( this, {
19386 click: [ 'onButtonClick', +1 ]
19387 } );
19388 this.minusButton.connect( this, {
19389 click: [ 'onButtonClick', -1 ]
19390 } );
19391
19392 // Initialization
19393 this.setIsInteger( !!config.isInteger );
19394 this.setRange( config.min, config.max );
19395 this.setStep( config.step, config.pageStep );
19396
19397 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19398 .append(
19399 this.minusButton.$element,
19400 this.input.$element,
19401 this.plusButton.$element
19402 );
19403 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19404 this.input.setValidation( this.validateNumber.bind( this ) );
19405 };
19406
19407 /* Setup */
19408
19409 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19410
19411 /* Events */
19412
19413 /**
19414 * A `change` event is emitted when the value of the input changes.
19415 *
19416 * @event change
19417 */
19418
19419 /**
19420 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19421 *
19422 * @event enter
19423 */
19424
19425 /* Methods */
19426
19427 /**
19428 * Set whether only integers are allowed
19429 * @param {boolean} flag
19430 */
19431 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19432 this.isInteger = !!flag;
19433 this.input.setValidityFlag();
19434 };
19435
19436 /**
19437 * Get whether only integers are allowed
19438 * @return {boolean} Flag value
19439 */
19440 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19441 return this.isInteger;
19442 };
19443
19444 /**
19445 * Set the range of allowed values
19446 * @param {number} min Minimum allowed value
19447 * @param {number} max Maximum allowed value
19448 */
19449 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19450 if ( min > max ) {
19451 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19452 }
19453 this.min = min;
19454 this.max = max;
19455 this.input.setValidityFlag();
19456 };
19457
19458 /**
19459 * Get the current range
19460 * @return {number[]} Minimum and maximum values
19461 */
19462 OO.ui.NumberInputWidget.prototype.getRange = function () {
19463 return [ this.min, this.max ];
19464 };
19465
19466 /**
19467 * Set the stepping deltas
19468 * @param {number} step Normal step
19469 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19470 */
19471 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19472 if ( step <= 0 ) {
19473 throw new Error( 'Step value must be positive' );
19474 }
19475 if ( pageStep === null ) {
19476 pageStep = step * 10;
19477 } else if ( pageStep <= 0 ) {
19478 throw new Error( 'Page step value must be positive' );
19479 }
19480 this.step = step;
19481 this.pageStep = pageStep;
19482 };
19483
19484 /**
19485 * Get the current stepping values
19486 * @return {number[]} Step and page step
19487 */
19488 OO.ui.NumberInputWidget.prototype.getStep = function () {
19489 return [ this.step, this.pageStep ];
19490 };
19491
19492 /**
19493 * Get the current value of the widget
19494 * @return {string}
19495 */
19496 OO.ui.NumberInputWidget.prototype.getValue = function () {
19497 return this.input.getValue();
19498 };
19499
19500 /**
19501 * Get the current value of the widget as a number
19502 * @return {number} May be NaN, or an invalid number
19503 */
19504 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19505 return +this.input.getValue();
19506 };
19507
19508 /**
19509 * Set the value of the widget
19510 * @param {string} value Invalid values are allowed
19511 */
19512 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19513 this.input.setValue( value );
19514 };
19515
19516 /**
19517 * Adjust the value of the widget
19518 * @param {number} delta Adjustment amount
19519 */
19520 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19521 var n, v = this.getNumericValue();
19522
19523 delta = +delta;
19524 if ( isNaN( delta ) || !isFinite( delta ) ) {
19525 throw new Error( 'Delta must be a finite number' );
19526 }
19527
19528 if ( isNaN( v ) ) {
19529 n = 0;
19530 } else {
19531 n = v + delta;
19532 n = Math.max( Math.min( n, this.max ), this.min );
19533 if ( this.isInteger ) {
19534 n = Math.round( n );
19535 }
19536 }
19537
19538 if ( n !== v ) {
19539 this.setValue( n );
19540 }
19541 };
19542
19543 /**
19544 * Validate input
19545 * @private
19546 * @param {string} value Field value
19547 * @return {boolean}
19548 */
19549 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19550 var n = +value;
19551 if ( isNaN( n ) || !isFinite( n ) ) {
19552 return false;
19553 }
19554
19555 /*jshint bitwise: false */
19556 if ( this.isInteger && ( n | 0 ) !== n ) {
19557 return false;
19558 }
19559 /*jshint bitwise: true */
19560
19561 if ( n < this.min || n > this.max ) {
19562 return false;
19563 }
19564
19565 return true;
19566 };
19567
19568 /**
19569 * Handle mouse click events.
19570 *
19571 * @private
19572 * @param {number} dir +1 or -1
19573 */
19574 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19575 this.adjustValue( dir * this.step );
19576 };
19577
19578 /**
19579 * Handle mouse wheel events.
19580 *
19581 * @private
19582 * @param {jQuery.Event} event
19583 */
19584 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19585 var delta = 0;
19586
19587 // Standard 'wheel' event
19588 if ( event.originalEvent.deltaMode !== undefined ) {
19589 this.sawWheelEvent = true;
19590 }
19591 if ( event.originalEvent.deltaY ) {
19592 delta = -event.originalEvent.deltaY;
19593 } else if ( event.originalEvent.deltaX ) {
19594 delta = event.originalEvent.deltaX;
19595 }
19596
19597 // Non-standard events
19598 if ( !this.sawWheelEvent ) {
19599 if ( event.originalEvent.wheelDeltaX ) {
19600 delta = -event.originalEvent.wheelDeltaX;
19601 } else if ( event.originalEvent.wheelDeltaY ) {
19602 delta = event.originalEvent.wheelDeltaY;
19603 } else if ( event.originalEvent.wheelDelta ) {
19604 delta = event.originalEvent.wheelDelta;
19605 } else if ( event.originalEvent.detail ) {
19606 delta = -event.originalEvent.detail;
19607 }
19608 }
19609
19610 if ( delta ) {
19611 delta = delta < 0 ? -1 : 1;
19612 this.adjustValue( delta * this.step );
19613 }
19614
19615 return false;
19616 };
19617
19618 /**
19619 * Handle key down events.
19620 *
19621 * @private
19622 * @param {jQuery.Event} e Key down event
19623 */
19624 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19625 if ( !this.isDisabled() ) {
19626 switch ( e.which ) {
19627 case OO.ui.Keys.UP:
19628 this.adjustValue( this.step );
19629 return false;
19630 case OO.ui.Keys.DOWN:
19631 this.adjustValue( -this.step );
19632 return false;
19633 case OO.ui.Keys.PAGEUP:
19634 this.adjustValue( this.pageStep );
19635 return false;
19636 case OO.ui.Keys.PAGEDOWN:
19637 this.adjustValue( -this.pageStep );
19638 return false;
19639 }
19640 }
19641 };
19642
19643 /**
19644 * @inheritdoc
19645 */
19646 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19647 // Parent method
19648 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19649
19650 if ( this.input ) {
19651 this.input.setDisabled( this.isDisabled() );
19652 }
19653 if ( this.minusButton ) {
19654 this.minusButton.setDisabled( this.isDisabled() );
19655 }
19656 if ( this.plusButton ) {
19657 this.plusButton.setDisabled( this.isDisabled() );
19658 }
19659
19660 return this;
19661 };
19662
19663 /**
19664 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19665 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19666 * visually by a slider in the leftmost position.
19667 *
19668 * @example
19669 * // Toggle switches in the 'off' and 'on' position.
19670 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19671 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19672 * value: true
19673 * } );
19674 *
19675 * // Create a FieldsetLayout to layout and label switches
19676 * var fieldset = new OO.ui.FieldsetLayout( {
19677 * label: 'Toggle switches'
19678 * } );
19679 * fieldset.addItems( [
19680 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19681 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19682 * ] );
19683 * $( 'body' ).append( fieldset.$element );
19684 *
19685 * @class
19686 * @extends OO.ui.ToggleWidget
19687 * @mixins OO.ui.mixin.TabIndexedElement
19688 *
19689 * @constructor
19690 * @param {Object} [config] Configuration options
19691 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19692 * By default, the toggle switch is in the 'off' position.
19693 */
19694 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19695 // Parent constructor
19696 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19697
19698 // Mixin constructors
19699 OO.ui.mixin.TabIndexedElement.call( this, config );
19700
19701 // Properties
19702 this.dragging = false;
19703 this.dragStart = null;
19704 this.sliding = false;
19705 this.$glow = $( '<span>' );
19706 this.$grip = $( '<span>' );
19707
19708 // Events
19709 this.$element.on( {
19710 click: this.onClick.bind( this ),
19711 keypress: this.onKeyPress.bind( this )
19712 } );
19713
19714 // Initialization
19715 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19716 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19717 this.$element
19718 .addClass( 'oo-ui-toggleSwitchWidget' )
19719 .attr( 'role', 'checkbox' )
19720 .append( this.$glow, this.$grip );
19721 };
19722
19723 /* Setup */
19724
19725 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19726 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19727
19728 /* Methods */
19729
19730 /**
19731 * Handle mouse click events.
19732 *
19733 * @private
19734 * @param {jQuery.Event} e Mouse click event
19735 */
19736 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19737 if ( !this.isDisabled() && e.which === 1 ) {
19738 this.setValue( !this.value );
19739 }
19740 return false;
19741 };
19742
19743 /**
19744 * Handle key press events.
19745 *
19746 * @private
19747 * @param {jQuery.Event} e Key press event
19748 */
19749 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19750 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19751 this.setValue( !this.value );
19752 return false;
19753 }
19754 };
19755
19756 }( OO ) );