Update OOjs UI to v0.14.0
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.14.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-11-25T01:06:47Z
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 * @param {string} key Message key
354 * @param {Mixed...} [params] Message parameters
355 * @return {string} Translated message with parameters substituted
356 */
357 OO.ui.msg = function ( key ) {
358 var message = messages[ key ],
359 params = Array.prototype.slice.call( arguments, 1 );
360 if ( typeof message === 'string' ) {
361 // Perform $1 substitution
362 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
363 var i = parseInt( n, 10 );
364 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
365 } );
366 } else {
367 // Return placeholder if message not found
368 message = '[' + key + ']';
369 }
370 return message;
371 };
372
373 /**
374 * Package a message and arguments for deferred resolution.
375 *
376 * Use this when you are statically specifying a message and the message may not yet be present.
377 *
378 * @param {string} key Message key
379 * @param {Mixed...} [params] Message parameters
380 * @return {Function} Function that returns the resolved message when executed
381 */
382 OO.ui.deferMsg = function () {
383 var args = arguments;
384 return function () {
385 return OO.ui.msg.apply( OO.ui, args );
386 };
387 };
388
389 /**
390 * Resolve a message.
391 *
392 * If the message is a function it will be executed, otherwise it will pass through directly.
393 *
394 * @param {Function|string} msg Deferred message, or message text
395 * @return {string} Resolved message
396 */
397 OO.ui.resolveMsg = function ( msg ) {
398 if ( $.isFunction( msg ) ) {
399 return msg();
400 }
401 return msg;
402 };
403
404 /**
405 * @param {string} url
406 * @return {boolean}
407 */
408 OO.ui.isSafeUrl = function ( url ) {
409 var protocol,
410 // Keep in sync with php/Tag.php
411 whitelist = [
412 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
413 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
414 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
415 ];
416
417 if ( url.indexOf( ':' ) === -1 ) {
418 // No protocol, safe
419 return true;
420 }
421
422 protocol = url.split( ':', 1 )[ 0 ] + ':';
423 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
424 // Not a valid protocol, safe
425 return true;
426 }
427
428 // Safe if in the whitelist
429 return whitelist.indexOf( protocol ) !== -1;
430 };
431
432 } )();
433
434 /*!
435 * Mixin namespace.
436 */
437
438 /**
439 * Namespace for OOjs UI mixins.
440 *
441 * Mixins are named according to the type of object they are intended to
442 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
443 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
444 * is intended to be mixed in to an instance of OO.ui.Widget.
445 *
446 * @class
447 * @singleton
448 */
449 OO.ui.mixin = {};
450
451 /**
452 * PendingElement is a mixin that is used to create elements that notify users that something is happening
453 * and that they should wait before proceeding. The pending state is visually represented with a pending
454 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
455 * field of a {@link OO.ui.TextInputWidget text input widget}.
456 *
457 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
458 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
459 * in process dialogs.
460 *
461 * @example
462 * function MessageDialog( config ) {
463 * MessageDialog.parent.call( this, config );
464 * }
465 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
466 *
467 * MessageDialog.static.actions = [
468 * { action: 'save', label: 'Done', flags: 'primary' },
469 * { label: 'Cancel', flags: 'safe' }
470 * ];
471 *
472 * MessageDialog.prototype.initialize = function () {
473 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
474 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
475 * 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>' );
476 * this.$body.append( this.content.$element );
477 * };
478 * MessageDialog.prototype.getBodyHeight = function () {
479 * return 100;
480 * }
481 * MessageDialog.prototype.getActionProcess = function ( action ) {
482 * var dialog = this;
483 * if ( action === 'save' ) {
484 * dialog.getActions().get({actions: 'save'})[0].pushPending();
485 * return new OO.ui.Process()
486 * .next( 1000 )
487 * .next( function () {
488 * dialog.getActions().get({actions: 'save'})[0].popPending();
489 * } );
490 * }
491 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
492 * };
493 *
494 * var windowManager = new OO.ui.WindowManager();
495 * $( 'body' ).append( windowManager.$element );
496 *
497 * var dialog = new MessageDialog();
498 * windowManager.addWindows( [ dialog ] );
499 * windowManager.openWindow( dialog );
500 *
501 * @abstract
502 * @class
503 *
504 * @constructor
505 * @param {Object} [config] Configuration options
506 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
507 */
508 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
509 // Configuration initialization
510 config = config || {};
511
512 // Properties
513 this.pending = 0;
514 this.$pending = null;
515
516 // Initialisation
517 this.setPendingElement( config.$pending || this.$element );
518 };
519
520 /* Setup */
521
522 OO.initClass( OO.ui.mixin.PendingElement );
523
524 /* Methods */
525
526 /**
527 * Set the pending element (and clean up any existing one).
528 *
529 * @param {jQuery} $pending The element to set to pending.
530 */
531 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
532 if ( this.$pending ) {
533 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
534 }
535
536 this.$pending = $pending;
537 if ( this.pending > 0 ) {
538 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
539 }
540 };
541
542 /**
543 * Check if an element is pending.
544 *
545 * @return {boolean} Element is pending
546 */
547 OO.ui.mixin.PendingElement.prototype.isPending = function () {
548 return !!this.pending;
549 };
550
551 /**
552 * Increase the pending counter. The pending state will remain active until the counter is zero
553 * (i.e., the number of calls to #pushPending and #popPending is the same).
554 *
555 * @chainable
556 */
557 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
558 if ( this.pending === 0 ) {
559 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
560 this.updateThemeClasses();
561 }
562 this.pending++;
563
564 return this;
565 };
566
567 /**
568 * Decrease the pending counter. The pending state will remain active until the counter is zero
569 * (i.e., the number of calls to #pushPending and #popPending is the same).
570 *
571 * @chainable
572 */
573 OO.ui.mixin.PendingElement.prototype.popPending = function () {
574 if ( this.pending === 1 ) {
575 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
576 this.updateThemeClasses();
577 }
578 this.pending = Math.max( 0, this.pending - 1 );
579
580 return this;
581 };
582
583 /**
584 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
585 * Actions can be made available for specific contexts (modes) and circumstances
586 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
587 *
588 * ActionSets contain two types of actions:
589 *
590 * - 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.
591 * - Other: Other actions include all non-special visible actions.
592 *
593 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
594 *
595 * @example
596 * // Example: An action set used in a process dialog
597 * function MyProcessDialog( config ) {
598 * MyProcessDialog.parent.call( this, config );
599 * }
600 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
601 * MyProcessDialog.static.title = 'An action set in a process dialog';
602 * // An action set that uses modes ('edit' and 'help' mode, in this example).
603 * MyProcessDialog.static.actions = [
604 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
605 * { action: 'help', modes: 'edit', label: 'Help' },
606 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
607 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
608 * ];
609 *
610 * MyProcessDialog.prototype.initialize = function () {
611 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
612 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
613 * 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>' );
614 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
615 * 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>' );
616 * this.stackLayout = new OO.ui.StackLayout( {
617 * items: [ this.panel1, this.panel2 ]
618 * } );
619 * this.$body.append( this.stackLayout.$element );
620 * };
621 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
622 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
623 * .next( function () {
624 * this.actions.setMode( 'edit' );
625 * }, this );
626 * };
627 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
628 * if ( action === 'help' ) {
629 * this.actions.setMode( 'help' );
630 * this.stackLayout.setItem( this.panel2 );
631 * } else if ( action === 'back' ) {
632 * this.actions.setMode( 'edit' );
633 * this.stackLayout.setItem( this.panel1 );
634 * } else if ( action === 'continue' ) {
635 * var dialog = this;
636 * return new OO.ui.Process( function () {
637 * dialog.close();
638 * } );
639 * }
640 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
641 * };
642 * MyProcessDialog.prototype.getBodyHeight = function () {
643 * return this.panel1.$element.outerHeight( true );
644 * };
645 * var windowManager = new OO.ui.WindowManager();
646 * $( 'body' ).append( windowManager.$element );
647 * var dialog = new MyProcessDialog( {
648 * size: 'medium'
649 * } );
650 * windowManager.addWindows( [ dialog ] );
651 * windowManager.openWindow( dialog );
652 *
653 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
654 *
655 * @abstract
656 * @class
657 * @mixins OO.EventEmitter
658 *
659 * @constructor
660 * @param {Object} [config] Configuration options
661 */
662 OO.ui.ActionSet = function OoUiActionSet( config ) {
663 // Configuration initialization
664 config = config || {};
665
666 // Mixin constructors
667 OO.EventEmitter.call( this );
668
669 // Properties
670 this.list = [];
671 this.categories = {
672 actions: 'getAction',
673 flags: 'getFlags',
674 modes: 'getModes'
675 };
676 this.categorized = {};
677 this.special = {};
678 this.others = [];
679 this.organized = false;
680 this.changing = false;
681 this.changed = false;
682 };
683
684 /* Setup */
685
686 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
687
688 /* Static Properties */
689
690 /**
691 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
692 * header of a {@link OO.ui.ProcessDialog process dialog}.
693 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
694 *
695 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
696 *
697 * @abstract
698 * @static
699 * @inheritable
700 * @property {string}
701 */
702 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
703
704 /* Events */
705
706 /**
707 * @event click
708 *
709 * A 'click' event is emitted when an action is clicked.
710 *
711 * @param {OO.ui.ActionWidget} action Action that was clicked
712 */
713
714 /**
715 * @event resize
716 *
717 * A 'resize' event is emitted when an action widget is resized.
718 *
719 * @param {OO.ui.ActionWidget} action Action that was resized
720 */
721
722 /**
723 * @event add
724 *
725 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
726 *
727 * @param {OO.ui.ActionWidget[]} added Actions added
728 */
729
730 /**
731 * @event remove
732 *
733 * A 'remove' event is emitted when actions are {@link #method-remove removed}
734 * or {@link #clear cleared}.
735 *
736 * @param {OO.ui.ActionWidget[]} added Actions removed
737 */
738
739 /**
740 * @event change
741 *
742 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
743 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
744 *
745 */
746
747 /* Methods */
748
749 /**
750 * Handle action change events.
751 *
752 * @private
753 * @fires change
754 */
755 OO.ui.ActionSet.prototype.onActionChange = function () {
756 this.organized = false;
757 if ( this.changing ) {
758 this.changed = true;
759 } else {
760 this.emit( 'change' );
761 }
762 };
763
764 /**
765 * Check if an action is one of the special actions.
766 *
767 * @param {OO.ui.ActionWidget} action Action to check
768 * @return {boolean} Action is special
769 */
770 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
771 var flag;
772
773 for ( flag in this.special ) {
774 if ( action === this.special[ flag ] ) {
775 return true;
776 }
777 }
778
779 return false;
780 };
781
782 /**
783 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
784 * or ‘disabled’.
785 *
786 * @param {Object} [filters] Filters to use, omit to get all actions
787 * @param {string|string[]} [filters.actions] Actions that action widgets must have
788 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
789 * @param {string|string[]} [filters.modes] Modes that action widgets must have
790 * @param {boolean} [filters.visible] Action widgets must be visible
791 * @param {boolean} [filters.disabled] Action widgets must be disabled
792 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
793 */
794 OO.ui.ActionSet.prototype.get = function ( filters ) {
795 var i, len, list, category, actions, index, match, matches;
796
797 if ( filters ) {
798 this.organize();
799
800 // Collect category candidates
801 matches = [];
802 for ( category in this.categorized ) {
803 list = filters[ category ];
804 if ( list ) {
805 if ( !Array.isArray( list ) ) {
806 list = [ list ];
807 }
808 for ( i = 0, len = list.length; i < len; i++ ) {
809 actions = this.categorized[ category ][ list[ i ] ];
810 if ( Array.isArray( actions ) ) {
811 matches.push.apply( matches, actions );
812 }
813 }
814 }
815 }
816 // Remove by boolean filters
817 for ( i = 0, len = matches.length; i < len; i++ ) {
818 match = matches[ i ];
819 if (
820 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
821 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
822 ) {
823 matches.splice( i, 1 );
824 len--;
825 i--;
826 }
827 }
828 // Remove duplicates
829 for ( i = 0, len = matches.length; i < len; i++ ) {
830 match = matches[ i ];
831 index = matches.lastIndexOf( match );
832 while ( index !== i ) {
833 matches.splice( index, 1 );
834 len--;
835 index = matches.lastIndexOf( match );
836 }
837 }
838 return matches;
839 }
840 return this.list.slice();
841 };
842
843 /**
844 * Get 'special' actions.
845 *
846 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
847 * Special flags can be configured in subclasses by changing the static #specialFlags property.
848 *
849 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
850 */
851 OO.ui.ActionSet.prototype.getSpecial = function () {
852 this.organize();
853 return $.extend( {}, this.special );
854 };
855
856 /**
857 * Get 'other' actions.
858 *
859 * Other actions include all non-special visible action widgets.
860 *
861 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
862 */
863 OO.ui.ActionSet.prototype.getOthers = function () {
864 this.organize();
865 return this.others.slice();
866 };
867
868 /**
869 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
870 * to be available in the specified mode will be made visible. All other actions will be hidden.
871 *
872 * @param {string} mode The mode. Only actions configured to be available in the specified
873 * mode will be made visible.
874 * @chainable
875 * @fires toggle
876 * @fires change
877 */
878 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
879 var i, len, action;
880
881 this.changing = true;
882 for ( i = 0, len = this.list.length; i < len; i++ ) {
883 action = this.list[ i ];
884 action.toggle( action.hasMode( mode ) );
885 }
886
887 this.organized = false;
888 this.changing = false;
889 this.emit( 'change' );
890
891 return this;
892 };
893
894 /**
895 * Set the abilities of the specified actions.
896 *
897 * Action widgets that are configured with the specified actions will be enabled
898 * or disabled based on the boolean values specified in the `actions`
899 * parameter.
900 *
901 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
902 * values that indicate whether or not the action should be enabled.
903 * @chainable
904 */
905 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
906 var i, len, action, item;
907
908 for ( i = 0, len = this.list.length; i < len; i++ ) {
909 item = this.list[ i ];
910 action = item.getAction();
911 if ( actions[ action ] !== undefined ) {
912 item.setDisabled( !actions[ action ] );
913 }
914 }
915
916 return this;
917 };
918
919 /**
920 * Executes a function once per action.
921 *
922 * When making changes to multiple actions, use this method instead of iterating over the actions
923 * manually to defer emitting a #change event until after all actions have been changed.
924 *
925 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
926 * @param {Function} callback Callback to run for each action; callback is invoked with three
927 * arguments: the action, the action's index, the list of actions being iterated over
928 * @chainable
929 */
930 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
931 this.changed = false;
932 this.changing = true;
933 this.get( filter ).forEach( callback );
934 this.changing = false;
935 if ( this.changed ) {
936 this.emit( 'change' );
937 }
938
939 return this;
940 };
941
942 /**
943 * Add action widgets to the action set.
944 *
945 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
946 * @chainable
947 * @fires add
948 * @fires change
949 */
950 OO.ui.ActionSet.prototype.add = function ( actions ) {
951 var i, len, action;
952
953 this.changing = true;
954 for ( i = 0, len = actions.length; i < len; i++ ) {
955 action = actions[ i ];
956 action.connect( this, {
957 click: [ 'emit', 'click', action ],
958 resize: [ 'emit', 'resize', action ],
959 toggle: [ 'onActionChange' ]
960 } );
961 this.list.push( action );
962 }
963 this.organized = false;
964 this.emit( 'add', actions );
965 this.changing = false;
966 this.emit( 'change' );
967
968 return this;
969 };
970
971 /**
972 * Remove action widgets from the set.
973 *
974 * To remove all actions, you may wish to use the #clear method instead.
975 *
976 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
977 * @chainable
978 * @fires remove
979 * @fires change
980 */
981 OO.ui.ActionSet.prototype.remove = function ( actions ) {
982 var i, len, index, action;
983
984 this.changing = true;
985 for ( i = 0, len = actions.length; i < len; i++ ) {
986 action = actions[ i ];
987 index = this.list.indexOf( action );
988 if ( index !== -1 ) {
989 action.disconnect( this );
990 this.list.splice( index, 1 );
991 }
992 }
993 this.organized = false;
994 this.emit( 'remove', actions );
995 this.changing = false;
996 this.emit( 'change' );
997
998 return this;
999 };
1000
1001 /**
1002 * Remove all action widets from the set.
1003 *
1004 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1005 *
1006 * @chainable
1007 * @fires remove
1008 * @fires change
1009 */
1010 OO.ui.ActionSet.prototype.clear = function () {
1011 var i, len, action,
1012 removed = this.list.slice();
1013
1014 this.changing = true;
1015 for ( i = 0, len = this.list.length; i < len; i++ ) {
1016 action = this.list[ i ];
1017 action.disconnect( this );
1018 }
1019
1020 this.list = [];
1021
1022 this.organized = false;
1023 this.emit( 'remove', removed );
1024 this.changing = false;
1025 this.emit( 'change' );
1026
1027 return this;
1028 };
1029
1030 /**
1031 * Organize actions.
1032 *
1033 * This is called whenever organized information is requested. It will only reorganize the actions
1034 * if something has changed since the last time it ran.
1035 *
1036 * @private
1037 * @chainable
1038 */
1039 OO.ui.ActionSet.prototype.organize = function () {
1040 var i, iLen, j, jLen, flag, action, category, list, item, special,
1041 specialFlags = this.constructor.static.specialFlags;
1042
1043 if ( !this.organized ) {
1044 this.categorized = {};
1045 this.special = {};
1046 this.others = [];
1047 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1048 action = this.list[ i ];
1049 if ( action.isVisible() ) {
1050 // Populate categories
1051 for ( category in this.categories ) {
1052 if ( !this.categorized[ category ] ) {
1053 this.categorized[ category ] = {};
1054 }
1055 list = action[ this.categories[ category ] ]();
1056 if ( !Array.isArray( list ) ) {
1057 list = [ list ];
1058 }
1059 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1060 item = list[ j ];
1061 if ( !this.categorized[ category ][ item ] ) {
1062 this.categorized[ category ][ item ] = [];
1063 }
1064 this.categorized[ category ][ item ].push( action );
1065 }
1066 }
1067 // Populate special/others
1068 special = false;
1069 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1070 flag = specialFlags[ j ];
1071 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1072 this.special[ flag ] = action;
1073 special = true;
1074 break;
1075 }
1076 }
1077 if ( !special ) {
1078 this.others.push( action );
1079 }
1080 }
1081 }
1082 this.organized = true;
1083 }
1084
1085 return this;
1086 };
1087
1088 /**
1089 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1090 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1091 * connected to them and can't be interacted with.
1092 *
1093 * @abstract
1094 * @class
1095 *
1096 * @constructor
1097 * @param {Object} [config] Configuration options
1098 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1099 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1100 * for an example.
1101 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1102 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1103 * @cfg {string} [text] Text to insert
1104 * @cfg {Array} [content] An array of content elements to append (after #text).
1105 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1106 * Instances of OO.ui.Element will have their $element appended.
1107 * @cfg {jQuery} [$content] Content elements to append (after #text).
1108 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
1109 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1110 * Data can also be specified with the #setData method.
1111 */
1112 OO.ui.Element = function OoUiElement( config ) {
1113 // Configuration initialization
1114 config = config || {};
1115
1116 // Properties
1117 this.$ = $;
1118 this.visible = true;
1119 this.data = config.data;
1120 this.$element = config.$element ||
1121 $( document.createElement( this.getTagName() ) );
1122 this.elementGroup = null;
1123 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1124
1125 // Initialization
1126 if ( Array.isArray( config.classes ) ) {
1127 this.$element.addClass( config.classes.join( ' ' ) );
1128 }
1129 if ( config.id ) {
1130 this.$element.attr( 'id', config.id );
1131 }
1132 if ( config.text ) {
1133 this.$element.text( config.text );
1134 }
1135 if ( config.content ) {
1136 // The `content` property treats plain strings as text; use an
1137 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1138 // appropriate $element appended.
1139 this.$element.append( config.content.map( function ( v ) {
1140 if ( typeof v === 'string' ) {
1141 // Escape string so it is properly represented in HTML.
1142 return document.createTextNode( v );
1143 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1144 // Bypass escaping.
1145 return v.toString();
1146 } else if ( v instanceof OO.ui.Element ) {
1147 return v.$element;
1148 }
1149 return v;
1150 } ) );
1151 }
1152 if ( config.$content ) {
1153 // The `$content` property treats plain strings as HTML.
1154 this.$element.append( config.$content );
1155 }
1156 };
1157
1158 /* Setup */
1159
1160 OO.initClass( OO.ui.Element );
1161
1162 /* Static Properties */
1163
1164 /**
1165 * The name of the HTML tag used by the element.
1166 *
1167 * The static value may be ignored if the #getTagName method is overridden.
1168 *
1169 * @static
1170 * @inheritable
1171 * @property {string}
1172 */
1173 OO.ui.Element.static.tagName = 'div';
1174
1175 /* Static Methods */
1176
1177 /**
1178 * Reconstitute a JavaScript object corresponding to a widget created
1179 * by the PHP implementation.
1180 *
1181 * @param {string|HTMLElement|jQuery} idOrNode
1182 * A DOM id (if a string) or node for the widget to infuse.
1183 * @return {OO.ui.Element}
1184 * The `OO.ui.Element` corresponding to this (infusable) document node.
1185 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1186 * the value returned is a newly-created Element wrapping around the existing
1187 * DOM node.
1188 */
1189 OO.ui.Element.static.infuse = function ( idOrNode ) {
1190 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1191 // Verify that the type matches up.
1192 // FIXME: uncomment after T89721 is fixed (see T90929)
1193 /*
1194 if ( !( obj instanceof this['class'] ) ) {
1195 throw new Error( 'Infusion type mismatch!' );
1196 }
1197 */
1198 return obj;
1199 };
1200
1201 /**
1202 * Implementation helper for `infuse`; skips the type check and has an
1203 * extra property so that only the top-level invocation touches the DOM.
1204 * @private
1205 * @param {string|HTMLElement|jQuery} idOrNode
1206 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1207 * when the top-level widget of this infusion is inserted into DOM,
1208 * replacing the original node; or false for top-level invocation.
1209 * @return {OO.ui.Element}
1210 */
1211 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1212 // look for a cached result of a previous infusion.
1213 var id, $elem, data, cls, parts, parent, obj, top, state;
1214 if ( typeof idOrNode === 'string' ) {
1215 id = idOrNode;
1216 $elem = $( document.getElementById( id ) );
1217 } else {
1218 $elem = $( idOrNode );
1219 id = $elem.attr( 'id' );
1220 }
1221 if ( !$elem.length ) {
1222 throw new Error( 'Widget not found: ' + id );
1223 }
1224 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1225 if ( data ) {
1226 // cached!
1227 if ( data === true ) {
1228 throw new Error( 'Circular dependency! ' + id );
1229 }
1230 return data;
1231 }
1232 data = $elem.attr( 'data-ooui' );
1233 if ( !data ) {
1234 throw new Error( 'No infusion data found: ' + id );
1235 }
1236 try {
1237 data = $.parseJSON( data );
1238 } catch ( _ ) {
1239 data = null;
1240 }
1241 if ( !( data && data._ ) ) {
1242 throw new Error( 'No valid infusion data found: ' + id );
1243 }
1244 if ( data._ === 'Tag' ) {
1245 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1246 return new OO.ui.Element( { $element: $elem } );
1247 }
1248 parts = data._.split( '.' );
1249 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1250 if ( cls === undefined ) {
1251 // The PHP output might be old and not including the "OO.ui" prefix
1252 // TODO: Remove this back-compat after next major release
1253 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1254 if ( cls === undefined ) {
1255 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1256 }
1257 }
1258
1259 // Verify that we're creating an OO.ui.Element instance
1260 parent = cls.parent;
1261
1262 while ( parent !== undefined ) {
1263 if ( parent === OO.ui.Element ) {
1264 // Safe
1265 break;
1266 }
1267
1268 parent = parent.parent;
1269 }
1270
1271 if ( parent !== OO.ui.Element ) {
1272 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1273 }
1274
1275 if ( domPromise === false ) {
1276 top = $.Deferred();
1277 domPromise = top.promise();
1278 }
1279 $elem.data( 'ooui-infused', true ); // prevent loops
1280 data.id = id; // implicit
1281 data = OO.copy( data, null, function deserialize( value ) {
1282 if ( OO.isPlainObject( value ) ) {
1283 if ( value.tag ) {
1284 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1285 }
1286 if ( value.html ) {
1287 return new OO.ui.HtmlSnippet( value.html );
1288 }
1289 }
1290 } );
1291 // allow widgets to reuse parts of the DOM
1292 data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data );
1293 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1294 state = cls.static.gatherPreInfuseState( $elem[ 0 ], data );
1295 // rebuild widget
1296 // jscs:disable requireCapitalizedConstructors
1297 obj = new cls( data );
1298 // jscs:enable requireCapitalizedConstructors
1299 // now replace old DOM with this new DOM.
1300 if ( top ) {
1301 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
1302 // so only mutate the DOM if we need to.
1303 if ( $elem[ 0 ] !== obj.$element[ 0 ] ) {
1304 $elem.replaceWith( obj.$element );
1305 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1306 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1307 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1308 $elem[ 0 ].oouiInfused = obj;
1309 }
1310 top.resolve();
1311 }
1312 obj.$element.data( 'ooui-infused', obj );
1313 // set the 'data-ooui' attribute so we can identify infused widgets
1314 obj.$element.attr( 'data-ooui', '' );
1315 // restore dynamic state after the new element is inserted into DOM
1316 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1317 return obj;
1318 };
1319
1320 /**
1321 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
1322 *
1323 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
1324 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
1325 * constructor, which will be given the enhanced config.
1326 *
1327 * @protected
1328 * @param {HTMLElement} node
1329 * @param {Object} config
1330 * @return {Object}
1331 */
1332 OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) {
1333 return config;
1334 };
1335
1336 /**
1337 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1338 * (and its children) that represent an Element of the same class and the given configuration,
1339 * generated by the PHP implementation.
1340 *
1341 * This method is called just before `node` is detached from the DOM. The return value of this
1342 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
1343 * is inserted into DOM to replace `node`.
1344 *
1345 * @protected
1346 * @param {HTMLElement} node
1347 * @param {Object} config
1348 * @return {Object}
1349 */
1350 OO.ui.Element.static.gatherPreInfuseState = function () {
1351 return {};
1352 };
1353
1354 /**
1355 * Get a jQuery function within a specific document.
1356 *
1357 * @static
1358 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1359 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1360 * not in an iframe
1361 * @return {Function} Bound jQuery function
1362 */
1363 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1364 function wrapper( selector ) {
1365 return $( selector, wrapper.context );
1366 }
1367
1368 wrapper.context = this.getDocument( context );
1369
1370 if ( $iframe ) {
1371 wrapper.$iframe = $iframe;
1372 }
1373
1374 return wrapper;
1375 };
1376
1377 /**
1378 * Get the document of an element.
1379 *
1380 * @static
1381 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1382 * @return {HTMLDocument|null} Document object
1383 */
1384 OO.ui.Element.static.getDocument = function ( obj ) {
1385 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1386 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1387 // Empty jQuery selections might have a context
1388 obj.context ||
1389 // HTMLElement
1390 obj.ownerDocument ||
1391 // Window
1392 obj.document ||
1393 // HTMLDocument
1394 ( obj.nodeType === 9 && obj ) ||
1395 null;
1396 };
1397
1398 /**
1399 * Get the window of an element or document.
1400 *
1401 * @static
1402 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1403 * @return {Window} Window object
1404 */
1405 OO.ui.Element.static.getWindow = function ( obj ) {
1406 var doc = this.getDocument( obj );
1407 // Support: IE 8
1408 // Standard Document.defaultView is IE9+
1409 return doc.parentWindow || doc.defaultView;
1410 };
1411
1412 /**
1413 * Get the direction of an element or document.
1414 *
1415 * @static
1416 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1417 * @return {string} Text direction, either 'ltr' or 'rtl'
1418 */
1419 OO.ui.Element.static.getDir = function ( obj ) {
1420 var isDoc, isWin;
1421
1422 if ( obj instanceof jQuery ) {
1423 obj = obj[ 0 ];
1424 }
1425 isDoc = obj.nodeType === 9;
1426 isWin = obj.document !== undefined;
1427 if ( isDoc || isWin ) {
1428 if ( isWin ) {
1429 obj = obj.document;
1430 }
1431 obj = obj.body;
1432 }
1433 return $( obj ).css( 'direction' );
1434 };
1435
1436 /**
1437 * Get the offset between two frames.
1438 *
1439 * TODO: Make this function not use recursion.
1440 *
1441 * @static
1442 * @param {Window} from Window of the child frame
1443 * @param {Window} [to=window] Window of the parent frame
1444 * @param {Object} [offset] Offset to start with, used internally
1445 * @return {Object} Offset object, containing left and top properties
1446 */
1447 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1448 var i, len, frames, frame, rect;
1449
1450 if ( !to ) {
1451 to = window;
1452 }
1453 if ( !offset ) {
1454 offset = { top: 0, left: 0 };
1455 }
1456 if ( from.parent === from ) {
1457 return offset;
1458 }
1459
1460 // Get iframe element
1461 frames = from.parent.document.getElementsByTagName( 'iframe' );
1462 for ( i = 0, len = frames.length; i < len; i++ ) {
1463 if ( frames[ i ].contentWindow === from ) {
1464 frame = frames[ i ];
1465 break;
1466 }
1467 }
1468
1469 // Recursively accumulate offset values
1470 if ( frame ) {
1471 rect = frame.getBoundingClientRect();
1472 offset.left += rect.left;
1473 offset.top += rect.top;
1474 if ( from !== to ) {
1475 this.getFrameOffset( from.parent, offset );
1476 }
1477 }
1478 return offset;
1479 };
1480
1481 /**
1482 * Get the offset between two elements.
1483 *
1484 * The two elements may be in a different frame, but in that case the frame $element is in must
1485 * be contained in the frame $anchor is in.
1486 *
1487 * @static
1488 * @param {jQuery} $element Element whose position to get
1489 * @param {jQuery} $anchor Element to get $element's position relative to
1490 * @return {Object} Translated position coordinates, containing top and left properties
1491 */
1492 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1493 var iframe, iframePos,
1494 pos = $element.offset(),
1495 anchorPos = $anchor.offset(),
1496 elementDocument = this.getDocument( $element ),
1497 anchorDocument = this.getDocument( $anchor );
1498
1499 // If $element isn't in the same document as $anchor, traverse up
1500 while ( elementDocument !== anchorDocument ) {
1501 iframe = elementDocument.defaultView.frameElement;
1502 if ( !iframe ) {
1503 throw new Error( '$element frame is not contained in $anchor frame' );
1504 }
1505 iframePos = $( iframe ).offset();
1506 pos.left += iframePos.left;
1507 pos.top += iframePos.top;
1508 elementDocument = iframe.ownerDocument;
1509 }
1510 pos.left -= anchorPos.left;
1511 pos.top -= anchorPos.top;
1512 return pos;
1513 };
1514
1515 /**
1516 * Get element border sizes.
1517 *
1518 * @static
1519 * @param {HTMLElement} el Element to measure
1520 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1521 */
1522 OO.ui.Element.static.getBorders = function ( el ) {
1523 var doc = el.ownerDocument,
1524 // Support: IE 8
1525 // Standard Document.defaultView is IE9+
1526 win = doc.parentWindow || doc.defaultView,
1527 style = win && win.getComputedStyle ?
1528 win.getComputedStyle( el, null ) :
1529 // Support: IE 8
1530 // Standard getComputedStyle() is IE9+
1531 el.currentStyle,
1532 $el = $( el ),
1533 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1534 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1535 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1536 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1537
1538 return {
1539 top: top,
1540 left: left,
1541 bottom: bottom,
1542 right: right
1543 };
1544 };
1545
1546 /**
1547 * Get dimensions of an element or window.
1548 *
1549 * @static
1550 * @param {HTMLElement|Window} el Element to measure
1551 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1552 */
1553 OO.ui.Element.static.getDimensions = function ( el ) {
1554 var $el, $win,
1555 doc = el.ownerDocument || el.document,
1556 // Support: IE 8
1557 // Standard Document.defaultView is IE9+
1558 win = doc.parentWindow || doc.defaultView;
1559
1560 if ( win === el || el === doc.documentElement ) {
1561 $win = $( win );
1562 return {
1563 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1564 scroll: {
1565 top: $win.scrollTop(),
1566 left: $win.scrollLeft()
1567 },
1568 scrollbar: { right: 0, bottom: 0 },
1569 rect: {
1570 top: 0,
1571 left: 0,
1572 bottom: $win.innerHeight(),
1573 right: $win.innerWidth()
1574 }
1575 };
1576 } else {
1577 $el = $( el );
1578 return {
1579 borders: this.getBorders( el ),
1580 scroll: {
1581 top: $el.scrollTop(),
1582 left: $el.scrollLeft()
1583 },
1584 scrollbar: {
1585 right: $el.innerWidth() - el.clientWidth,
1586 bottom: $el.innerHeight() - el.clientHeight
1587 },
1588 rect: el.getBoundingClientRect()
1589 };
1590 }
1591 };
1592
1593 /**
1594 * Get scrollable object parent
1595 *
1596 * documentElement can't be used to get or set the scrollTop
1597 * property on Blink. Changing and testing its value lets us
1598 * use 'body' or 'documentElement' based on what is working.
1599 *
1600 * https://code.google.com/p/chromium/issues/detail?id=303131
1601 *
1602 * @static
1603 * @param {HTMLElement} el Element to find scrollable parent for
1604 * @return {HTMLElement} Scrollable parent
1605 */
1606 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1607 var scrollTop, body;
1608
1609 if ( OO.ui.scrollableElement === undefined ) {
1610 body = el.ownerDocument.body;
1611 scrollTop = body.scrollTop;
1612 body.scrollTop = 1;
1613
1614 if ( body.scrollTop === 1 ) {
1615 body.scrollTop = scrollTop;
1616 OO.ui.scrollableElement = 'body';
1617 } else {
1618 OO.ui.scrollableElement = 'documentElement';
1619 }
1620 }
1621
1622 return el.ownerDocument[ OO.ui.scrollableElement ];
1623 };
1624
1625 /**
1626 * Get closest scrollable container.
1627 *
1628 * Traverses up until either a scrollable element or the root is reached, in which case the window
1629 * will be returned.
1630 *
1631 * @static
1632 * @param {HTMLElement} el Element to find scrollable container for
1633 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1634 * @return {HTMLElement} Closest scrollable container
1635 */
1636 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1637 var i, val,
1638 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1639 props = [ 'overflow-x', 'overflow-y' ],
1640 $parent = $( el ).parent();
1641
1642 if ( dimension === 'x' || dimension === 'y' ) {
1643 props = [ 'overflow-' + dimension ];
1644 }
1645
1646 while ( $parent.length ) {
1647 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1648 return $parent[ 0 ];
1649 }
1650 i = props.length;
1651 while ( i-- ) {
1652 val = $parent.css( props[ i ] );
1653 if ( val === 'auto' || val === 'scroll' ) {
1654 return $parent[ 0 ];
1655 }
1656 }
1657 $parent = $parent.parent();
1658 }
1659 return this.getDocument( el ).body;
1660 };
1661
1662 /**
1663 * Scroll element into view.
1664 *
1665 * @static
1666 * @param {HTMLElement} el Element to scroll into view
1667 * @param {Object} [config] Configuration options
1668 * @param {string} [config.duration] jQuery animation duration value
1669 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1670 * to scroll in both directions
1671 * @param {Function} [config.complete] Function to call when scrolling completes
1672 */
1673 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1674 var rel, anim, callback, sc, $sc, eld, scd, $win;
1675
1676 // Configuration initialization
1677 config = config || {};
1678
1679 anim = {};
1680 callback = typeof config.complete === 'function' && config.complete;
1681 sc = this.getClosestScrollableContainer( el, config.direction );
1682 $sc = $( sc );
1683 eld = this.getDimensions( el );
1684 scd = this.getDimensions( sc );
1685 $win = $( this.getWindow( el ) );
1686
1687 // Compute the distances between the edges of el and the edges of the scroll viewport
1688 if ( $sc.is( 'html, body' ) ) {
1689 // If the scrollable container is the root, this is easy
1690 rel = {
1691 top: eld.rect.top,
1692 bottom: $win.innerHeight() - eld.rect.bottom,
1693 left: eld.rect.left,
1694 right: $win.innerWidth() - eld.rect.right
1695 };
1696 } else {
1697 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1698 rel = {
1699 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1700 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1701 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1702 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1703 };
1704 }
1705
1706 if ( !config.direction || config.direction === 'y' ) {
1707 if ( rel.top < 0 ) {
1708 anim.scrollTop = scd.scroll.top + rel.top;
1709 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1710 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1711 }
1712 }
1713 if ( !config.direction || config.direction === 'x' ) {
1714 if ( rel.left < 0 ) {
1715 anim.scrollLeft = scd.scroll.left + rel.left;
1716 } else if ( rel.left > 0 && rel.right < 0 ) {
1717 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1718 }
1719 }
1720 if ( !$.isEmptyObject( anim ) ) {
1721 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1722 if ( callback ) {
1723 $sc.queue( function ( next ) {
1724 callback();
1725 next();
1726 } );
1727 }
1728 } else {
1729 if ( callback ) {
1730 callback();
1731 }
1732 }
1733 };
1734
1735 /**
1736 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1737 * and reserve space for them, because it probably doesn't.
1738 *
1739 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1740 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1741 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1742 * and then reattach (or show) them back.
1743 *
1744 * @static
1745 * @param {HTMLElement} el Element to reconsider the scrollbars on
1746 */
1747 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1748 var i, len, scrollLeft, scrollTop, nodes = [];
1749 // Save scroll position
1750 scrollLeft = el.scrollLeft;
1751 scrollTop = el.scrollTop;
1752 // Detach all children
1753 while ( el.firstChild ) {
1754 nodes.push( el.firstChild );
1755 el.removeChild( el.firstChild );
1756 }
1757 // Force reflow
1758 void el.offsetHeight;
1759 // Reattach all children
1760 for ( i = 0, len = nodes.length; i < len; i++ ) {
1761 el.appendChild( nodes[ i ] );
1762 }
1763 // Restore scroll position (no-op if scrollbars disappeared)
1764 el.scrollLeft = scrollLeft;
1765 el.scrollTop = scrollTop;
1766 };
1767
1768 /* Methods */
1769
1770 /**
1771 * Toggle visibility of an element.
1772 *
1773 * @param {boolean} [show] Make element visible, omit to toggle visibility
1774 * @fires visible
1775 * @chainable
1776 */
1777 OO.ui.Element.prototype.toggle = function ( show ) {
1778 show = show === undefined ? !this.visible : !!show;
1779
1780 if ( show !== this.isVisible() ) {
1781 this.visible = show;
1782 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1783 this.emit( 'toggle', show );
1784 }
1785
1786 return this;
1787 };
1788
1789 /**
1790 * Check if element is visible.
1791 *
1792 * @return {boolean} element is visible
1793 */
1794 OO.ui.Element.prototype.isVisible = function () {
1795 return this.visible;
1796 };
1797
1798 /**
1799 * Get element data.
1800 *
1801 * @return {Mixed} Element data
1802 */
1803 OO.ui.Element.prototype.getData = function () {
1804 return this.data;
1805 };
1806
1807 /**
1808 * Set element data.
1809 *
1810 * @param {Mixed} Element data
1811 * @chainable
1812 */
1813 OO.ui.Element.prototype.setData = function ( data ) {
1814 this.data = data;
1815 return this;
1816 };
1817
1818 /**
1819 * Check if element supports one or more methods.
1820 *
1821 * @param {string|string[]} methods Method or list of methods to check
1822 * @return {boolean} All methods are supported
1823 */
1824 OO.ui.Element.prototype.supports = function ( methods ) {
1825 var i, len,
1826 support = 0;
1827
1828 methods = Array.isArray( methods ) ? methods : [ methods ];
1829 for ( i = 0, len = methods.length; i < len; i++ ) {
1830 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1831 support++;
1832 }
1833 }
1834
1835 return methods.length === support;
1836 };
1837
1838 /**
1839 * Update the theme-provided classes.
1840 *
1841 * @localdoc This is called in element mixins and widget classes any time state changes.
1842 * Updating is debounced, minimizing overhead of changing multiple attributes and
1843 * guaranteeing that theme updates do not occur within an element's constructor
1844 */
1845 OO.ui.Element.prototype.updateThemeClasses = function () {
1846 this.debouncedUpdateThemeClassesHandler();
1847 };
1848
1849 /**
1850 * @private
1851 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1852 * make them synchronous.
1853 */
1854 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1855 OO.ui.theme.updateElementClasses( this );
1856 };
1857
1858 /**
1859 * Get the HTML tag name.
1860 *
1861 * Override this method to base the result on instance information.
1862 *
1863 * @return {string} HTML tag name
1864 */
1865 OO.ui.Element.prototype.getTagName = function () {
1866 return this.constructor.static.tagName;
1867 };
1868
1869 /**
1870 * Check if the element is attached to the DOM
1871 * @return {boolean} The element is attached to the DOM
1872 */
1873 OO.ui.Element.prototype.isElementAttached = function () {
1874 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1875 };
1876
1877 /**
1878 * Get the DOM document.
1879 *
1880 * @return {HTMLDocument} Document object
1881 */
1882 OO.ui.Element.prototype.getElementDocument = function () {
1883 // Don't cache this in other ways either because subclasses could can change this.$element
1884 return OO.ui.Element.static.getDocument( this.$element );
1885 };
1886
1887 /**
1888 * Get the DOM window.
1889 *
1890 * @return {Window} Window object
1891 */
1892 OO.ui.Element.prototype.getElementWindow = function () {
1893 return OO.ui.Element.static.getWindow( this.$element );
1894 };
1895
1896 /**
1897 * Get closest scrollable container.
1898 */
1899 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1900 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1901 };
1902
1903 /**
1904 * Get group element is in.
1905 *
1906 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1907 */
1908 OO.ui.Element.prototype.getElementGroup = function () {
1909 return this.elementGroup;
1910 };
1911
1912 /**
1913 * Set group element is in.
1914 *
1915 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1916 * @chainable
1917 */
1918 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1919 this.elementGroup = group;
1920 return this;
1921 };
1922
1923 /**
1924 * Scroll element into view.
1925 *
1926 * @param {Object} [config] Configuration options
1927 */
1928 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1929 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1930 };
1931
1932 /**
1933 * Restore the pre-infusion dynamic state for this widget.
1934 *
1935 * This method is called after #$element has been inserted into DOM. The parameter is the return
1936 * value of #gatherPreInfuseState.
1937 *
1938 * @protected
1939 * @param {Object} state
1940 */
1941 OO.ui.Element.prototype.restorePreInfuseState = function () {
1942 };
1943
1944 /**
1945 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1946 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1947 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1948 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1949 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1950 *
1951 * @abstract
1952 * @class
1953 * @extends OO.ui.Element
1954 * @mixins OO.EventEmitter
1955 *
1956 * @constructor
1957 * @param {Object} [config] Configuration options
1958 */
1959 OO.ui.Layout = function OoUiLayout( config ) {
1960 // Configuration initialization
1961 config = config || {};
1962
1963 // Parent constructor
1964 OO.ui.Layout.parent.call( this, config );
1965
1966 // Mixin constructors
1967 OO.EventEmitter.call( this );
1968
1969 // Initialization
1970 this.$element.addClass( 'oo-ui-layout' );
1971 };
1972
1973 /* Setup */
1974
1975 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1976 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1977
1978 /**
1979 * Widgets are compositions of one or more OOjs UI elements that users can both view
1980 * and interact with. All widgets can be configured and modified via a standard API,
1981 * and their state can change dynamically according to a model.
1982 *
1983 * @abstract
1984 * @class
1985 * @extends OO.ui.Element
1986 * @mixins OO.EventEmitter
1987 *
1988 * @constructor
1989 * @param {Object} [config] Configuration options
1990 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1991 * appearance reflects this state.
1992 */
1993 OO.ui.Widget = function OoUiWidget( config ) {
1994 // Initialize config
1995 config = $.extend( { disabled: false }, config );
1996
1997 // Parent constructor
1998 OO.ui.Widget.parent.call( this, config );
1999
2000 // Mixin constructors
2001 OO.EventEmitter.call( this );
2002
2003 // Properties
2004 this.disabled = null;
2005 this.wasDisabled = null;
2006
2007 // Initialization
2008 this.$element.addClass( 'oo-ui-widget' );
2009 this.setDisabled( !!config.disabled );
2010 };
2011
2012 /* Setup */
2013
2014 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
2015 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
2016
2017 /* Static Properties */
2018
2019 /**
2020 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
2021 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2022 * handling.
2023 *
2024 * @static
2025 * @inheritable
2026 * @property {boolean}
2027 */
2028 OO.ui.Widget.static.supportsSimpleLabel = false;
2029
2030 /* Events */
2031
2032 /**
2033 * @event disable
2034 *
2035 * A 'disable' event is emitted when the disabled state of the widget changes
2036 * (i.e. on disable **and** enable).
2037 *
2038 * @param {boolean} disabled Widget is disabled
2039 */
2040
2041 /**
2042 * @event toggle
2043 *
2044 * A 'toggle' event is emitted when the visibility of the widget changes.
2045 *
2046 * @param {boolean} visible Widget is visible
2047 */
2048
2049 /* Methods */
2050
2051 /**
2052 * Check if the widget is disabled.
2053 *
2054 * @return {boolean} Widget is disabled
2055 */
2056 OO.ui.Widget.prototype.isDisabled = function () {
2057 return this.disabled;
2058 };
2059
2060 /**
2061 * Set the 'disabled' state of the widget.
2062 *
2063 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2064 *
2065 * @param {boolean} disabled Disable widget
2066 * @chainable
2067 */
2068 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
2069 var isDisabled;
2070
2071 this.disabled = !!disabled;
2072 isDisabled = this.isDisabled();
2073 if ( isDisabled !== this.wasDisabled ) {
2074 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2075 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2076 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2077 this.emit( 'disable', isDisabled );
2078 this.updateThemeClasses();
2079 }
2080 this.wasDisabled = isDisabled;
2081
2082 return this;
2083 };
2084
2085 /**
2086 * Update the disabled state, in case of changes in parent widget.
2087 *
2088 * @chainable
2089 */
2090 OO.ui.Widget.prototype.updateDisabled = function () {
2091 this.setDisabled( this.disabled );
2092 return this;
2093 };
2094
2095 /**
2096 * A window is a container for elements that are in a child frame. They are used with
2097 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2098 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2099 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2100 * the window manager will choose a sensible fallback.
2101 *
2102 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2103 * different processes are executed:
2104 *
2105 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2106 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2107 * the window.
2108 *
2109 * - {@link #getSetupProcess} method is called and its result executed
2110 * - {@link #getReadyProcess} method is called and its result executed
2111 *
2112 * **opened**: The window is now open
2113 *
2114 * **closing**: The closing stage begins when the window manager's
2115 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2116 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2117 *
2118 * - {@link #getHoldProcess} method is called and its result executed
2119 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2120 *
2121 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2122 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2123 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2124 * processing can complete. Always assume window processes are executed asynchronously.
2125 *
2126 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2127 *
2128 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2129 *
2130 * @abstract
2131 * @class
2132 * @extends OO.ui.Element
2133 * @mixins OO.EventEmitter
2134 *
2135 * @constructor
2136 * @param {Object} [config] Configuration options
2137 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2138 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2139 */
2140 OO.ui.Window = function OoUiWindow( config ) {
2141 // Configuration initialization
2142 config = config || {};
2143
2144 // Parent constructor
2145 OO.ui.Window.parent.call( this, config );
2146
2147 // Mixin constructors
2148 OO.EventEmitter.call( this );
2149
2150 // Properties
2151 this.manager = null;
2152 this.size = config.size || this.constructor.static.size;
2153 this.$frame = $( '<div>' );
2154 this.$overlay = $( '<div>' );
2155 this.$content = $( '<div>' );
2156
2157 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
2158 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
2159 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
2160
2161 // Initialization
2162 this.$overlay.addClass( 'oo-ui-window-overlay' );
2163 this.$content
2164 .addClass( 'oo-ui-window-content' )
2165 .attr( 'tabindex', 0 );
2166 this.$frame
2167 .addClass( 'oo-ui-window-frame' )
2168 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
2169
2170 this.$element
2171 .addClass( 'oo-ui-window' )
2172 .append( this.$frame, this.$overlay );
2173
2174 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2175 // that reference properties not initialized at that time of parent class construction
2176 // TODO: Find a better way to handle post-constructor setup
2177 this.visible = false;
2178 this.$element.addClass( 'oo-ui-element-hidden' );
2179 };
2180
2181 /* Setup */
2182
2183 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2184 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2185
2186 /* Static Properties */
2187
2188 /**
2189 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2190 *
2191 * The static size is used if no #size is configured during construction.
2192 *
2193 * @static
2194 * @inheritable
2195 * @property {string}
2196 */
2197 OO.ui.Window.static.size = 'medium';
2198
2199 /* Methods */
2200
2201 /**
2202 * Handle mouse down events.
2203 *
2204 * @private
2205 * @param {jQuery.Event} e Mouse down event
2206 */
2207 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2208 // Prevent clicking on the click-block from stealing focus
2209 if ( e.target === this.$element[ 0 ] ) {
2210 return false;
2211 }
2212 };
2213
2214 /**
2215 * Check if the window has been initialized.
2216 *
2217 * Initialization occurs when a window is added to a manager.
2218 *
2219 * @return {boolean} Window has been initialized
2220 */
2221 OO.ui.Window.prototype.isInitialized = function () {
2222 return !!this.manager;
2223 };
2224
2225 /**
2226 * Check if the window is visible.
2227 *
2228 * @return {boolean} Window is visible
2229 */
2230 OO.ui.Window.prototype.isVisible = function () {
2231 return this.visible;
2232 };
2233
2234 /**
2235 * Check if the window is opening.
2236 *
2237 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2238 * method.
2239 *
2240 * @return {boolean} Window is opening
2241 */
2242 OO.ui.Window.prototype.isOpening = function () {
2243 return this.manager.isOpening( this );
2244 };
2245
2246 /**
2247 * Check if the window is closing.
2248 *
2249 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2250 *
2251 * @return {boolean} Window is closing
2252 */
2253 OO.ui.Window.prototype.isClosing = function () {
2254 return this.manager.isClosing( this );
2255 };
2256
2257 /**
2258 * Check if the window is opened.
2259 *
2260 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2261 *
2262 * @return {boolean} Window is opened
2263 */
2264 OO.ui.Window.prototype.isOpened = function () {
2265 return this.manager.isOpened( this );
2266 };
2267
2268 /**
2269 * Get the window manager.
2270 *
2271 * All windows must be attached to a window manager, which is used to open
2272 * and close the window and control its presentation.
2273 *
2274 * @return {OO.ui.WindowManager} Manager of window
2275 */
2276 OO.ui.Window.prototype.getManager = function () {
2277 return this.manager;
2278 };
2279
2280 /**
2281 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2282 *
2283 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2284 */
2285 OO.ui.Window.prototype.getSize = function () {
2286 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2287 sizes = this.manager.constructor.static.sizes,
2288 size = this.size;
2289
2290 if ( !sizes[ size ] ) {
2291 size = this.manager.constructor.static.defaultSize;
2292 }
2293 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2294 size = 'full';
2295 }
2296
2297 return size;
2298 };
2299
2300 /**
2301 * Get the size properties associated with the current window size
2302 *
2303 * @return {Object} Size properties
2304 */
2305 OO.ui.Window.prototype.getSizeProperties = function () {
2306 return this.manager.constructor.static.sizes[ this.getSize() ];
2307 };
2308
2309 /**
2310 * Disable transitions on window's frame for the duration of the callback function, then enable them
2311 * back.
2312 *
2313 * @private
2314 * @param {Function} callback Function to call while transitions are disabled
2315 */
2316 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2317 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2318 // Disable transitions first, otherwise we'll get values from when the window was animating.
2319 var oldTransition,
2320 styleObj = this.$frame[ 0 ].style;
2321 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2322 styleObj.MozTransition || styleObj.WebkitTransition;
2323 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2324 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2325 callback();
2326 // Force reflow to make sure the style changes done inside callback really are not transitioned
2327 this.$frame.height();
2328 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2329 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2330 };
2331
2332 /**
2333 * Get the height of the full window contents (i.e., the window head, body and foot together).
2334 *
2335 * What consistitutes the head, body, and foot varies depending on the window type.
2336 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2337 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2338 * and special actions in the head, and dialog content in the body.
2339 *
2340 * To get just the height of the dialog body, use the #getBodyHeight method.
2341 *
2342 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2343 */
2344 OO.ui.Window.prototype.getContentHeight = function () {
2345 var bodyHeight,
2346 win = this,
2347 bodyStyleObj = this.$body[ 0 ].style,
2348 frameStyleObj = this.$frame[ 0 ].style;
2349
2350 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2351 // Disable transitions first, otherwise we'll get values from when the window was animating.
2352 this.withoutSizeTransitions( function () {
2353 var oldHeight = frameStyleObj.height,
2354 oldPosition = bodyStyleObj.position;
2355 frameStyleObj.height = '1px';
2356 // Force body to resize to new width
2357 bodyStyleObj.position = 'relative';
2358 bodyHeight = win.getBodyHeight();
2359 frameStyleObj.height = oldHeight;
2360 bodyStyleObj.position = oldPosition;
2361 } );
2362
2363 return (
2364 // Add buffer for border
2365 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2366 // Use combined heights of children
2367 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2368 );
2369 };
2370
2371 /**
2372 * Get the height of the window body.
2373 *
2374 * To get the height of the full window contents (the window body, head, and foot together),
2375 * use #getContentHeight.
2376 *
2377 * When this function is called, the window will temporarily have been resized
2378 * to height=1px, so .scrollHeight measurements can be taken accurately.
2379 *
2380 * @return {number} Height of the window body in pixels
2381 */
2382 OO.ui.Window.prototype.getBodyHeight = function () {
2383 return this.$body[ 0 ].scrollHeight;
2384 };
2385
2386 /**
2387 * Get the directionality of the frame (right-to-left or left-to-right).
2388 *
2389 * @return {string} Directionality: `'ltr'` or `'rtl'`
2390 */
2391 OO.ui.Window.prototype.getDir = function () {
2392 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2393 };
2394
2395 /**
2396 * Get the 'setup' process.
2397 *
2398 * The setup process is used to set up a window for use in a particular context,
2399 * based on the `data` argument. This method is called during the opening phase of the window’s
2400 * lifecycle.
2401 *
2402 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2403 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2404 * of OO.ui.Process.
2405 *
2406 * To add window content that persists between openings, you may wish to use the #initialize method
2407 * instead.
2408 *
2409 * @param {Object} [data] Window opening data
2410 * @return {OO.ui.Process} Setup process
2411 */
2412 OO.ui.Window.prototype.getSetupProcess = function () {
2413 return new OO.ui.Process();
2414 };
2415
2416 /**
2417 * Get the ‘ready’ process.
2418 *
2419 * The ready process is used to ready a window for use in a particular
2420 * context, based on the `data` argument. This method is called during the opening phase of
2421 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2422 *
2423 * Override this method to add additional steps to the ‘ready’ process the parent method
2424 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2425 * methods of OO.ui.Process.
2426 *
2427 * @param {Object} [data] Window opening data
2428 * @return {OO.ui.Process} Ready process
2429 */
2430 OO.ui.Window.prototype.getReadyProcess = function () {
2431 return new OO.ui.Process();
2432 };
2433
2434 /**
2435 * Get the 'hold' process.
2436 *
2437 * The hold proccess is used to keep a window from being used in a particular context,
2438 * based on the `data` argument. This method is called during the closing phase of the window’s
2439 * lifecycle.
2440 *
2441 * Override this method to add additional steps to the 'hold' process the parent method provides
2442 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2443 * of OO.ui.Process.
2444 *
2445 * @param {Object} [data] Window closing data
2446 * @return {OO.ui.Process} Hold process
2447 */
2448 OO.ui.Window.prototype.getHoldProcess = function () {
2449 return new OO.ui.Process();
2450 };
2451
2452 /**
2453 * Get the ‘teardown’ process.
2454 *
2455 * The teardown process is used to teardown a window after use. During teardown,
2456 * user interactions within the window are conveyed and the window is closed, based on the `data`
2457 * argument. This method is called during the closing phase of the window’s lifecycle.
2458 *
2459 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2460 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2461 * of OO.ui.Process.
2462 *
2463 * @param {Object} [data] Window closing data
2464 * @return {OO.ui.Process} Teardown process
2465 */
2466 OO.ui.Window.prototype.getTeardownProcess = function () {
2467 return new OO.ui.Process();
2468 };
2469
2470 /**
2471 * Set the window manager.
2472 *
2473 * This will cause the window to initialize. Calling it more than once will cause an error.
2474 *
2475 * @param {OO.ui.WindowManager} manager Manager for this window
2476 * @throws {Error} An error is thrown if the method is called more than once
2477 * @chainable
2478 */
2479 OO.ui.Window.prototype.setManager = function ( manager ) {
2480 if ( this.manager ) {
2481 throw new Error( 'Cannot set window manager, window already has a manager' );
2482 }
2483
2484 this.manager = manager;
2485 this.initialize();
2486
2487 return this;
2488 };
2489
2490 /**
2491 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2492 *
2493 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2494 * `full`
2495 * @chainable
2496 */
2497 OO.ui.Window.prototype.setSize = function ( size ) {
2498 this.size = size;
2499 this.updateSize();
2500 return this;
2501 };
2502
2503 /**
2504 * Update the window size.
2505 *
2506 * @throws {Error} An error is thrown if the window is not attached to a window manager
2507 * @chainable
2508 */
2509 OO.ui.Window.prototype.updateSize = function () {
2510 if ( !this.manager ) {
2511 throw new Error( 'Cannot update window size, must be attached to a manager' );
2512 }
2513
2514 this.manager.updateWindowSize( this );
2515
2516 return this;
2517 };
2518
2519 /**
2520 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2521 * when the window is opening. In general, setDimensions should not be called directly.
2522 *
2523 * To set the size of the window, use the #setSize method.
2524 *
2525 * @param {Object} dim CSS dimension properties
2526 * @param {string|number} [dim.width] Width
2527 * @param {string|number} [dim.minWidth] Minimum width
2528 * @param {string|number} [dim.maxWidth] Maximum width
2529 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2530 * @param {string|number} [dim.minWidth] Minimum height
2531 * @param {string|number} [dim.maxWidth] Maximum height
2532 * @chainable
2533 */
2534 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2535 var height,
2536 win = this,
2537 styleObj = this.$frame[ 0 ].style;
2538
2539 // Calculate the height we need to set using the correct width
2540 if ( dim.height === undefined ) {
2541 this.withoutSizeTransitions( function () {
2542 var oldWidth = styleObj.width;
2543 win.$frame.css( 'width', dim.width || '' );
2544 height = win.getContentHeight();
2545 styleObj.width = oldWidth;
2546 } );
2547 } else {
2548 height = dim.height;
2549 }
2550
2551 this.$frame.css( {
2552 width: dim.width || '',
2553 minWidth: dim.minWidth || '',
2554 maxWidth: dim.maxWidth || '',
2555 height: height || '',
2556 minHeight: dim.minHeight || '',
2557 maxHeight: dim.maxHeight || ''
2558 } );
2559
2560 return this;
2561 };
2562
2563 /**
2564 * Initialize window contents.
2565 *
2566 * Before the window is opened for the first time, #initialize is called so that content that
2567 * persists between openings can be added to the window.
2568 *
2569 * To set up a window with new content each time the window opens, use #getSetupProcess.
2570 *
2571 * @throws {Error} An error is thrown if the window is not attached to a window manager
2572 * @chainable
2573 */
2574 OO.ui.Window.prototype.initialize = function () {
2575 if ( !this.manager ) {
2576 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2577 }
2578
2579 // Properties
2580 this.$head = $( '<div>' );
2581 this.$body = $( '<div>' );
2582 this.$foot = $( '<div>' );
2583 this.$document = $( this.getElementDocument() );
2584
2585 // Events
2586 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2587
2588 // Initialization
2589 this.$head.addClass( 'oo-ui-window-head' );
2590 this.$body.addClass( 'oo-ui-window-body' );
2591 this.$foot.addClass( 'oo-ui-window-foot' );
2592 this.$content.append( this.$head, this.$body, this.$foot );
2593
2594 return this;
2595 };
2596
2597 /**
2598 * Called when someone tries to focus the hidden element at the end of the dialog.
2599 * Sends focus back to the start of the dialog.
2600 *
2601 * @param {jQuery.Event} event Focus event
2602 */
2603 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2604 if ( this.$focusTrapBefore.is( event.target ) ) {
2605 OO.ui.findFocusable( this.$content, true ).focus();
2606 } else {
2607 // this.$content is the part of the focus cycle, and is the first focusable element
2608 this.$content.focus();
2609 }
2610 };
2611
2612 /**
2613 * Open the window.
2614 *
2615 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2616 * method, which returns a promise resolved when the window is done opening.
2617 *
2618 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2619 *
2620 * @param {Object} [data] Window opening data
2621 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2622 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2623 * value is a new promise, which is resolved when the window begins closing.
2624 * @throws {Error} An error is thrown if the window is not attached to a window manager
2625 */
2626 OO.ui.Window.prototype.open = function ( data ) {
2627 if ( !this.manager ) {
2628 throw new Error( 'Cannot open window, must be attached to a manager' );
2629 }
2630
2631 return this.manager.openWindow( this, data );
2632 };
2633
2634 /**
2635 * Close the window.
2636 *
2637 * This method is a wrapper around a call to the window
2638 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2639 * which returns a closing promise resolved when the window is done closing.
2640 *
2641 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2642 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2643 * the window closes.
2644 *
2645 * @param {Object} [data] Window closing data
2646 * @return {jQuery.Promise} Promise resolved when window is closed
2647 * @throws {Error} An error is thrown if the window is not attached to a window manager
2648 */
2649 OO.ui.Window.prototype.close = function ( data ) {
2650 if ( !this.manager ) {
2651 throw new Error( 'Cannot close window, must be attached to a manager' );
2652 }
2653
2654 return this.manager.closeWindow( this, data );
2655 };
2656
2657 /**
2658 * Setup window.
2659 *
2660 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2661 * by other systems.
2662 *
2663 * @param {Object} [data] Window opening data
2664 * @return {jQuery.Promise} Promise resolved when window is setup
2665 */
2666 OO.ui.Window.prototype.setup = function ( data ) {
2667 var win = this;
2668
2669 this.toggle( true );
2670
2671 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2672 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2673
2674 return this.getSetupProcess( data ).execute().then( function () {
2675 // Force redraw by asking the browser to measure the elements' widths
2676 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2677 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2678 } );
2679 };
2680
2681 /**
2682 * Ready window.
2683 *
2684 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2685 * by other systems.
2686 *
2687 * @param {Object} [data] Window opening data
2688 * @return {jQuery.Promise} Promise resolved when window is ready
2689 */
2690 OO.ui.Window.prototype.ready = function ( data ) {
2691 var win = this;
2692
2693 this.$content.focus();
2694 return this.getReadyProcess( data ).execute().then( function () {
2695 // Force redraw by asking the browser to measure the elements' widths
2696 win.$element.addClass( 'oo-ui-window-ready' ).width();
2697 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2698 } );
2699 };
2700
2701 /**
2702 * Hold window.
2703 *
2704 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2705 * by other systems.
2706 *
2707 * @param {Object} [data] Window closing data
2708 * @return {jQuery.Promise} Promise resolved when window is held
2709 */
2710 OO.ui.Window.prototype.hold = function ( data ) {
2711 var win = this;
2712
2713 return this.getHoldProcess( data ).execute().then( function () {
2714 // Get the focused element within the window's content
2715 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2716
2717 // Blur the focused element
2718 if ( $focus.length ) {
2719 $focus[ 0 ].blur();
2720 }
2721
2722 // Force redraw by asking the browser to measure the elements' widths
2723 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2724 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2725 } );
2726 };
2727
2728 /**
2729 * Teardown window.
2730 *
2731 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2732 * by other systems.
2733 *
2734 * @param {Object} [data] Window closing data
2735 * @return {jQuery.Promise} Promise resolved when window is torn down
2736 */
2737 OO.ui.Window.prototype.teardown = function ( data ) {
2738 var win = this;
2739
2740 return this.getTeardownProcess( data ).execute().then( function () {
2741 // Force redraw by asking the browser to measure the elements' widths
2742 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2743 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2744 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2745 win.toggle( false );
2746 } );
2747 };
2748
2749 /**
2750 * The Dialog class serves as the base class for the other types of dialogs.
2751 * Unless extended to include controls, the rendered dialog box is a simple window
2752 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2753 * which opens, closes, and controls the presentation of the window. See the
2754 * [OOjs UI documentation on MediaWiki] [1] for more information.
2755 *
2756 * @example
2757 * // A simple dialog window.
2758 * function MyDialog( config ) {
2759 * MyDialog.parent.call( this, config );
2760 * }
2761 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2762 * MyDialog.prototype.initialize = function () {
2763 * MyDialog.parent.prototype.initialize.call( this );
2764 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2765 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2766 * this.$body.append( this.content.$element );
2767 * };
2768 * MyDialog.prototype.getBodyHeight = function () {
2769 * return this.content.$element.outerHeight( true );
2770 * };
2771 * var myDialog = new MyDialog( {
2772 * size: 'medium'
2773 * } );
2774 * // Create and append a window manager, which opens and closes the window.
2775 * var windowManager = new OO.ui.WindowManager();
2776 * $( 'body' ).append( windowManager.$element );
2777 * windowManager.addWindows( [ myDialog ] );
2778 * // Open the window!
2779 * windowManager.openWindow( myDialog );
2780 *
2781 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2782 *
2783 * @abstract
2784 * @class
2785 * @extends OO.ui.Window
2786 * @mixins OO.ui.mixin.PendingElement
2787 *
2788 * @constructor
2789 * @param {Object} [config] Configuration options
2790 */
2791 OO.ui.Dialog = function OoUiDialog( config ) {
2792 // Parent constructor
2793 OO.ui.Dialog.parent.call( this, config );
2794
2795 // Mixin constructors
2796 OO.ui.mixin.PendingElement.call( this );
2797
2798 // Properties
2799 this.actions = new OO.ui.ActionSet();
2800 this.attachedActions = [];
2801 this.currentAction = null;
2802 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2803
2804 // Events
2805 this.actions.connect( this, {
2806 click: 'onActionClick',
2807 resize: 'onActionResize',
2808 change: 'onActionsChange'
2809 } );
2810
2811 // Initialization
2812 this.$element
2813 .addClass( 'oo-ui-dialog' )
2814 .attr( 'role', 'dialog' );
2815 };
2816
2817 /* Setup */
2818
2819 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2820 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2821
2822 /* Static Properties */
2823
2824 /**
2825 * Symbolic name of dialog.
2826 *
2827 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2828 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2829 *
2830 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2831 *
2832 * @abstract
2833 * @static
2834 * @inheritable
2835 * @property {string}
2836 */
2837 OO.ui.Dialog.static.name = '';
2838
2839 /**
2840 * The dialog title.
2841 *
2842 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2843 * that will produce a Label node or string. The title can also be specified with data passed to the
2844 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2845 *
2846 * @abstract
2847 * @static
2848 * @inheritable
2849 * @property {jQuery|string|Function}
2850 */
2851 OO.ui.Dialog.static.title = '';
2852
2853 /**
2854 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2855 *
2856 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2857 * value will be overriden.
2858 *
2859 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2860 *
2861 * @static
2862 * @inheritable
2863 * @property {Object[]}
2864 */
2865 OO.ui.Dialog.static.actions = [];
2866
2867 /**
2868 * Close the dialog when the 'Esc' key is pressed.
2869 *
2870 * @static
2871 * @abstract
2872 * @inheritable
2873 * @property {boolean}
2874 */
2875 OO.ui.Dialog.static.escapable = true;
2876
2877 /* Methods */
2878
2879 /**
2880 * Handle frame document key down events.
2881 *
2882 * @private
2883 * @param {jQuery.Event} e Key down event
2884 */
2885 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2886 if ( e.which === OO.ui.Keys.ESCAPE ) {
2887 this.close();
2888 e.preventDefault();
2889 e.stopPropagation();
2890 }
2891 };
2892
2893 /**
2894 * Handle action resized events.
2895 *
2896 * @private
2897 * @param {OO.ui.ActionWidget} action Action that was resized
2898 */
2899 OO.ui.Dialog.prototype.onActionResize = function () {
2900 // Override in subclass
2901 };
2902
2903 /**
2904 * Handle action click events.
2905 *
2906 * @private
2907 * @param {OO.ui.ActionWidget} action Action that was clicked
2908 */
2909 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2910 if ( !this.isPending() ) {
2911 this.executeAction( action.getAction() );
2912 }
2913 };
2914
2915 /**
2916 * Handle actions change event.
2917 *
2918 * @private
2919 */
2920 OO.ui.Dialog.prototype.onActionsChange = function () {
2921 this.detachActions();
2922 if ( !this.isClosing() ) {
2923 this.attachActions();
2924 }
2925 };
2926
2927 /**
2928 * Get the set of actions used by the dialog.
2929 *
2930 * @return {OO.ui.ActionSet}
2931 */
2932 OO.ui.Dialog.prototype.getActions = function () {
2933 return this.actions;
2934 };
2935
2936 /**
2937 * Get a process for taking action.
2938 *
2939 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2940 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2941 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2942 *
2943 * @param {string} [action] Symbolic name of action
2944 * @return {OO.ui.Process} Action process
2945 */
2946 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2947 return new OO.ui.Process()
2948 .next( function () {
2949 if ( !action ) {
2950 // An empty action always closes the dialog without data, which should always be
2951 // safe and make no changes
2952 this.close();
2953 }
2954 }, this );
2955 };
2956
2957 /**
2958 * @inheritdoc
2959 *
2960 * @param {Object} [data] Dialog opening data
2961 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2962 * the {@link #static-title static title}
2963 * @param {Object[]} [data.actions] List of configuration options for each
2964 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2965 */
2966 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2967 data = data || {};
2968
2969 // Parent method
2970 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2971 .next( function () {
2972 var config = this.constructor.static,
2973 actions = data.actions !== undefined ? data.actions : config.actions;
2974
2975 this.title.setLabel(
2976 data.title !== undefined ? data.title : this.constructor.static.title
2977 );
2978 this.actions.add( this.getActionWidgets( actions ) );
2979
2980 if ( this.constructor.static.escapable ) {
2981 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2982 }
2983 }, this );
2984 };
2985
2986 /**
2987 * @inheritdoc
2988 */
2989 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2990 // Parent method
2991 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2992 .first( function () {
2993 if ( this.constructor.static.escapable ) {
2994 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2995 }
2996
2997 this.actions.clear();
2998 this.currentAction = null;
2999 }, this );
3000 };
3001
3002 /**
3003 * @inheritdoc
3004 */
3005 OO.ui.Dialog.prototype.initialize = function () {
3006 var titleId;
3007
3008 // Parent method
3009 OO.ui.Dialog.parent.prototype.initialize.call( this );
3010
3011 titleId = OO.ui.generateElementId();
3012
3013 // Properties
3014 this.title = new OO.ui.LabelWidget( {
3015 id: titleId
3016 } );
3017
3018 // Initialization
3019 this.$content.addClass( 'oo-ui-dialog-content' );
3020 this.$element.attr( 'aria-labelledby', titleId );
3021 this.setPendingElement( this.$head );
3022 };
3023
3024 /**
3025 * Get action widgets from a list of configs
3026 *
3027 * @param {Object[]} actions Action widget configs
3028 * @return {OO.ui.ActionWidget[]} Action widgets
3029 */
3030 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
3031 var i, len, widgets = [];
3032 for ( i = 0, len = actions.length; i < len; i++ ) {
3033 widgets.push(
3034 new OO.ui.ActionWidget( actions[ i ] )
3035 );
3036 }
3037 return widgets;
3038 };
3039
3040 /**
3041 * Attach action actions.
3042 *
3043 * @protected
3044 */
3045 OO.ui.Dialog.prototype.attachActions = function () {
3046 // Remember the list of potentially attached actions
3047 this.attachedActions = this.actions.get();
3048 };
3049
3050 /**
3051 * Detach action actions.
3052 *
3053 * @protected
3054 * @chainable
3055 */
3056 OO.ui.Dialog.prototype.detachActions = function () {
3057 var i, len;
3058
3059 // Detach all actions that may have been previously attached
3060 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
3061 this.attachedActions[ i ].$element.detach();
3062 }
3063 this.attachedActions = [];
3064 };
3065
3066 /**
3067 * Execute an action.
3068 *
3069 * @param {string} action Symbolic name of action to execute
3070 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3071 */
3072 OO.ui.Dialog.prototype.executeAction = function ( action ) {
3073 this.pushPending();
3074 this.currentAction = action;
3075 return this.getActionProcess( action ).execute()
3076 .always( this.popPending.bind( this ) );
3077 };
3078
3079 /**
3080 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3081 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3082 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3083 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3084 * pertinent data and reused.
3085 *
3086 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3087 * `opened`, and `closing`, which represent the primary stages of the cycle:
3088 *
3089 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3090 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3091 *
3092 * - an `opening` event is emitted with an `opening` promise
3093 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3094 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3095 * window and its result executed
3096 * - a `setup` progress notification is emitted from the `opening` promise
3097 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3098 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3099 * window and its result executed
3100 * - a `ready` progress notification is emitted from the `opening` promise
3101 * - the `opening` promise is resolved with an `opened` promise
3102 *
3103 * **Opened**: the window is now open.
3104 *
3105 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3106 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3107 * to close the window.
3108 *
3109 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3110 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3111 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3112 * window and its result executed
3113 * - a `hold` progress notification is emitted from the `closing` promise
3114 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3115 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3116 * window and its result executed
3117 * - a `teardown` progress notification is emitted from the `closing` promise
3118 * - the `closing` promise is resolved. The window is now closed
3119 *
3120 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3121 *
3122 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3123 *
3124 * @class
3125 * @extends OO.ui.Element
3126 * @mixins OO.EventEmitter
3127 *
3128 * @constructor
3129 * @param {Object} [config] Configuration options
3130 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3131 * Note that window classes that are instantiated with a factory must have
3132 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3133 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3134 */
3135 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3136 // Configuration initialization
3137 config = config || {};
3138
3139 // Parent constructor
3140 OO.ui.WindowManager.parent.call( this, config );
3141
3142 // Mixin constructors
3143 OO.EventEmitter.call( this );
3144
3145 // Properties
3146 this.factory = config.factory;
3147 this.modal = config.modal === undefined || !!config.modal;
3148 this.windows = {};
3149 this.opening = null;
3150 this.opened = null;
3151 this.closing = null;
3152 this.preparingToOpen = null;
3153 this.preparingToClose = null;
3154 this.currentWindow = null;
3155 this.globalEvents = false;
3156 this.$ariaHidden = null;
3157 this.onWindowResizeTimeout = null;
3158 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3159 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3160
3161 // Initialization
3162 this.$element
3163 .addClass( 'oo-ui-windowManager' )
3164 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3165 };
3166
3167 /* Setup */
3168
3169 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3170 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3171
3172 /* Events */
3173
3174 /**
3175 * An 'opening' event is emitted when the window begins to be opened.
3176 *
3177 * @event opening
3178 * @param {OO.ui.Window} win Window that's being opened
3179 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3180 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3181 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3182 * @param {Object} data Window opening data
3183 */
3184
3185 /**
3186 * A 'closing' event is emitted when the window begins to be closed.
3187 *
3188 * @event closing
3189 * @param {OO.ui.Window} win Window that's being closed
3190 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3191 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3192 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3193 * is the closing data.
3194 * @param {Object} data Window closing data
3195 */
3196
3197 /**
3198 * A 'resize' event is emitted when a window is resized.
3199 *
3200 * @event resize
3201 * @param {OO.ui.Window} win Window that was resized
3202 */
3203
3204 /* Static Properties */
3205
3206 /**
3207 * Map of the symbolic name of each window size and its CSS properties.
3208 *
3209 * @static
3210 * @inheritable
3211 * @property {Object}
3212 */
3213 OO.ui.WindowManager.static.sizes = {
3214 small: {
3215 width: 300
3216 },
3217 medium: {
3218 width: 500
3219 },
3220 large: {
3221 width: 700
3222 },
3223 larger: {
3224 width: 900
3225 },
3226 full: {
3227 // These can be non-numeric because they are never used in calculations
3228 width: '100%',
3229 height: '100%'
3230 }
3231 };
3232
3233 /**
3234 * Symbolic name of the default window size.
3235 *
3236 * The default size is used if the window's requested size is not recognized.
3237 *
3238 * @static
3239 * @inheritable
3240 * @property {string}
3241 */
3242 OO.ui.WindowManager.static.defaultSize = 'medium';
3243
3244 /* Methods */
3245
3246 /**
3247 * Handle window resize events.
3248 *
3249 * @private
3250 * @param {jQuery.Event} e Window resize event
3251 */
3252 OO.ui.WindowManager.prototype.onWindowResize = function () {
3253 clearTimeout( this.onWindowResizeTimeout );
3254 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3255 };
3256
3257 /**
3258 * Handle window resize events.
3259 *
3260 * @private
3261 * @param {jQuery.Event} e Window resize event
3262 */
3263 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3264 if ( this.currentWindow ) {
3265 this.updateWindowSize( this.currentWindow );
3266 }
3267 };
3268
3269 /**
3270 * Check if window is opening.
3271 *
3272 * @return {boolean} Window is opening
3273 */
3274 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3275 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3276 };
3277
3278 /**
3279 * Check if window is closing.
3280 *
3281 * @return {boolean} Window is closing
3282 */
3283 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3284 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3285 };
3286
3287 /**
3288 * Check if window is opened.
3289 *
3290 * @return {boolean} Window is opened
3291 */
3292 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3293 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3294 };
3295
3296 /**
3297 * Check if a window is being managed.
3298 *
3299 * @param {OO.ui.Window} win Window to check
3300 * @return {boolean} Window is being managed
3301 */
3302 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3303 var name;
3304
3305 for ( name in this.windows ) {
3306 if ( this.windows[ name ] === win ) {
3307 return true;
3308 }
3309 }
3310
3311 return false;
3312 };
3313
3314 /**
3315 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3316 *
3317 * @param {OO.ui.Window} win Window being opened
3318 * @param {Object} [data] Window opening data
3319 * @return {number} Milliseconds to wait
3320 */
3321 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3322 return 0;
3323 };
3324
3325 /**
3326 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3327 *
3328 * @param {OO.ui.Window} win Window being opened
3329 * @param {Object} [data] Window opening data
3330 * @return {number} Milliseconds to wait
3331 */
3332 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3333 return 0;
3334 };
3335
3336 /**
3337 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3338 *
3339 * @param {OO.ui.Window} win Window being closed
3340 * @param {Object} [data] Window closing data
3341 * @return {number} Milliseconds to wait
3342 */
3343 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3344 return 0;
3345 };
3346
3347 /**
3348 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3349 * executing the ‘teardown’ process.
3350 *
3351 * @param {OO.ui.Window} win Window being closed
3352 * @param {Object} [data] Window closing data
3353 * @return {number} Milliseconds to wait
3354 */
3355 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3356 return this.modal ? 250 : 0;
3357 };
3358
3359 /**
3360 * Get a window by its symbolic name.
3361 *
3362 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3363 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3364 * for more information about using factories.
3365 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3366 *
3367 * @param {string} name Symbolic name of the window
3368 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3369 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3370 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3371 */
3372 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3373 var deferred = $.Deferred(),
3374 win = this.windows[ name ];
3375
3376 if ( !( win instanceof OO.ui.Window ) ) {
3377 if ( this.factory ) {
3378 if ( !this.factory.lookup( name ) ) {
3379 deferred.reject( new OO.ui.Error(
3380 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3381 ) );
3382 } else {
3383 win = this.factory.create( name );
3384 this.addWindows( [ win ] );
3385 deferred.resolve( win );
3386 }
3387 } else {
3388 deferred.reject( new OO.ui.Error(
3389 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3390 ) );
3391 }
3392 } else {
3393 deferred.resolve( win );
3394 }
3395
3396 return deferred.promise();
3397 };
3398
3399 /**
3400 * Get current window.
3401 *
3402 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3403 */
3404 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3405 return this.currentWindow;
3406 };
3407
3408 /**
3409 * Open a window.
3410 *
3411 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3412 * @param {Object} [data] Window opening data
3413 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3414 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3415 * @fires opening
3416 */
3417 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3418 var manager = this,
3419 opening = $.Deferred();
3420
3421 // Argument handling
3422 if ( typeof win === 'string' ) {
3423 return this.getWindow( win ).then( function ( win ) {
3424 return manager.openWindow( win, data );
3425 } );
3426 }
3427
3428 // Error handling
3429 if ( !this.hasWindow( win ) ) {
3430 opening.reject( new OO.ui.Error(
3431 'Cannot open window: window is not attached to manager'
3432 ) );
3433 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3434 opening.reject( new OO.ui.Error(
3435 'Cannot open window: another window is opening or open'
3436 ) );
3437 }
3438
3439 // Window opening
3440 if ( opening.state() !== 'rejected' ) {
3441 // If a window is currently closing, wait for it to complete
3442 this.preparingToOpen = $.when( this.closing );
3443 // Ensure handlers get called after preparingToOpen is set
3444 this.preparingToOpen.done( function () {
3445 if ( manager.modal ) {
3446 manager.toggleGlobalEvents( true );
3447 manager.toggleAriaIsolation( true );
3448 }
3449 manager.currentWindow = win;
3450 manager.opening = opening;
3451 manager.preparingToOpen = null;
3452 manager.emit( 'opening', win, opening, data );
3453 setTimeout( function () {
3454 win.setup( data ).then( function () {
3455 manager.updateWindowSize( win );
3456 manager.opening.notify( { state: 'setup' } );
3457 setTimeout( function () {
3458 win.ready( data ).then( function () {
3459 manager.opening.notify( { state: 'ready' } );
3460 manager.opening = null;
3461 manager.opened = $.Deferred();
3462 opening.resolve( manager.opened.promise(), data );
3463 }, function () {
3464 manager.opening = null;
3465 manager.opened = $.Deferred();
3466 opening.reject();
3467 manager.closeWindow( win );
3468 } );
3469 }, manager.getReadyDelay() );
3470 }, function () {
3471 manager.opening = null;
3472 manager.opened = $.Deferred();
3473 opening.reject();
3474 manager.closeWindow( win );
3475 } );
3476 }, manager.getSetupDelay() );
3477 } );
3478 }
3479
3480 return opening.promise();
3481 };
3482
3483 /**
3484 * Close a window.
3485 *
3486 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3487 * @param {Object} [data] Window closing data
3488 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3489 * See {@link #event-closing 'closing' event} for more information about closing promises.
3490 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3491 * @fires closing
3492 */
3493 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3494 var manager = this,
3495 closing = $.Deferred(),
3496 opened;
3497
3498 // Argument handling
3499 if ( typeof win === 'string' ) {
3500 win = this.windows[ win ];
3501 } else if ( !this.hasWindow( win ) ) {
3502 win = null;
3503 }
3504
3505 // Error handling
3506 if ( !win ) {
3507 closing.reject( new OO.ui.Error(
3508 'Cannot close window: window is not attached to manager'
3509 ) );
3510 } else if ( win !== this.currentWindow ) {
3511 closing.reject( new OO.ui.Error(
3512 'Cannot close window: window already closed with different data'
3513 ) );
3514 } else if ( this.preparingToClose || this.closing ) {
3515 closing.reject( new OO.ui.Error(
3516 'Cannot close window: window already closing with different data'
3517 ) );
3518 }
3519
3520 // Window closing
3521 if ( closing.state() !== 'rejected' ) {
3522 // If the window is currently opening, close it when it's done
3523 this.preparingToClose = $.when( this.opening );
3524 // Ensure handlers get called after preparingToClose is set
3525 this.preparingToClose.always( function () {
3526 manager.closing = closing;
3527 manager.preparingToClose = null;
3528 manager.emit( 'closing', win, closing, data );
3529 opened = manager.opened;
3530 manager.opened = null;
3531 opened.resolve( closing.promise(), data );
3532 setTimeout( function () {
3533 win.hold( data ).then( function () {
3534 closing.notify( { state: 'hold' } );
3535 setTimeout( function () {
3536 win.teardown( data ).then( function () {
3537 closing.notify( { state: 'teardown' } );
3538 if ( manager.modal ) {
3539 manager.toggleGlobalEvents( false );
3540 manager.toggleAriaIsolation( false );
3541 }
3542 manager.closing = null;
3543 manager.currentWindow = null;
3544 closing.resolve( data );
3545 } );
3546 }, manager.getTeardownDelay() );
3547 } );
3548 }, manager.getHoldDelay() );
3549 } );
3550 }
3551
3552 return closing.promise();
3553 };
3554
3555 /**
3556 * Add windows to the window manager.
3557 *
3558 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3559 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3560 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3561 *
3562 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3563 * by reference, symbolic name, or explicitly defined symbolic names.
3564 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3565 * explicit nor a statically configured symbolic name.
3566 */
3567 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3568 var i, len, win, name, list;
3569
3570 if ( Array.isArray( windows ) ) {
3571 // Convert to map of windows by looking up symbolic names from static configuration
3572 list = {};
3573 for ( i = 0, len = windows.length; i < len; i++ ) {
3574 name = windows[ i ].constructor.static.name;
3575 if ( typeof name !== 'string' ) {
3576 throw new Error( 'Cannot add window' );
3577 }
3578 list[ name ] = windows[ i ];
3579 }
3580 } else if ( OO.isPlainObject( windows ) ) {
3581 list = windows;
3582 }
3583
3584 // Add windows
3585 for ( name in list ) {
3586 win = list[ name ];
3587 this.windows[ name ] = win.toggle( false );
3588 this.$element.append( win.$element );
3589 win.setManager( this );
3590 }
3591 };
3592
3593 /**
3594 * Remove the specified windows from the windows manager.
3595 *
3596 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3597 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3598 * longer listens to events, use the #destroy method.
3599 *
3600 * @param {string[]} names Symbolic names of windows to remove
3601 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3602 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3603 */
3604 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3605 var i, len, win, name, cleanupWindow,
3606 manager = this,
3607 promises = [],
3608 cleanup = function ( name, win ) {
3609 delete manager.windows[ name ];
3610 win.$element.detach();
3611 };
3612
3613 for ( i = 0, len = names.length; i < len; i++ ) {
3614 name = names[ i ];
3615 win = this.windows[ name ];
3616 if ( !win ) {
3617 throw new Error( 'Cannot remove window' );
3618 }
3619 cleanupWindow = cleanup.bind( null, name, win );
3620 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3621 }
3622
3623 return $.when.apply( $, promises );
3624 };
3625
3626 /**
3627 * Remove all windows from the window manager.
3628 *
3629 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3630 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3631 * To remove just a subset of windows, use the #removeWindows method.
3632 *
3633 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3634 */
3635 OO.ui.WindowManager.prototype.clearWindows = function () {
3636 return this.removeWindows( Object.keys( this.windows ) );
3637 };
3638
3639 /**
3640 * Set dialog size. In general, this method should not be called directly.
3641 *
3642 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3643 *
3644 * @chainable
3645 */
3646 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3647 var isFullscreen;
3648
3649 // Bypass for non-current, and thus invisible, windows
3650 if ( win !== this.currentWindow ) {
3651 return;
3652 }
3653
3654 isFullscreen = win.getSize() === 'full';
3655
3656 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3657 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3658 win.setDimensions( win.getSizeProperties() );
3659
3660 this.emit( 'resize', win );
3661
3662 return this;
3663 };
3664
3665 /**
3666 * Bind or unbind global events for scrolling.
3667 *
3668 * @private
3669 * @param {boolean} [on] Bind global events
3670 * @chainable
3671 */
3672 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3673 var scrollWidth, bodyMargin,
3674 $body = $( this.getElementDocument().body ),
3675 // We could have multiple window managers open so only modify
3676 // the body css at the bottom of the stack
3677 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3678
3679 on = on === undefined ? !!this.globalEvents : !!on;
3680
3681 if ( on ) {
3682 if ( !this.globalEvents ) {
3683 $( this.getElementWindow() ).on( {
3684 // Start listening for top-level window dimension changes
3685 'orientationchange resize': this.onWindowResizeHandler
3686 } );
3687 if ( stackDepth === 0 ) {
3688 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3689 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3690 $body.css( {
3691 overflow: 'hidden',
3692 'margin-right': bodyMargin + scrollWidth
3693 } );
3694 }
3695 stackDepth++;
3696 this.globalEvents = true;
3697 }
3698 } else if ( this.globalEvents ) {
3699 $( this.getElementWindow() ).off( {
3700 // Stop listening for top-level window dimension changes
3701 'orientationchange resize': this.onWindowResizeHandler
3702 } );
3703 stackDepth--;
3704 if ( stackDepth === 0 ) {
3705 $body.css( {
3706 overflow: '',
3707 'margin-right': ''
3708 } );
3709 }
3710 this.globalEvents = false;
3711 }
3712 $body.data( 'windowManagerGlobalEvents', stackDepth );
3713
3714 return this;
3715 };
3716
3717 /**
3718 * Toggle screen reader visibility of content other than the window manager.
3719 *
3720 * @private
3721 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3722 * @chainable
3723 */
3724 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3725 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3726
3727 if ( isolate ) {
3728 if ( !this.$ariaHidden ) {
3729 // Hide everything other than the window manager from screen readers
3730 this.$ariaHidden = $( 'body' )
3731 .children()
3732 .not( this.$element.parentsUntil( 'body' ).last() )
3733 .attr( 'aria-hidden', '' );
3734 }
3735 } else if ( this.$ariaHidden ) {
3736 // Restore screen reader visibility
3737 this.$ariaHidden.removeAttr( 'aria-hidden' );
3738 this.$ariaHidden = null;
3739 }
3740
3741 return this;
3742 };
3743
3744 /**
3745 * Destroy the window manager.
3746 *
3747 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3748 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3749 * instead.
3750 */
3751 OO.ui.WindowManager.prototype.destroy = function () {
3752 this.toggleGlobalEvents( false );
3753 this.toggleAriaIsolation( false );
3754 this.clearWindows();
3755 this.$element.remove();
3756 };
3757
3758 /**
3759 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3760 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3761 * appearance and functionality of the error interface.
3762 *
3763 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3764 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3765 * that initiated the failed process will be disabled.
3766 *
3767 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3768 * process again.
3769 *
3770 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3771 *
3772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3773 *
3774 * @class
3775 *
3776 * @constructor
3777 * @param {string|jQuery} message Description of error
3778 * @param {Object} [config] Configuration options
3779 * @cfg {boolean} [recoverable=true] Error is recoverable.
3780 * By default, errors are recoverable, and users can try the process again.
3781 * @cfg {boolean} [warning=false] Error is a warning.
3782 * If the error is a warning, the error interface will include a
3783 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3784 * is not triggered a second time if the user chooses to continue.
3785 */
3786 OO.ui.Error = function OoUiError( message, config ) {
3787 // Allow passing positional parameters inside the config object
3788 if ( OO.isPlainObject( message ) && config === undefined ) {
3789 config = message;
3790 message = config.message;
3791 }
3792
3793 // Configuration initialization
3794 config = config || {};
3795
3796 // Properties
3797 this.message = message instanceof jQuery ? message : String( message );
3798 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3799 this.warning = !!config.warning;
3800 };
3801
3802 /* Setup */
3803
3804 OO.initClass( OO.ui.Error );
3805
3806 /* Methods */
3807
3808 /**
3809 * Check if the error is recoverable.
3810 *
3811 * If the error is recoverable, users are able to try the process again.
3812 *
3813 * @return {boolean} Error is recoverable
3814 */
3815 OO.ui.Error.prototype.isRecoverable = function () {
3816 return this.recoverable;
3817 };
3818
3819 /**
3820 * Check if the error is a warning.
3821 *
3822 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3823 *
3824 * @return {boolean} Error is warning
3825 */
3826 OO.ui.Error.prototype.isWarning = function () {
3827 return this.warning;
3828 };
3829
3830 /**
3831 * Get error message as DOM nodes.
3832 *
3833 * @return {jQuery} Error message in DOM nodes
3834 */
3835 OO.ui.Error.prototype.getMessage = function () {
3836 return this.message instanceof jQuery ?
3837 this.message.clone() :
3838 $( '<div>' ).text( this.message ).contents();
3839 };
3840
3841 /**
3842 * Get the error message text.
3843 *
3844 * @return {string} Error message
3845 */
3846 OO.ui.Error.prototype.getMessageText = function () {
3847 return this.message instanceof jQuery ? this.message.text() : this.message;
3848 };
3849
3850 /**
3851 * Wraps an HTML snippet for use with configuration values which default
3852 * to strings. This bypasses the default html-escaping done to string
3853 * values.
3854 *
3855 * @class
3856 *
3857 * @constructor
3858 * @param {string} [content] HTML content
3859 */
3860 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3861 // Properties
3862 this.content = content;
3863 };
3864
3865 /* Setup */
3866
3867 OO.initClass( OO.ui.HtmlSnippet );
3868
3869 /* Methods */
3870
3871 /**
3872 * Render into HTML.
3873 *
3874 * @return {string} Unchanged HTML snippet.
3875 */
3876 OO.ui.HtmlSnippet.prototype.toString = function () {
3877 return this.content;
3878 };
3879
3880 /**
3881 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3882 * or a function:
3883 *
3884 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3885 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3886 * or stop if the promise is rejected.
3887 * - **function**: the process will execute the function. The process will stop if the function returns
3888 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3889 * will wait for that number of milliseconds before proceeding.
3890 *
3891 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3892 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3893 * its remaining steps will not be performed.
3894 *
3895 * @class
3896 *
3897 * @constructor
3898 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3899 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3900 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3901 * a number or promise.
3902 * @return {Object} Step object, with `callback` and `context` properties
3903 */
3904 OO.ui.Process = function ( step, context ) {
3905 // Properties
3906 this.steps = [];
3907
3908 // Initialization
3909 if ( step !== undefined ) {
3910 this.next( step, context );
3911 }
3912 };
3913
3914 /* Setup */
3915
3916 OO.initClass( OO.ui.Process );
3917
3918 /* Methods */
3919
3920 /**
3921 * Start the process.
3922 *
3923 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3924 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3925 * and any remaining steps are not performed.
3926 */
3927 OO.ui.Process.prototype.execute = function () {
3928 var i, len, promise;
3929
3930 /**
3931 * Continue execution.
3932 *
3933 * @ignore
3934 * @param {Array} step A function and the context it should be called in
3935 * @return {Function} Function that continues the process
3936 */
3937 function proceed( step ) {
3938 return function () {
3939 // Execute step in the correct context
3940 var deferred,
3941 result = step.callback.call( step.context );
3942
3943 if ( result === false ) {
3944 // Use rejected promise for boolean false results
3945 return $.Deferred().reject( [] ).promise();
3946 }
3947 if ( typeof result === 'number' ) {
3948 if ( result < 0 ) {
3949 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3950 }
3951 // Use a delayed promise for numbers, expecting them to be in milliseconds
3952 deferred = $.Deferred();
3953 setTimeout( deferred.resolve, result );
3954 return deferred.promise();
3955 }
3956 if ( result instanceof OO.ui.Error ) {
3957 // Use rejected promise for error
3958 return $.Deferred().reject( [ result ] ).promise();
3959 }
3960 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3961 // Use rejected promise for list of errors
3962 return $.Deferred().reject( result ).promise();
3963 }
3964 // Duck-type the object to see if it can produce a promise
3965 if ( result && $.isFunction( result.promise ) ) {
3966 // Use a promise generated from the result
3967 return result.promise();
3968 }
3969 // Use resolved promise for other results
3970 return $.Deferred().resolve().promise();
3971 };
3972 }
3973
3974 if ( this.steps.length ) {
3975 // Generate a chain reaction of promises
3976 promise = proceed( this.steps[ 0 ] )();
3977 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3978 promise = promise.then( proceed( this.steps[ i ] ) );
3979 }
3980 } else {
3981 promise = $.Deferred().resolve().promise();
3982 }
3983
3984 return promise;
3985 };
3986
3987 /**
3988 * Create a process step.
3989 *
3990 * @private
3991 * @param {number|jQuery.Promise|Function} step
3992 *
3993 * - Number of milliseconds to wait before proceeding
3994 * - Promise that must be resolved before proceeding
3995 * - Function to execute
3996 * - If the function returns a boolean false the process will stop
3997 * - If the function returns a promise, the process will continue to the next
3998 * step when the promise is resolved or stop if the promise is rejected
3999 * - If the function returns a number, the process will wait for that number of
4000 * milliseconds before proceeding
4001 * @param {Object} [context=null] Execution context of the function. The context is
4002 * ignored if the step is a number or promise.
4003 * @return {Object} Step object, with `callback` and `context` properties
4004 */
4005 OO.ui.Process.prototype.createStep = function ( step, context ) {
4006 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
4007 return {
4008 callback: function () {
4009 return step;
4010 },
4011 context: null
4012 };
4013 }
4014 if ( $.isFunction( step ) ) {
4015 return {
4016 callback: step,
4017 context: context
4018 };
4019 }
4020 throw new Error( 'Cannot create process step: number, promise or function expected' );
4021 };
4022
4023 /**
4024 * Add step to the beginning of the process.
4025 *
4026 * @inheritdoc #createStep
4027 * @return {OO.ui.Process} this
4028 * @chainable
4029 */
4030 OO.ui.Process.prototype.first = function ( step, context ) {
4031 this.steps.unshift( this.createStep( step, context ) );
4032 return this;
4033 };
4034
4035 /**
4036 * Add step to the end of the process.
4037 *
4038 * @inheritdoc #createStep
4039 * @return {OO.ui.Process} this
4040 * @chainable
4041 */
4042 OO.ui.Process.prototype.next = function ( step, context ) {
4043 this.steps.push( this.createStep( step, context ) );
4044 return this;
4045 };
4046
4047 /**
4048 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4049 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4050 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4051 *
4052 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4053 *
4054 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4055 *
4056 * @class
4057 * @extends OO.Factory
4058 * @constructor
4059 */
4060 OO.ui.ToolFactory = function OoUiToolFactory() {
4061 // Parent constructor
4062 OO.ui.ToolFactory.parent.call( this );
4063 };
4064
4065 /* Setup */
4066
4067 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
4068
4069 /* Methods */
4070
4071 /**
4072 * Get tools from the factory
4073 *
4074 * @param {Array} include Included tools
4075 * @param {Array} exclude Excluded tools
4076 * @param {Array} promote Promoted tools
4077 * @param {Array} demote Demoted tools
4078 * @return {string[]} List of tools
4079 */
4080 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
4081 var i, len, included, promoted, demoted,
4082 auto = [],
4083 used = {};
4084
4085 // Collect included and not excluded tools
4086 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
4087
4088 // Promotion
4089 promoted = this.extract( promote, used );
4090 demoted = this.extract( demote, used );
4091
4092 // Auto
4093 for ( i = 0, len = included.length; i < len; i++ ) {
4094 if ( !used[ included[ i ] ] ) {
4095 auto.push( included[ i ] );
4096 }
4097 }
4098
4099 return promoted.concat( auto ).concat( demoted );
4100 };
4101
4102 /**
4103 * Get a flat list of names from a list of names or groups.
4104 *
4105 * Tools can be specified in the following ways:
4106 *
4107 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4108 * - All tools in a group: `{ group: 'group-name' }`
4109 * - All tools: `'*'`
4110 *
4111 * @private
4112 * @param {Array|string} collection List of tools
4113 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4114 * names will be added as properties
4115 * @return {string[]} List of extracted names
4116 */
4117 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4118 var i, len, item, name, tool,
4119 names = [];
4120
4121 if ( collection === '*' ) {
4122 for ( name in this.registry ) {
4123 tool = this.registry[ name ];
4124 if (
4125 // Only add tools by group name when auto-add is enabled
4126 tool.static.autoAddToCatchall &&
4127 // Exclude already used tools
4128 ( !used || !used[ name ] )
4129 ) {
4130 names.push( name );
4131 if ( used ) {
4132 used[ name ] = true;
4133 }
4134 }
4135 }
4136 } else if ( Array.isArray( collection ) ) {
4137 for ( i = 0, len = collection.length; i < len; i++ ) {
4138 item = collection[ i ];
4139 // Allow plain strings as shorthand for named tools
4140 if ( typeof item === 'string' ) {
4141 item = { name: item };
4142 }
4143 if ( OO.isPlainObject( item ) ) {
4144 if ( item.group ) {
4145 for ( name in this.registry ) {
4146 tool = this.registry[ name ];
4147 if (
4148 // Include tools with matching group
4149 tool.static.group === item.group &&
4150 // Only add tools by group name when auto-add is enabled
4151 tool.static.autoAddToGroup &&
4152 // Exclude already used tools
4153 ( !used || !used[ name ] )
4154 ) {
4155 names.push( name );
4156 if ( used ) {
4157 used[ name ] = true;
4158 }
4159 }
4160 }
4161 // Include tools with matching name and exclude already used tools
4162 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4163 names.push( item.name );
4164 if ( used ) {
4165 used[ item.name ] = true;
4166 }
4167 }
4168 }
4169 }
4170 }
4171 return names;
4172 };
4173
4174 /**
4175 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4176 * specify a symbolic name and be registered with the factory. The following classes are registered by
4177 * default:
4178 *
4179 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4180 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4181 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4182 *
4183 * See {@link OO.ui.Toolbar toolbars} for an example.
4184 *
4185 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4186 *
4187 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4188 * @class
4189 * @extends OO.Factory
4190 * @constructor
4191 */
4192 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4193 var i, l, defaultClasses;
4194 // Parent constructor
4195 OO.Factory.call( this );
4196
4197 defaultClasses = this.constructor.static.getDefaultClasses();
4198
4199 // Register default toolgroups
4200 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4201 this.register( defaultClasses[ i ] );
4202 }
4203 };
4204
4205 /* Setup */
4206
4207 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4208
4209 /* Static Methods */
4210
4211 /**
4212 * Get a default set of classes to be registered on construction.
4213 *
4214 * @return {Function[]} Default classes
4215 */
4216 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4217 return [
4218 OO.ui.BarToolGroup,
4219 OO.ui.ListToolGroup,
4220 OO.ui.MenuToolGroup
4221 ];
4222 };
4223
4224 /**
4225 * Theme logic.
4226 *
4227 * @abstract
4228 * @class
4229 *
4230 * @constructor
4231 * @param {Object} [config] Configuration options
4232 */
4233 OO.ui.Theme = function OoUiTheme( config ) {
4234 // Configuration initialization
4235 config = config || {};
4236 };
4237
4238 /* Setup */
4239
4240 OO.initClass( OO.ui.Theme );
4241
4242 /* Methods */
4243
4244 /**
4245 * Get a list of classes to be applied to a widget.
4246 *
4247 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4248 * otherwise state transitions will not work properly.
4249 *
4250 * @param {OO.ui.Element} element Element for which to get classes
4251 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4252 */
4253 OO.ui.Theme.prototype.getElementClasses = function () {
4254 return { on: [], off: [] };
4255 };
4256
4257 /**
4258 * Update CSS classes provided by the theme.
4259 *
4260 * For elements with theme logic hooks, this should be called any time there's a state change.
4261 *
4262 * @param {OO.ui.Element} element Element for which to update classes
4263 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4264 */
4265 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4266 var $elements = $( [] ),
4267 classes = this.getElementClasses( element );
4268
4269 if ( element.$icon ) {
4270 $elements = $elements.add( element.$icon );
4271 }
4272 if ( element.$indicator ) {
4273 $elements = $elements.add( element.$indicator );
4274 }
4275
4276 $elements
4277 .removeClass( classes.off.join( ' ' ) )
4278 .addClass( classes.on.join( ' ' ) );
4279 };
4280
4281 /**
4282 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
4283 * the {@link OO.ui.mixin.LookupElement}.
4284 *
4285 * @class
4286 * @abstract
4287 *
4288 * @constructor
4289 */
4290 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
4291 this.requestCache = {};
4292 this.requestQuery = null;
4293 this.requestRequest = null;
4294 };
4295
4296 /* Setup */
4297
4298 OO.initClass( OO.ui.mixin.RequestManager );
4299
4300 /**
4301 * Get request results for the current query.
4302 *
4303 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
4304 * the done event. If the request was aborted to make way for a subsequent request, this promise
4305 * may not be rejected, depending on what jQuery feels like doing.
4306 */
4307 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
4308 var widget = this,
4309 value = this.getRequestQuery(),
4310 deferred = $.Deferred(),
4311 ourRequest;
4312
4313 this.abortRequest();
4314 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
4315 deferred.resolve( this.requestCache[ value ] );
4316 } else {
4317 if ( this.pushPending ) {
4318 this.pushPending();
4319 }
4320 this.requestQuery = value;
4321 ourRequest = this.requestRequest = this.getRequest();
4322 ourRequest
4323 .always( function () {
4324 // We need to pop pending even if this is an old request, otherwise
4325 // the widget will remain pending forever.
4326 // TODO: this assumes that an aborted request will fail or succeed soon after
4327 // being aborted, or at least eventually. It would be nice if we could popPending()
4328 // at abort time, but only if we knew that we hadn't already called popPending()
4329 // for that request.
4330 if ( widget.popPending ) {
4331 widget.popPending();
4332 }
4333 } )
4334 .done( function ( response ) {
4335 // If this is an old request (and aborting it somehow caused it to still succeed),
4336 // ignore its success completely
4337 if ( ourRequest === widget.requestRequest ) {
4338 widget.requestQuery = null;
4339 widget.requestRequest = null;
4340 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
4341 deferred.resolve( widget.requestCache[ value ] );
4342 }
4343 } )
4344 .fail( function () {
4345 // If this is an old request (or a request failing because it's being aborted),
4346 // ignore its failure completely
4347 if ( ourRequest === widget.requestRequest ) {
4348 widget.requestQuery = null;
4349 widget.requestRequest = null;
4350 deferred.reject();
4351 }
4352 } );
4353 }
4354 return deferred.promise();
4355 };
4356
4357 /**
4358 * Abort the currently pending request, if any.
4359 *
4360 * @private
4361 */
4362 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
4363 var oldRequest = this.requestRequest;
4364 if ( oldRequest ) {
4365 // First unset this.requestRequest to the fail handler will notice
4366 // that the request is no longer current
4367 this.requestRequest = null;
4368 this.requestQuery = null;
4369 oldRequest.abort();
4370 }
4371 };
4372
4373 /**
4374 * Get the query to be made.
4375 *
4376 * @protected
4377 * @method
4378 * @abstract
4379 * @return {string} query to be used
4380 */
4381 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
4382
4383 /**
4384 * Get a new request object of the current query value.
4385 *
4386 * @protected
4387 * @method
4388 * @abstract
4389 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
4390 */
4391 OO.ui.mixin.RequestManager.prototype.getRequest = null;
4392
4393 /**
4394 * Pre-process data returned by the request from #getRequest.
4395 *
4396 * The return value of this function will be cached, and any further queries for the given value
4397 * will use the cache rather than doing API requests.
4398 *
4399 * @protected
4400 * @method
4401 * @abstract
4402 * @param {Mixed} response Response from server
4403 * @return {Mixed} Cached result data
4404 */
4405 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
4406
4407 /**
4408 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4409 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4410 * order in which users will navigate through the focusable elements via the "tab" key.
4411 *
4412 * @example
4413 * // TabIndexedElement is mixed into the ButtonWidget class
4414 * // to provide a tabIndex property.
4415 * var button1 = new OO.ui.ButtonWidget( {
4416 * label: 'fourth',
4417 * tabIndex: 4
4418 * } );
4419 * var button2 = new OO.ui.ButtonWidget( {
4420 * label: 'second',
4421 * tabIndex: 2
4422 * } );
4423 * var button3 = new OO.ui.ButtonWidget( {
4424 * label: 'third',
4425 * tabIndex: 3
4426 * } );
4427 * var button4 = new OO.ui.ButtonWidget( {
4428 * label: 'first',
4429 * tabIndex: 1
4430 * } );
4431 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4432 *
4433 * @abstract
4434 * @class
4435 *
4436 * @constructor
4437 * @param {Object} [config] Configuration options
4438 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4439 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4440 * functionality will be applied to it instead.
4441 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4442 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4443 * to remove the element from the tab-navigation flow.
4444 */
4445 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4446 // Configuration initialization
4447 config = $.extend( { tabIndex: 0 }, config );
4448
4449 // Properties
4450 this.$tabIndexed = null;
4451 this.tabIndex = null;
4452
4453 // Events
4454 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4455
4456 // Initialization
4457 this.setTabIndex( config.tabIndex );
4458 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4459 };
4460
4461 /* Setup */
4462
4463 OO.initClass( OO.ui.mixin.TabIndexedElement );
4464
4465 /* Methods */
4466
4467 /**
4468 * Set the element that should use the tabindex functionality.
4469 *
4470 * This method is used to retarget a tabindex mixin so that its functionality applies
4471 * to the specified element. If an element is currently using the functionality, the mixin’s
4472 * effect on that element is removed before the new element is set up.
4473 *
4474 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4475 * @chainable
4476 */
4477 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4478 var tabIndex = this.tabIndex;
4479 // Remove attributes from old $tabIndexed
4480 this.setTabIndex( null );
4481 // Force update of new $tabIndexed
4482 this.$tabIndexed = $tabIndexed;
4483 this.tabIndex = tabIndex;
4484 return this.updateTabIndex();
4485 };
4486
4487 /**
4488 * Set the value of the tabindex.
4489 *
4490 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4491 * @chainable
4492 */
4493 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4494 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4495
4496 if ( this.tabIndex !== tabIndex ) {
4497 this.tabIndex = tabIndex;
4498 this.updateTabIndex();
4499 }
4500
4501 return this;
4502 };
4503
4504 /**
4505 * Update the `tabindex` attribute, in case of changes to tab index or
4506 * disabled state.
4507 *
4508 * @private
4509 * @chainable
4510 */
4511 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4512 if ( this.$tabIndexed ) {
4513 if ( this.tabIndex !== null ) {
4514 // Do not index over disabled elements
4515 this.$tabIndexed.attr( {
4516 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4517 // Support: ChromeVox and NVDA
4518 // These do not seem to inherit aria-disabled from parent elements
4519 'aria-disabled': this.isDisabled().toString()
4520 } );
4521 } else {
4522 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4523 }
4524 }
4525 return this;
4526 };
4527
4528 /**
4529 * Handle disable events.
4530 *
4531 * @private
4532 * @param {boolean} disabled Element is disabled
4533 */
4534 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4535 this.updateTabIndex();
4536 };
4537
4538 /**
4539 * Get the value of the tabindex.
4540 *
4541 * @return {number|null} Tabindex value
4542 */
4543 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4544 return this.tabIndex;
4545 };
4546
4547 /**
4548 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4549 * interface element that can be configured with access keys for accessibility.
4550 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4551 *
4552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4553 * @abstract
4554 * @class
4555 *
4556 * @constructor
4557 * @param {Object} [config] Configuration options
4558 * @cfg {jQuery} [$button] The button element created by the class.
4559 * If this configuration is omitted, the button element will use a generated `<a>`.
4560 * @cfg {boolean} [framed=true] Render the button with a frame
4561 */
4562 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4563 // Configuration initialization
4564 config = config || {};
4565
4566 // Properties
4567 this.$button = null;
4568 this.framed = null;
4569 this.active = false;
4570 this.onMouseUpHandler = this.onMouseUp.bind( this );
4571 this.onMouseDownHandler = this.onMouseDown.bind( this );
4572 this.onKeyDownHandler = this.onKeyDown.bind( this );
4573 this.onKeyUpHandler = this.onKeyUp.bind( this );
4574 this.onClickHandler = this.onClick.bind( this );
4575 this.onKeyPressHandler = this.onKeyPress.bind( this );
4576
4577 // Initialization
4578 this.$element.addClass( 'oo-ui-buttonElement' );
4579 this.toggleFramed( config.framed === undefined || config.framed );
4580 this.setButtonElement( config.$button || $( '<a>' ) );
4581 };
4582
4583 /* Setup */
4584
4585 OO.initClass( OO.ui.mixin.ButtonElement );
4586
4587 /* Static Properties */
4588
4589 /**
4590 * Cancel mouse down events.
4591 *
4592 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4593 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4594 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4595 * parent widget.
4596 *
4597 * @static
4598 * @inheritable
4599 * @property {boolean}
4600 */
4601 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4602
4603 /* Events */
4604
4605 /**
4606 * A 'click' event is emitted when the button element is clicked.
4607 *
4608 * @event click
4609 */
4610
4611 /* Methods */
4612
4613 /**
4614 * Set the button element.
4615 *
4616 * This method is used to retarget a button mixin so that its functionality applies to
4617 * the specified button element instead of the one created by the class. If a button element
4618 * is already set, the method will remove the mixin’s effect on that element.
4619 *
4620 * @param {jQuery} $button Element to use as button
4621 */
4622 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4623 if ( this.$button ) {
4624 this.$button
4625 .removeClass( 'oo-ui-buttonElement-button' )
4626 .removeAttr( 'role accesskey' )
4627 .off( {
4628 mousedown: this.onMouseDownHandler,
4629 keydown: this.onKeyDownHandler,
4630 click: this.onClickHandler,
4631 keypress: this.onKeyPressHandler
4632 } );
4633 }
4634
4635 this.$button = $button
4636 .addClass( 'oo-ui-buttonElement-button' )
4637 .attr( { role: 'button' } )
4638 .on( {
4639 mousedown: this.onMouseDownHandler,
4640 keydown: this.onKeyDownHandler,
4641 click: this.onClickHandler,
4642 keypress: this.onKeyPressHandler
4643 } );
4644 };
4645
4646 /**
4647 * Handles mouse down events.
4648 *
4649 * @protected
4650 * @param {jQuery.Event} e Mouse down event
4651 */
4652 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4653 if ( this.isDisabled() || e.which !== 1 ) {
4654 return;
4655 }
4656 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4657 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4658 // reliably remove the pressed class
4659 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4660 // Prevent change of focus unless specifically configured otherwise
4661 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4662 return false;
4663 }
4664 };
4665
4666 /**
4667 * Handles mouse up events.
4668 *
4669 * @protected
4670 * @param {jQuery.Event} e Mouse up event
4671 */
4672 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4673 if ( this.isDisabled() || e.which !== 1 ) {
4674 return;
4675 }
4676 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4677 // Stop listening for mouseup, since we only needed this once
4678 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4679 };
4680
4681 /**
4682 * Handles mouse click events.
4683 *
4684 * @protected
4685 * @param {jQuery.Event} e Mouse click event
4686 * @fires click
4687 */
4688 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4689 if ( !this.isDisabled() && e.which === 1 ) {
4690 if ( this.emit( 'click' ) ) {
4691 return false;
4692 }
4693 }
4694 };
4695
4696 /**
4697 * Handles key down events.
4698 *
4699 * @protected
4700 * @param {jQuery.Event} e Key down event
4701 */
4702 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4703 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4704 return;
4705 }
4706 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4707 // Run the keyup handler no matter where the key is when the button is let go, so we can
4708 // reliably remove the pressed class
4709 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4710 };
4711
4712 /**
4713 * Handles key up events.
4714 *
4715 * @protected
4716 * @param {jQuery.Event} e Key up event
4717 */
4718 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4719 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4720 return;
4721 }
4722 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4723 // Stop listening for keyup, since we only needed this once
4724 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4725 };
4726
4727 /**
4728 * Handles key press events.
4729 *
4730 * @protected
4731 * @param {jQuery.Event} e Key press event
4732 * @fires click
4733 */
4734 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4735 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4736 if ( this.emit( 'click' ) ) {
4737 return false;
4738 }
4739 }
4740 };
4741
4742 /**
4743 * Check if button has a frame.
4744 *
4745 * @return {boolean} Button is framed
4746 */
4747 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4748 return this.framed;
4749 };
4750
4751 /**
4752 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4753 *
4754 * @param {boolean} [framed] Make button framed, omit to toggle
4755 * @chainable
4756 */
4757 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4758 framed = framed === undefined ? !this.framed : !!framed;
4759 if ( framed !== this.framed ) {
4760 this.framed = framed;
4761 this.$element
4762 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4763 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4764 this.updateThemeClasses();
4765 }
4766
4767 return this;
4768 };
4769
4770 /**
4771 * Set the button's active state.
4772 *
4773 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4774 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4775 * for other button types.
4776 *
4777 * @param {boolean} value Make button active
4778 * @chainable
4779 */
4780 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4781 this.active = !!value;
4782 this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active );
4783 return this;
4784 };
4785
4786 /**
4787 * Check if the button is active
4788 *
4789 * @return {boolean} The button is active
4790 */
4791 OO.ui.mixin.ButtonElement.prototype.isActive = function () {
4792 return this.active;
4793 };
4794
4795 /**
4796 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4797 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4798 * items from the group is done through the interface the class provides.
4799 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4800 *
4801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4802 *
4803 * @abstract
4804 * @class
4805 *
4806 * @constructor
4807 * @param {Object} [config] Configuration options
4808 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4809 * is omitted, the group element will use a generated `<div>`.
4810 */
4811 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4812 // Configuration initialization
4813 config = config || {};
4814
4815 // Properties
4816 this.$group = null;
4817 this.items = [];
4818 this.aggregateItemEvents = {};
4819
4820 // Initialization
4821 this.setGroupElement( config.$group || $( '<div>' ) );
4822 };
4823
4824 /* Methods */
4825
4826 /**
4827 * Set the group element.
4828 *
4829 * If an element is already set, items will be moved to the new element.
4830 *
4831 * @param {jQuery} $group Element to use as group
4832 */
4833 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4834 var i, len;
4835
4836 this.$group = $group;
4837 for ( i = 0, len = this.items.length; i < len; i++ ) {
4838 this.$group.append( this.items[ i ].$element );
4839 }
4840 };
4841
4842 /**
4843 * Check if a group contains no items.
4844 *
4845 * @return {boolean} Group is empty
4846 */
4847 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4848 return !this.items.length;
4849 };
4850
4851 /**
4852 * Get all items in the group.
4853 *
4854 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4855 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4856 * from a group).
4857 *
4858 * @return {OO.ui.Element[]} An array of items.
4859 */
4860 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4861 return this.items.slice( 0 );
4862 };
4863
4864 /**
4865 * Get an item by its data.
4866 *
4867 * Only the first item with matching data will be returned. To return all matching items,
4868 * use the #getItemsFromData method.
4869 *
4870 * @param {Object} data Item data to search for
4871 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4872 */
4873 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4874 var i, len, item,
4875 hash = OO.getHash( data );
4876
4877 for ( i = 0, len = this.items.length; i < len; i++ ) {
4878 item = this.items[ i ];
4879 if ( hash === OO.getHash( item.getData() ) ) {
4880 return item;
4881 }
4882 }
4883
4884 return null;
4885 };
4886
4887 /**
4888 * Get items by their data.
4889 *
4890 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4891 *
4892 * @param {Object} data Item data to search for
4893 * @return {OO.ui.Element[]} Items with equivalent data
4894 */
4895 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4896 var i, len, item,
4897 hash = OO.getHash( data ),
4898 items = [];
4899
4900 for ( i = 0, len = this.items.length; i < len; i++ ) {
4901 item = this.items[ i ];
4902 if ( hash === OO.getHash( item.getData() ) ) {
4903 items.push( item );
4904 }
4905 }
4906
4907 return items;
4908 };
4909
4910 /**
4911 * Aggregate the events emitted by the group.
4912 *
4913 * When events are aggregated, the group will listen to all contained items for the event,
4914 * and then emit the event under a new name. The new event will contain an additional leading
4915 * parameter containing the item that emitted the original event. Other arguments emitted from
4916 * the original event are passed through.
4917 *
4918 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4919 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4920 * A `null` value will remove aggregated events.
4921
4922 * @throws {Error} An error is thrown if aggregation already exists.
4923 */
4924 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4925 var i, len, item, add, remove, itemEvent, groupEvent;
4926
4927 for ( itemEvent in events ) {
4928 groupEvent = events[ itemEvent ];
4929
4930 // Remove existing aggregated event
4931 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4932 // Don't allow duplicate aggregations
4933 if ( groupEvent ) {
4934 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4935 }
4936 // Remove event aggregation from existing items
4937 for ( i = 0, len = this.items.length; i < len; i++ ) {
4938 item = this.items[ i ];
4939 if ( item.connect && item.disconnect ) {
4940 remove = {};
4941 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4942 item.disconnect( this, remove );
4943 }
4944 }
4945 // Prevent future items from aggregating event
4946 delete this.aggregateItemEvents[ itemEvent ];
4947 }
4948
4949 // Add new aggregate event
4950 if ( groupEvent ) {
4951 // Make future items aggregate event
4952 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4953 // Add event aggregation to existing items
4954 for ( i = 0, len = this.items.length; i < len; i++ ) {
4955 item = this.items[ i ];
4956 if ( item.connect && item.disconnect ) {
4957 add = {};
4958 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4959 item.connect( this, add );
4960 }
4961 }
4962 }
4963 }
4964 };
4965
4966 /**
4967 * Add items to the group.
4968 *
4969 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4970 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4971 *
4972 * @param {OO.ui.Element[]} items An array of items to add to the group
4973 * @param {number} [index] Index of the insertion point
4974 * @chainable
4975 */
4976 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4977 var i, len, item, event, events, currentIndex,
4978 itemElements = [];
4979
4980 for ( i = 0, len = items.length; i < len; i++ ) {
4981 item = items[ i ];
4982
4983 // Check if item exists then remove it first, effectively "moving" it
4984 currentIndex = this.items.indexOf( item );
4985 if ( currentIndex >= 0 ) {
4986 this.removeItems( [ item ] );
4987 // Adjust index to compensate for removal
4988 if ( currentIndex < index ) {
4989 index--;
4990 }
4991 }
4992 // Add the item
4993 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4994 events = {};
4995 for ( event in this.aggregateItemEvents ) {
4996 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4997 }
4998 item.connect( this, events );
4999 }
5000 item.setElementGroup( this );
5001 itemElements.push( item.$element.get( 0 ) );
5002 }
5003
5004 if ( index === undefined || index < 0 || index >= this.items.length ) {
5005 this.$group.append( itemElements );
5006 this.items.push.apply( this.items, items );
5007 } else if ( index === 0 ) {
5008 this.$group.prepend( itemElements );
5009 this.items.unshift.apply( this.items, items );
5010 } else {
5011 this.items[ index ].$element.before( itemElements );
5012 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
5013 }
5014
5015 return this;
5016 };
5017
5018 /**
5019 * Remove the specified items from a group.
5020 *
5021 * Removed items are detached (not removed) from the DOM so that they may be reused.
5022 * To remove all items from a group, you may wish to use the #clearItems method instead.
5023 *
5024 * @param {OO.ui.Element[]} items An array of items to remove
5025 * @chainable
5026 */
5027 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
5028 var i, len, item, index, remove, itemEvent;
5029
5030 // Remove specific items
5031 for ( i = 0, len = items.length; i < len; i++ ) {
5032 item = items[ i ];
5033 index = this.items.indexOf( item );
5034 if ( index !== -1 ) {
5035 if (
5036 item.connect && item.disconnect &&
5037 !$.isEmptyObject( this.aggregateItemEvents )
5038 ) {
5039 remove = {};
5040 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5041 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5042 }
5043 item.disconnect( this, remove );
5044 }
5045 item.setElementGroup( null );
5046 this.items.splice( index, 1 );
5047 item.$element.detach();
5048 }
5049 }
5050
5051 return this;
5052 };
5053
5054 /**
5055 * Clear all items from the group.
5056 *
5057 * Cleared items are detached from the DOM, not removed, so that they may be reused.
5058 * To remove only a subset of items from a group, use the #removeItems method.
5059 *
5060 * @chainable
5061 */
5062 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
5063 var i, len, item, remove, itemEvent;
5064
5065 // Remove all items
5066 for ( i = 0, len = this.items.length; i < len; i++ ) {
5067 item = this.items[ i ];
5068 if (
5069 item.connect && item.disconnect &&
5070 !$.isEmptyObject( this.aggregateItemEvents )
5071 ) {
5072 remove = {};
5073 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
5074 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
5075 }
5076 item.disconnect( this, remove );
5077 }
5078 item.setElementGroup( null );
5079 item.$element.detach();
5080 }
5081
5082 this.items = [];
5083 return this;
5084 };
5085
5086 /**
5087 * DraggableElement is a mixin class used to create elements that can be clicked
5088 * and dragged by a mouse to a new position within a group. This class must be used
5089 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
5090 * the draggable elements.
5091 *
5092 * @abstract
5093 * @class
5094 *
5095 * @constructor
5096 */
5097 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
5098 // Properties
5099 this.index = null;
5100
5101 // Initialize and events
5102 this.$element
5103 .attr( 'draggable', true )
5104 .addClass( 'oo-ui-draggableElement' )
5105 .on( {
5106 dragstart: this.onDragStart.bind( this ),
5107 dragover: this.onDragOver.bind( this ),
5108 dragend: this.onDragEnd.bind( this ),
5109 drop: this.onDrop.bind( this )
5110 } );
5111 };
5112
5113 OO.initClass( OO.ui.mixin.DraggableElement );
5114
5115 /* Events */
5116
5117 /**
5118 * @event dragstart
5119 *
5120 * A dragstart event is emitted when the user clicks and begins dragging an item.
5121 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
5122 */
5123
5124 /**
5125 * @event dragend
5126 * A dragend event is emitted when the user drags an item and releases the mouse,
5127 * thus terminating the drag operation.
5128 */
5129
5130 /**
5131 * @event drop
5132 * A drop event is emitted when the user drags an item and then releases the mouse button
5133 * over a valid target.
5134 */
5135
5136 /* Static Properties */
5137
5138 /**
5139 * @inheritdoc OO.ui.mixin.ButtonElement
5140 */
5141 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
5142
5143 /* Methods */
5144
5145 /**
5146 * Respond to dragstart event.
5147 *
5148 * @private
5149 * @param {jQuery.Event} event jQuery event
5150 * @fires dragstart
5151 */
5152 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
5153 var dataTransfer = e.originalEvent.dataTransfer;
5154 // Define drop effect
5155 dataTransfer.dropEffect = 'none';
5156 dataTransfer.effectAllowed = 'move';
5157 // Support: Firefox
5158 // We must set up a dataTransfer data property or Firefox seems to
5159 // ignore the fact the element is draggable.
5160 try {
5161 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5162 } catch ( err ) {
5163 // The above is only for Firefox. Move on if it fails.
5164 }
5165 // Add dragging class
5166 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
5167 // Emit event
5168 this.emit( 'dragstart', this );
5169 return true;
5170 };
5171
5172 /**
5173 * Respond to dragend event.
5174 *
5175 * @private
5176 * @fires dragend
5177 */
5178 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
5179 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
5180 this.emit( 'dragend' );
5181 };
5182
5183 /**
5184 * Handle drop event.
5185 *
5186 * @private
5187 * @param {jQuery.Event} event jQuery event
5188 * @fires drop
5189 */
5190 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
5191 e.preventDefault();
5192 this.emit( 'drop', e );
5193 };
5194
5195 /**
5196 * In order for drag/drop to work, the dragover event must
5197 * return false and stop propogation.
5198 *
5199 * @private
5200 */
5201 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
5202 e.preventDefault();
5203 };
5204
5205 /**
5206 * Set item index.
5207 * Store it in the DOM so we can access from the widget drag event
5208 *
5209 * @private
5210 * @param {number} Item index
5211 */
5212 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
5213 if ( this.index !== index ) {
5214 this.index = index;
5215 this.$element.data( 'index', index );
5216 }
5217 };
5218
5219 /**
5220 * Get item index
5221 *
5222 * @private
5223 * @return {number} Item index
5224 */
5225 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5226 return this.index;
5227 };
5228
5229 /**
5230 * DraggableGroupElement is a mixin class used to create a group element to
5231 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5232 * The class is used with OO.ui.mixin.DraggableElement.
5233 *
5234 * @abstract
5235 * @class
5236 * @mixins OO.ui.mixin.GroupElement
5237 *
5238 * @constructor
5239 * @param {Object} [config] Configuration options
5240 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5241 * should match the layout of the items. Items displayed in a single row
5242 * or in several rows should use horizontal orientation. The vertical orientation should only be
5243 * used when the items are displayed in a single column. Defaults to 'vertical'
5244 */
5245 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5246 // Configuration initialization
5247 config = config || {};
5248
5249 // Parent constructor
5250 OO.ui.mixin.GroupElement.call( this, config );
5251
5252 // Properties
5253 this.orientation = config.orientation || 'vertical';
5254 this.dragItem = null;
5255 this.itemDragOver = null;
5256 this.itemKeys = {};
5257 this.sideInsertion = '';
5258
5259 // Events
5260 this.aggregate( {
5261 dragstart: 'itemDragStart',
5262 dragend: 'itemDragEnd',
5263 drop: 'itemDrop'
5264 } );
5265 this.connect( this, {
5266 itemDragStart: 'onItemDragStart',
5267 itemDrop: 'onItemDrop',
5268 itemDragEnd: 'onItemDragEnd'
5269 } );
5270 this.$element.on( {
5271 dragover: this.onDragOver.bind( this ),
5272 dragleave: this.onDragLeave.bind( this )
5273 } );
5274
5275 // Initialize
5276 if ( Array.isArray( config.items ) ) {
5277 this.addItems( config.items );
5278 }
5279 this.$placeholder = $( '<div>' )
5280 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5281 this.$element
5282 .addClass( 'oo-ui-draggableGroupElement' )
5283 .append( this.$status )
5284 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5285 .prepend( this.$placeholder );
5286 };
5287
5288 /* Setup */
5289 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5290
5291 /* Events */
5292
5293 /**
5294 * A 'reorder' event is emitted when the order of items in the group changes.
5295 *
5296 * @event reorder
5297 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5298 * @param {number} [newIndex] New index for the item
5299 */
5300
5301 /* Methods */
5302
5303 /**
5304 * Respond to item drag start event
5305 *
5306 * @private
5307 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5308 */
5309 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5310 var i, len;
5311
5312 // Map the index of each object
5313 for ( i = 0, len = this.items.length; i < len; i++ ) {
5314 this.items[ i ].setIndex( i );
5315 }
5316
5317 if ( this.orientation === 'horizontal' ) {
5318 // Set the height of the indicator
5319 this.$placeholder.css( {
5320 height: item.$element.outerHeight(),
5321 width: 2
5322 } );
5323 } else {
5324 // Set the width of the indicator
5325 this.$placeholder.css( {
5326 height: 2,
5327 width: item.$element.outerWidth()
5328 } );
5329 }
5330 this.setDragItem( item );
5331 };
5332
5333 /**
5334 * Respond to item drag end event
5335 *
5336 * @private
5337 */
5338 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5339 this.unsetDragItem();
5340 return false;
5341 };
5342
5343 /**
5344 * Handle drop event and switch the order of the items accordingly
5345 *
5346 * @private
5347 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5348 * @fires reorder
5349 */
5350 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5351 var toIndex = item.getIndex();
5352 // Check if the dropped item is from the current group
5353 // TODO: Figure out a way to configure a list of legally droppable
5354 // elements even if they are not yet in the list
5355 if ( this.getDragItem() ) {
5356 // If the insertion point is 'after', the insertion index
5357 // is shifted to the right (or to the left in RTL, hence 'after')
5358 if ( this.sideInsertion === 'after' ) {
5359 toIndex++;
5360 }
5361 // Emit change event
5362 this.emit( 'reorder', this.getDragItem(), toIndex );
5363 }
5364 this.unsetDragItem();
5365 // Return false to prevent propogation
5366 return false;
5367 };
5368
5369 /**
5370 * Handle dragleave event.
5371 *
5372 * @private
5373 */
5374 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5375 // This means the item was dragged outside the widget
5376 this.$placeholder
5377 .css( 'left', 0 )
5378 .addClass( 'oo-ui-element-hidden' );
5379 };
5380
5381 /**
5382 * Respond to dragover event
5383 *
5384 * @private
5385 * @param {jQuery.Event} event Event details
5386 */
5387 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5388 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5389 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5390 clientX = e.originalEvent.clientX,
5391 clientY = e.originalEvent.clientY;
5392
5393 // Get the OptionWidget item we are dragging over
5394 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5395 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5396 if ( $optionWidget[ 0 ] ) {
5397 itemOffset = $optionWidget.offset();
5398 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5399 itemPosition = $optionWidget.position();
5400 itemIndex = $optionWidget.data( 'index' );
5401 }
5402
5403 if (
5404 itemOffset &&
5405 this.isDragging() &&
5406 itemIndex !== this.getDragItem().getIndex()
5407 ) {
5408 if ( this.orientation === 'horizontal' ) {
5409 // Calculate where the mouse is relative to the item width
5410 itemSize = itemBoundingRect.width;
5411 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5412 dragPosition = clientX;
5413 // Which side of the item we hover over will dictate
5414 // where the placeholder will appear, on the left or
5415 // on the right
5416 cssOutput = {
5417 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5418 top: itemPosition.top
5419 };
5420 } else {
5421 // Calculate where the mouse is relative to the item height
5422 itemSize = itemBoundingRect.height;
5423 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5424 dragPosition = clientY;
5425 // Which side of the item we hover over will dictate
5426 // where the placeholder will appear, on the top or
5427 // on the bottom
5428 cssOutput = {
5429 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5430 left: itemPosition.left
5431 };
5432 }
5433 // Store whether we are before or after an item to rearrange
5434 // For horizontal layout, we need to account for RTL, as this is flipped
5435 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5436 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5437 } else {
5438 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5439 }
5440 // Add drop indicator between objects
5441 this.$placeholder
5442 .css( cssOutput )
5443 .removeClass( 'oo-ui-element-hidden' );
5444 } else {
5445 // This means the item was dragged outside the widget
5446 this.$placeholder
5447 .css( 'left', 0 )
5448 .addClass( 'oo-ui-element-hidden' );
5449 }
5450 // Prevent default
5451 e.preventDefault();
5452 };
5453
5454 /**
5455 * Set a dragged item
5456 *
5457 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5458 */
5459 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5460 this.dragItem = item;
5461 };
5462
5463 /**
5464 * Unset the current dragged item
5465 */
5466 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5467 this.dragItem = null;
5468 this.itemDragOver = null;
5469 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5470 this.sideInsertion = '';
5471 };
5472
5473 /**
5474 * Get the item that is currently being dragged.
5475 *
5476 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5477 */
5478 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5479 return this.dragItem;
5480 };
5481
5482 /**
5483 * Check if an item in the group is currently being dragged.
5484 *
5485 * @return {Boolean} Item is being dragged
5486 */
5487 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5488 return this.getDragItem() !== null;
5489 };
5490
5491 /**
5492 * IconElement is often mixed into other classes to generate an icon.
5493 * Icons are graphics, about the size of normal text. They are used to aid the user
5494 * in locating a control or to convey information in a space-efficient way. See the
5495 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5496 * included in the library.
5497 *
5498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5499 *
5500 * @abstract
5501 * @class
5502 *
5503 * @constructor
5504 * @param {Object} [config] Configuration options
5505 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5506 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5507 * the icon element be set to an existing icon instead of the one generated by this class, set a
5508 * value using a jQuery selection. For example:
5509 *
5510 * // Use a <div> tag instead of a <span>
5511 * $icon: $("<div>")
5512 * // Use an existing icon element instead of the one generated by the class
5513 * $icon: this.$element
5514 * // Use an icon element from a child widget
5515 * $icon: this.childwidget.$element
5516 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5517 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5518 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5519 * by the user's language.
5520 *
5521 * Example of an i18n map:
5522 *
5523 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5524 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5525 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5526 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5527 * text. The icon title is displayed when users move the mouse over the icon.
5528 */
5529 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5530 // Configuration initialization
5531 config = config || {};
5532
5533 // Properties
5534 this.$icon = null;
5535 this.icon = null;
5536 this.iconTitle = null;
5537
5538 // Initialization
5539 this.setIcon( config.icon || this.constructor.static.icon );
5540 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5541 this.setIconElement( config.$icon || $( '<span>' ) );
5542 };
5543
5544 /* Setup */
5545
5546 OO.initClass( OO.ui.mixin.IconElement );
5547
5548 /* Static Properties */
5549
5550 /**
5551 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5552 * for i18n purposes and contains a `default` icon name and additional names keyed by
5553 * language code. The `default` name is used when no icon is keyed by the user's language.
5554 *
5555 * Example of an i18n map:
5556 *
5557 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5558 *
5559 * Note: the static property will be overridden if the #icon configuration is used.
5560 *
5561 * @static
5562 * @inheritable
5563 * @property {Object|string}
5564 */
5565 OO.ui.mixin.IconElement.static.icon = null;
5566
5567 /**
5568 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5569 * function that returns title text, or `null` for no title.
5570 *
5571 * The static property will be overridden if the #iconTitle configuration is used.
5572 *
5573 * @static
5574 * @inheritable
5575 * @property {string|Function|null}
5576 */
5577 OO.ui.mixin.IconElement.static.iconTitle = null;
5578
5579 /* Methods */
5580
5581 /**
5582 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5583 * applies to the specified icon element instead of the one created by the class. If an icon
5584 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5585 * and mixin methods will no longer affect the element.
5586 *
5587 * @param {jQuery} $icon Element to use as icon
5588 */
5589 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5590 if ( this.$icon ) {
5591 this.$icon
5592 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5593 .removeAttr( 'title' );
5594 }
5595
5596 this.$icon = $icon
5597 .addClass( 'oo-ui-iconElement-icon' )
5598 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5599 if ( this.iconTitle !== null ) {
5600 this.$icon.attr( 'title', this.iconTitle );
5601 }
5602
5603 this.updateThemeClasses();
5604 };
5605
5606 /**
5607 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5608 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5609 * for an example.
5610 *
5611 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5612 * by language code, or `null` to remove the icon.
5613 * @chainable
5614 */
5615 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5616 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5617 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5618
5619 if ( this.icon !== icon ) {
5620 if ( this.$icon ) {
5621 if ( this.icon !== null ) {
5622 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5623 }
5624 if ( icon !== null ) {
5625 this.$icon.addClass( 'oo-ui-icon-' + icon );
5626 }
5627 }
5628 this.icon = icon;
5629 }
5630
5631 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5632 this.updateThemeClasses();
5633
5634 return this;
5635 };
5636
5637 /**
5638 * Set the icon title. Use `null` to remove the title.
5639 *
5640 * @param {string|Function|null} iconTitle A text string used as the icon title,
5641 * a function that returns title text, or `null` for no title.
5642 * @chainable
5643 */
5644 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5645 iconTitle = typeof iconTitle === 'function' ||
5646 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5647 OO.ui.resolveMsg( iconTitle ) : null;
5648
5649 if ( this.iconTitle !== iconTitle ) {
5650 this.iconTitle = iconTitle;
5651 if ( this.$icon ) {
5652 if ( this.iconTitle !== null ) {
5653 this.$icon.attr( 'title', iconTitle );
5654 } else {
5655 this.$icon.removeAttr( 'title' );
5656 }
5657 }
5658 }
5659
5660 return this;
5661 };
5662
5663 /**
5664 * Get the symbolic name of the icon.
5665 *
5666 * @return {string} Icon name
5667 */
5668 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5669 return this.icon;
5670 };
5671
5672 /**
5673 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5674 *
5675 * @return {string} Icon title text
5676 */
5677 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5678 return this.iconTitle;
5679 };
5680
5681 /**
5682 * IndicatorElement is often mixed into other classes to generate an indicator.
5683 * Indicators are small graphics that are generally used in two ways:
5684 *
5685 * - To draw attention to the status of an item. For example, an indicator might be
5686 * used to show that an item in a list has errors that need to be resolved.
5687 * - To clarify the function of a control that acts in an exceptional way (a button
5688 * that opens a menu instead of performing an action directly, for example).
5689 *
5690 * For a list of indicators included in the library, please see the
5691 * [OOjs UI documentation on MediaWiki] [1].
5692 *
5693 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5694 *
5695 * @abstract
5696 * @class
5697 *
5698 * @constructor
5699 * @param {Object} [config] Configuration options
5700 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5701 * configuration is omitted, the indicator element will use a generated `<span>`.
5702 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5703 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5704 * in the library.
5705 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5706 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5707 * or a function that returns title text. The indicator title is displayed when users move
5708 * the mouse over the indicator.
5709 */
5710 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5711 // Configuration initialization
5712 config = config || {};
5713
5714 // Properties
5715 this.$indicator = null;
5716 this.indicator = null;
5717 this.indicatorTitle = null;
5718
5719 // Initialization
5720 this.setIndicator( config.indicator || this.constructor.static.indicator );
5721 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5722 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5723 };
5724
5725 /* Setup */
5726
5727 OO.initClass( OO.ui.mixin.IndicatorElement );
5728
5729 /* Static Properties */
5730
5731 /**
5732 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5733 * The static property will be overridden if the #indicator configuration is used.
5734 *
5735 * @static
5736 * @inheritable
5737 * @property {string|null}
5738 */
5739 OO.ui.mixin.IndicatorElement.static.indicator = null;
5740
5741 /**
5742 * A text string used as the indicator title, a function that returns title text, or `null`
5743 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5744 *
5745 * @static
5746 * @inheritable
5747 * @property {string|Function|null}
5748 */
5749 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5750
5751 /* Methods */
5752
5753 /**
5754 * Set the indicator element.
5755 *
5756 * If an element is already set, it will be cleaned up before setting up the new element.
5757 *
5758 * @param {jQuery} $indicator Element to use as indicator
5759 */
5760 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5761 if ( this.$indicator ) {
5762 this.$indicator
5763 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5764 .removeAttr( 'title' );
5765 }
5766
5767 this.$indicator = $indicator
5768 .addClass( 'oo-ui-indicatorElement-indicator' )
5769 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5770 if ( this.indicatorTitle !== null ) {
5771 this.$indicator.attr( 'title', this.indicatorTitle );
5772 }
5773
5774 this.updateThemeClasses();
5775 };
5776
5777 /**
5778 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5779 *
5780 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5781 * @chainable
5782 */
5783 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5784 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5785
5786 if ( this.indicator !== indicator ) {
5787 if ( this.$indicator ) {
5788 if ( this.indicator !== null ) {
5789 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5790 }
5791 if ( indicator !== null ) {
5792 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5793 }
5794 }
5795 this.indicator = indicator;
5796 }
5797
5798 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5799 this.updateThemeClasses();
5800
5801 return this;
5802 };
5803
5804 /**
5805 * Set the indicator title.
5806 *
5807 * The title is displayed when a user moves the mouse over the indicator.
5808 *
5809 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5810 * `null` for no indicator title
5811 * @chainable
5812 */
5813 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5814 indicatorTitle = typeof indicatorTitle === 'function' ||
5815 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5816 OO.ui.resolveMsg( indicatorTitle ) : null;
5817
5818 if ( this.indicatorTitle !== indicatorTitle ) {
5819 this.indicatorTitle = indicatorTitle;
5820 if ( this.$indicator ) {
5821 if ( this.indicatorTitle !== null ) {
5822 this.$indicator.attr( 'title', indicatorTitle );
5823 } else {
5824 this.$indicator.removeAttr( 'title' );
5825 }
5826 }
5827 }
5828
5829 return this;
5830 };
5831
5832 /**
5833 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5834 *
5835 * @return {string} Symbolic name of indicator
5836 */
5837 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5838 return this.indicator;
5839 };
5840
5841 /**
5842 * Get the indicator title.
5843 *
5844 * The title is displayed when a user moves the mouse over the indicator.
5845 *
5846 * @return {string} Indicator title text
5847 */
5848 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5849 return this.indicatorTitle;
5850 };
5851
5852 /**
5853 * LabelElement is often mixed into other classes to generate a label, which
5854 * helps identify the function of an interface element.
5855 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5856 *
5857 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5858 *
5859 * @abstract
5860 * @class
5861 *
5862 * @constructor
5863 * @param {Object} [config] Configuration options
5864 * @cfg {jQuery} [$label] The label element created by the class. If this
5865 * configuration is omitted, the label element will use a generated `<span>`.
5866 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5867 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5868 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5869 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5870 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5871 * The label will be truncated to fit if necessary.
5872 */
5873 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5874 // Configuration initialization
5875 config = config || {};
5876
5877 // Properties
5878 this.$label = null;
5879 this.label = null;
5880 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5881
5882 // Initialization
5883 this.setLabel( config.label || this.constructor.static.label );
5884 this.setLabelElement( config.$label || $( '<span>' ) );
5885 };
5886
5887 /* Setup */
5888
5889 OO.initClass( OO.ui.mixin.LabelElement );
5890
5891 /* Events */
5892
5893 /**
5894 * @event labelChange
5895 * @param {string} value
5896 */
5897
5898 /* Static Properties */
5899
5900 /**
5901 * The label text. The label can be specified as a plaintext string, a function that will
5902 * produce a string in the future, or `null` for no label. The static value will
5903 * be overridden if a label is specified with the #label config option.
5904 *
5905 * @static
5906 * @inheritable
5907 * @property {string|Function|null}
5908 */
5909 OO.ui.mixin.LabelElement.static.label = null;
5910
5911 /* Methods */
5912
5913 /**
5914 * Set the label element.
5915 *
5916 * If an element is already set, it will be cleaned up before setting up the new element.
5917 *
5918 * @param {jQuery} $label Element to use as label
5919 */
5920 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5921 if ( this.$label ) {
5922 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5923 }
5924
5925 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5926 this.setLabelContent( this.label );
5927 };
5928
5929 /**
5930 * Set the label.
5931 *
5932 * An empty string will result in the label being hidden. A string containing only whitespace will
5933 * be converted to a single `&nbsp;`.
5934 *
5935 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5936 * text; or null for no label
5937 * @chainable
5938 */
5939 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5940 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5941 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5942
5943 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5944
5945 if ( this.label !== label ) {
5946 if ( this.$label ) {
5947 this.setLabelContent( label );
5948 }
5949 this.label = label;
5950 this.emit( 'labelChange' );
5951 }
5952
5953 return this;
5954 };
5955
5956 /**
5957 * Get the label.
5958 *
5959 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5960 * text; or null for no label
5961 */
5962 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5963 return this.label;
5964 };
5965
5966 /**
5967 * Fit the label.
5968 *
5969 * @chainable
5970 */
5971 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5972 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5973 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5974 }
5975
5976 return this;
5977 };
5978
5979 /**
5980 * Set the content of the label.
5981 *
5982 * Do not call this method until after the label element has been set by #setLabelElement.
5983 *
5984 * @private
5985 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5986 * text; or null for no label
5987 */
5988 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5989 if ( typeof label === 'string' ) {
5990 if ( label.match( /^\s*$/ ) ) {
5991 // Convert whitespace only string to a single non-breaking space
5992 this.$label.html( '&nbsp;' );
5993 } else {
5994 this.$label.text( label );
5995 }
5996 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5997 this.$label.html( label.toString() );
5998 } else if ( label instanceof jQuery ) {
5999 this.$label.empty().append( label );
6000 } else {
6001 this.$label.empty();
6002 }
6003 };
6004
6005 /**
6006 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
6007 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
6008 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
6009 * from the lookup menu, that value becomes the value of the input field.
6010 *
6011 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
6012 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
6013 * re-enable lookups.
6014 *
6015 * See the [OOjs UI demos][1] for an example.
6016 *
6017 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
6018 *
6019 * @class
6020 * @abstract
6021 *
6022 * @constructor
6023 * @param {Object} [config] Configuration options
6024 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
6025 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
6026 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
6027 * By default, the lookup menu is not generated and displayed until the user begins to type.
6028 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
6029 * take it over into the input with simply pressing return) automatically or not.
6030 */
6031 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
6032 // Configuration initialization
6033 config = $.extend( { highlightFirst: true }, config );
6034
6035 // Mixin constructors
6036 OO.ui.mixin.RequestManager.call( this, config );
6037
6038 // Properties
6039 this.$overlay = config.$overlay || this.$element;
6040 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
6041 widget: this,
6042 input: this,
6043 $container: config.$container || this.$element
6044 } );
6045
6046 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
6047
6048 this.lookupsDisabled = false;
6049 this.lookupInputFocused = false;
6050 this.lookupHighlightFirstItem = config.highlightFirst;
6051
6052 // Events
6053 this.$input.on( {
6054 focus: this.onLookupInputFocus.bind( this ),
6055 blur: this.onLookupInputBlur.bind( this ),
6056 mousedown: this.onLookupInputMouseDown.bind( this )
6057 } );
6058 this.connect( this, { change: 'onLookupInputChange' } );
6059 this.lookupMenu.connect( this, {
6060 toggle: 'onLookupMenuToggle',
6061 choose: 'onLookupMenuItemChoose'
6062 } );
6063
6064 // Initialization
6065 this.$element.addClass( 'oo-ui-lookupElement' );
6066 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
6067 this.$overlay.append( this.lookupMenu.$element );
6068 };
6069
6070 /* Setup */
6071
6072 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
6073
6074 /* Methods */
6075
6076 /**
6077 * Handle input focus event.
6078 *
6079 * @protected
6080 * @param {jQuery.Event} e Input focus event
6081 */
6082 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
6083 this.lookupInputFocused = true;
6084 this.populateLookupMenu();
6085 };
6086
6087 /**
6088 * Handle input blur event.
6089 *
6090 * @protected
6091 * @param {jQuery.Event} e Input blur event
6092 */
6093 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
6094 this.closeLookupMenu();
6095 this.lookupInputFocused = false;
6096 };
6097
6098 /**
6099 * Handle input mouse down event.
6100 *
6101 * @protected
6102 * @param {jQuery.Event} e Input mouse down event
6103 */
6104 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
6105 // Only open the menu if the input was already focused.
6106 // This way we allow the user to open the menu again after closing it with Esc
6107 // by clicking in the input. Opening (and populating) the menu when initially
6108 // clicking into the input is handled by the focus handler.
6109 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
6110 this.populateLookupMenu();
6111 }
6112 };
6113
6114 /**
6115 * Handle input change event.
6116 *
6117 * @protected
6118 * @param {string} value New input value
6119 */
6120 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
6121 if ( this.lookupInputFocused ) {
6122 this.populateLookupMenu();
6123 }
6124 };
6125
6126 /**
6127 * Handle the lookup menu being shown/hidden.
6128 *
6129 * @protected
6130 * @param {boolean} visible Whether the lookup menu is now visible.
6131 */
6132 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
6133 if ( !visible ) {
6134 // When the menu is hidden, abort any active request and clear the menu.
6135 // This has to be done here in addition to closeLookupMenu(), because
6136 // MenuSelectWidget will close itself when the user presses Esc.
6137 this.abortLookupRequest();
6138 this.lookupMenu.clearItems();
6139 }
6140 };
6141
6142 /**
6143 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
6144 *
6145 * @protected
6146 * @param {OO.ui.MenuOptionWidget} item Selected item
6147 */
6148 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
6149 this.setValue( item.getData() );
6150 };
6151
6152 /**
6153 * Get lookup menu.
6154 *
6155 * @private
6156 * @return {OO.ui.FloatingMenuSelectWidget}
6157 */
6158 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
6159 return this.lookupMenu;
6160 };
6161
6162 /**
6163 * Disable or re-enable lookups.
6164 *
6165 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6166 *
6167 * @param {boolean} disabled Disable lookups
6168 */
6169 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
6170 this.lookupsDisabled = !!disabled;
6171 };
6172
6173 /**
6174 * Open the menu. If there are no entries in the menu, this does nothing.
6175 *
6176 * @private
6177 * @chainable
6178 */
6179 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
6180 if ( !this.lookupMenu.isEmpty() ) {
6181 this.lookupMenu.toggle( true );
6182 }
6183 return this;
6184 };
6185
6186 /**
6187 * Close the menu, empty it, and abort any pending request.
6188 *
6189 * @private
6190 * @chainable
6191 */
6192 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
6193 this.lookupMenu.toggle( false );
6194 this.abortLookupRequest();
6195 this.lookupMenu.clearItems();
6196 return this;
6197 };
6198
6199 /**
6200 * Request menu items based on the input's current value, and when they arrive,
6201 * populate the menu with these items and show the menu.
6202 *
6203 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6204 *
6205 * @private
6206 * @chainable
6207 */
6208 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
6209 var widget = this,
6210 value = this.getValue();
6211
6212 if ( this.lookupsDisabled || this.isReadOnly() ) {
6213 return;
6214 }
6215
6216 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6217 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
6218 this.closeLookupMenu();
6219 // Skip population if there is already a request pending for the current value
6220 } else if ( value !== this.lookupQuery ) {
6221 this.getLookupMenuItems()
6222 .done( function ( items ) {
6223 widget.lookupMenu.clearItems();
6224 if ( items.length ) {
6225 widget.lookupMenu
6226 .addItems( items )
6227 .toggle( true );
6228 widget.initializeLookupMenuSelection();
6229 } else {
6230 widget.lookupMenu.toggle( false );
6231 }
6232 } )
6233 .fail( function () {
6234 widget.lookupMenu.clearItems();
6235 } );
6236 }
6237
6238 return this;
6239 };
6240
6241 /**
6242 * Highlight the first selectable item in the menu, if configured.
6243 *
6244 * @private
6245 * @chainable
6246 */
6247 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6248 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
6249 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6250 }
6251 };
6252
6253 /**
6254 * Get lookup menu items for the current query.
6255 *
6256 * @private
6257 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6258 * the done event. If the request was aborted to make way for a subsequent request, this promise
6259 * will not be rejected: it will remain pending forever.
6260 */
6261 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6262 return this.getRequestData().then( function ( data ) {
6263 return this.getLookupMenuOptionsFromData( data );
6264 }.bind( this ) );
6265 };
6266
6267 /**
6268 * Abort the currently pending lookup request, if any.
6269 *
6270 * @private
6271 */
6272 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6273 this.abortRequest();
6274 };
6275
6276 /**
6277 * Get a new request object of the current lookup query value.
6278 *
6279 * @protected
6280 * @method
6281 * @abstract
6282 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6283 */
6284 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
6285
6286 /**
6287 * Pre-process data returned by the request from #getLookupRequest.
6288 *
6289 * The return value of this function will be cached, and any further queries for the given value
6290 * will use the cache rather than doing API requests.
6291 *
6292 * @protected
6293 * @method
6294 * @abstract
6295 * @param {Mixed} response Response from server
6296 * @return {Mixed} Cached result data
6297 */
6298 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
6299
6300 /**
6301 * Get a list of menu option widgets from the (possibly cached) data returned by
6302 * #getLookupCacheDataFromResponse.
6303 *
6304 * @protected
6305 * @method
6306 * @abstract
6307 * @param {Mixed} data Cached result data, usually an array
6308 * @return {OO.ui.MenuOptionWidget[]} Menu items
6309 */
6310 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
6311
6312 /**
6313 * Set the read-only state of the widget.
6314 *
6315 * This will also disable/enable the lookups functionality.
6316 *
6317 * @param {boolean} readOnly Make input read-only
6318 * @chainable
6319 */
6320 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6321 // Parent method
6322 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6323 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6324
6325 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6326 if ( this.isReadOnly() && this.lookupMenu ) {
6327 this.closeLookupMenu();
6328 }
6329
6330 return this;
6331 };
6332
6333 /**
6334 * @inheritdoc OO.ui.mixin.RequestManager
6335 */
6336 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
6337 return this.getValue();
6338 };
6339
6340 /**
6341 * @inheritdoc OO.ui.mixin.RequestManager
6342 */
6343 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
6344 return this.getLookupRequest();
6345 };
6346
6347 /**
6348 * @inheritdoc OO.ui.mixin.RequestManager
6349 */
6350 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
6351 return this.getLookupCacheDataFromResponse( response );
6352 };
6353
6354 /**
6355 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6356 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6357 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6358 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6359 *
6360 * @abstract
6361 * @class
6362 *
6363 * @constructor
6364 * @param {Object} [config] Configuration options
6365 * @cfg {Object} [popup] Configuration to pass to popup
6366 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6367 */
6368 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6369 // Configuration initialization
6370 config = config || {};
6371
6372 // Properties
6373 this.popup = new OO.ui.PopupWidget( $.extend(
6374 { autoClose: true },
6375 config.popup,
6376 { $autoCloseIgnore: this.$element }
6377 ) );
6378 };
6379
6380 /* Methods */
6381
6382 /**
6383 * Get popup.
6384 *
6385 * @return {OO.ui.PopupWidget} Popup widget
6386 */
6387 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6388 return this.popup;
6389 };
6390
6391 /**
6392 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6393 * additional functionality to an element created by another class. The class provides
6394 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6395 * which are used to customize the look and feel of a widget to better describe its
6396 * importance and functionality.
6397 *
6398 * The library currently contains the following styling flags for general use:
6399 *
6400 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6401 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6402 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6403 *
6404 * The flags affect the appearance of the buttons:
6405 *
6406 * @example
6407 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6408 * var button1 = new OO.ui.ButtonWidget( {
6409 * label: 'Constructive',
6410 * flags: 'constructive'
6411 * } );
6412 * var button2 = new OO.ui.ButtonWidget( {
6413 * label: 'Destructive',
6414 * flags: 'destructive'
6415 * } );
6416 * var button3 = new OO.ui.ButtonWidget( {
6417 * label: 'Progressive',
6418 * flags: 'progressive'
6419 * } );
6420 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6421 *
6422 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6423 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6424 *
6425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6426 *
6427 * @abstract
6428 * @class
6429 *
6430 * @constructor
6431 * @param {Object} [config] Configuration options
6432 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6433 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6434 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6435 * @cfg {jQuery} [$flagged] The flagged element. By default,
6436 * the flagged functionality is applied to the element created by the class ($element).
6437 * If a different element is specified, the flagged functionality will be applied to it instead.
6438 */
6439 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6440 // Configuration initialization
6441 config = config || {};
6442
6443 // Properties
6444 this.flags = {};
6445 this.$flagged = null;
6446
6447 // Initialization
6448 this.setFlags( config.flags );
6449 this.setFlaggedElement( config.$flagged || this.$element );
6450 };
6451
6452 /* Events */
6453
6454 /**
6455 * @event flag
6456 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6457 * parameter contains the name of each modified flag and indicates whether it was
6458 * added or removed.
6459 *
6460 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6461 * that the flag was added, `false` that the flag was removed.
6462 */
6463
6464 /* Methods */
6465
6466 /**
6467 * Set the flagged element.
6468 *
6469 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6470 * If an element is already set, the method will remove the mixin’s effect on that element.
6471 *
6472 * @param {jQuery} $flagged Element that should be flagged
6473 */
6474 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6475 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6476 return 'oo-ui-flaggedElement-' + flag;
6477 } ).join( ' ' );
6478
6479 if ( this.$flagged ) {
6480 this.$flagged.removeClass( classNames );
6481 }
6482
6483 this.$flagged = $flagged.addClass( classNames );
6484 };
6485
6486 /**
6487 * Check if the specified flag is set.
6488 *
6489 * @param {string} flag Name of flag
6490 * @return {boolean} The flag is set
6491 */
6492 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6493 // This may be called before the constructor, thus before this.flags is set
6494 return this.flags && ( flag in this.flags );
6495 };
6496
6497 /**
6498 * Get the names of all flags set.
6499 *
6500 * @return {string[]} Flag names
6501 */
6502 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6503 // This may be called before the constructor, thus before this.flags is set
6504 return Object.keys( this.flags || {} );
6505 };
6506
6507 /**
6508 * Clear all flags.
6509 *
6510 * @chainable
6511 * @fires flag
6512 */
6513 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6514 var flag, className,
6515 changes = {},
6516 remove = [],
6517 classPrefix = 'oo-ui-flaggedElement-';
6518
6519 for ( flag in this.flags ) {
6520 className = classPrefix + flag;
6521 changes[ flag ] = false;
6522 delete this.flags[ flag ];
6523 remove.push( className );
6524 }
6525
6526 if ( this.$flagged ) {
6527 this.$flagged.removeClass( remove.join( ' ' ) );
6528 }
6529
6530 this.updateThemeClasses();
6531 this.emit( 'flag', changes );
6532
6533 return this;
6534 };
6535
6536 /**
6537 * Add one or more flags.
6538 *
6539 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6540 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6541 * be added (`true`) or removed (`false`).
6542 * @chainable
6543 * @fires flag
6544 */
6545 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6546 var i, len, flag, className,
6547 changes = {},
6548 add = [],
6549 remove = [],
6550 classPrefix = 'oo-ui-flaggedElement-';
6551
6552 if ( typeof flags === 'string' ) {
6553 className = classPrefix + flags;
6554 // Set
6555 if ( !this.flags[ flags ] ) {
6556 this.flags[ flags ] = true;
6557 add.push( className );
6558 }
6559 } else if ( Array.isArray( flags ) ) {
6560 for ( i = 0, len = flags.length; i < len; i++ ) {
6561 flag = flags[ i ];
6562 className = classPrefix + flag;
6563 // Set
6564 if ( !this.flags[ flag ] ) {
6565 changes[ flag ] = true;
6566 this.flags[ flag ] = true;
6567 add.push( className );
6568 }
6569 }
6570 } else if ( OO.isPlainObject( flags ) ) {
6571 for ( flag in flags ) {
6572 className = classPrefix + flag;
6573 if ( flags[ flag ] ) {
6574 // Set
6575 if ( !this.flags[ flag ] ) {
6576 changes[ flag ] = true;
6577 this.flags[ flag ] = true;
6578 add.push( className );
6579 }
6580 } else {
6581 // Remove
6582 if ( this.flags[ flag ] ) {
6583 changes[ flag ] = false;
6584 delete this.flags[ flag ];
6585 remove.push( className );
6586 }
6587 }
6588 }
6589 }
6590
6591 if ( this.$flagged ) {
6592 this.$flagged
6593 .addClass( add.join( ' ' ) )
6594 .removeClass( remove.join( ' ' ) );
6595 }
6596
6597 this.updateThemeClasses();
6598 this.emit( 'flag', changes );
6599
6600 return this;
6601 };
6602
6603 /**
6604 * TitledElement is mixed into other classes to provide a `title` attribute.
6605 * Titles are rendered by the browser and are made visible when the user moves
6606 * the mouse over the element. Titles are not visible on touch devices.
6607 *
6608 * @example
6609 * // TitledElement provides a 'title' attribute to the
6610 * // ButtonWidget class
6611 * var button = new OO.ui.ButtonWidget( {
6612 * label: 'Button with Title',
6613 * title: 'I am a button'
6614 * } );
6615 * $( 'body' ).append( button.$element );
6616 *
6617 * @abstract
6618 * @class
6619 *
6620 * @constructor
6621 * @param {Object} [config] Configuration options
6622 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6623 * If this config is omitted, the title functionality is applied to $element, the
6624 * element created by the class.
6625 * @cfg {string|Function} [title] The title text or a function that returns text. If
6626 * this config is omitted, the value of the {@link #static-title static title} property is used.
6627 */
6628 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6629 // Configuration initialization
6630 config = config || {};
6631
6632 // Properties
6633 this.$titled = null;
6634 this.title = null;
6635
6636 // Initialization
6637 this.setTitle( config.title || this.constructor.static.title );
6638 this.setTitledElement( config.$titled || this.$element );
6639 };
6640
6641 /* Setup */
6642
6643 OO.initClass( OO.ui.mixin.TitledElement );
6644
6645 /* Static Properties */
6646
6647 /**
6648 * The title text, a function that returns text, or `null` for no title. The value of the static property
6649 * is overridden if the #title config option is used.
6650 *
6651 * @static
6652 * @inheritable
6653 * @property {string|Function|null}
6654 */
6655 OO.ui.mixin.TitledElement.static.title = null;
6656
6657 /* Methods */
6658
6659 /**
6660 * Set the titled element.
6661 *
6662 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6663 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6664 *
6665 * @param {jQuery} $titled Element that should use the 'titled' functionality
6666 */
6667 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6668 if ( this.$titled ) {
6669 this.$titled.removeAttr( 'title' );
6670 }
6671
6672 this.$titled = $titled;
6673 if ( this.title ) {
6674 this.$titled.attr( 'title', this.title );
6675 }
6676 };
6677
6678 /**
6679 * Set title.
6680 *
6681 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6682 * @chainable
6683 */
6684 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6685 title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title;
6686 title = ( typeof title === 'string' && title.length ) ? title : null;
6687
6688 if ( this.title !== title ) {
6689 if ( this.$titled ) {
6690 if ( title !== null ) {
6691 this.$titled.attr( 'title', title );
6692 } else {
6693 this.$titled.removeAttr( 'title' );
6694 }
6695 }
6696 this.title = title;
6697 }
6698
6699 return this;
6700 };
6701
6702 /**
6703 * Get title.
6704 *
6705 * @return {string} Title string
6706 */
6707 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6708 return this.title;
6709 };
6710
6711 /**
6712 * Element that can be automatically clipped to visible boundaries.
6713 *
6714 * Whenever the element's natural height changes, you have to call
6715 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6716 * clipping correctly.
6717 *
6718 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6719 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6720 * then #$clippable will be given a fixed reduced height and/or width and will be made
6721 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6722 * but you can build a static footer by setting #$clippableContainer to an element that contains
6723 * #$clippable and the footer.
6724 *
6725 * @abstract
6726 * @class
6727 *
6728 * @constructor
6729 * @param {Object} [config] Configuration options
6730 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6731 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6732 * omit to use #$clippable
6733 */
6734 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6735 // Configuration initialization
6736 config = config || {};
6737
6738 // Properties
6739 this.$clippable = null;
6740 this.$clippableContainer = null;
6741 this.clipping = false;
6742 this.clippedHorizontally = false;
6743 this.clippedVertically = false;
6744 this.$clippableScrollableContainer = null;
6745 this.$clippableScroller = null;
6746 this.$clippableWindow = null;
6747 this.idealWidth = null;
6748 this.idealHeight = null;
6749 this.onClippableScrollHandler = this.clip.bind( this );
6750 this.onClippableWindowResizeHandler = this.clip.bind( this );
6751
6752 // Initialization
6753 if ( config.$clippableContainer ) {
6754 this.setClippableContainer( config.$clippableContainer );
6755 }
6756 this.setClippableElement( config.$clippable || this.$element );
6757 };
6758
6759 /* Methods */
6760
6761 /**
6762 * Set clippable element.
6763 *
6764 * If an element is already set, it will be cleaned up before setting up the new element.
6765 *
6766 * @param {jQuery} $clippable Element to make clippable
6767 */
6768 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6769 if ( this.$clippable ) {
6770 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6771 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6772 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6773 }
6774
6775 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6776 this.clip();
6777 };
6778
6779 /**
6780 * Set clippable container.
6781 *
6782 * This is the container that will be measured when deciding whether to clip. When clipping,
6783 * #$clippable will be resized in order to keep the clippable container fully visible.
6784 *
6785 * If the clippable container is unset, #$clippable will be used.
6786 *
6787 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6788 */
6789 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6790 this.$clippableContainer = $clippableContainer;
6791 if ( this.$clippable ) {
6792 this.clip();
6793 }
6794 };
6795
6796 /**
6797 * Toggle clipping.
6798 *
6799 * Do not turn clipping on until after the element is attached to the DOM and visible.
6800 *
6801 * @param {boolean} [clipping] Enable clipping, omit to toggle
6802 * @chainable
6803 */
6804 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6805 clipping = clipping === undefined ? !this.clipping : !!clipping;
6806
6807 if ( this.clipping !== clipping ) {
6808 this.clipping = clipping;
6809 if ( clipping ) {
6810 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6811 // If the clippable container is the root, we have to listen to scroll events and check
6812 // jQuery.scrollTop on the window because of browser inconsistencies
6813 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6814 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6815 this.$clippableScrollableContainer;
6816 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6817 this.$clippableWindow = $( this.getElementWindow() )
6818 .on( 'resize', this.onClippableWindowResizeHandler );
6819 // Initial clip after visible
6820 this.clip();
6821 } else {
6822 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6823 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6824
6825 this.$clippableScrollableContainer = null;
6826 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6827 this.$clippableScroller = null;
6828 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6829 this.$clippableWindow = null;
6830 }
6831 }
6832
6833 return this;
6834 };
6835
6836 /**
6837 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6838 *
6839 * @return {boolean} Element will be clipped to the visible area
6840 */
6841 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6842 return this.clipping;
6843 };
6844
6845 /**
6846 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6847 *
6848 * @return {boolean} Part of the element is being clipped
6849 */
6850 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6851 return this.clippedHorizontally || this.clippedVertically;
6852 };
6853
6854 /**
6855 * Check if the right of the element is being clipped by the nearest scrollable container.
6856 *
6857 * @return {boolean} Part of the element is being clipped
6858 */
6859 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6860 return this.clippedHorizontally;
6861 };
6862
6863 /**
6864 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6865 *
6866 * @return {boolean} Part of the element is being clipped
6867 */
6868 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6869 return this.clippedVertically;
6870 };
6871
6872 /**
6873 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6874 *
6875 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6876 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6877 */
6878 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6879 this.idealWidth = width;
6880 this.idealHeight = height;
6881
6882 if ( !this.clipping ) {
6883 // Update dimensions
6884 this.$clippable.css( { width: width, height: height } );
6885 }
6886 // While clipping, idealWidth and idealHeight are not considered
6887 };
6888
6889 /**
6890 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6891 * the element's natural height changes.
6892 *
6893 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6894 * overlapped by, the visible area of the nearest scrollable container.
6895 *
6896 * @chainable
6897 */
6898 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6899 var $container, extraHeight, extraWidth, ccOffset,
6900 $scrollableContainer, scOffset, scHeight, scWidth,
6901 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6902 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6903 naturalWidth, naturalHeight, clipWidth, clipHeight,
6904 buffer = 7; // Chosen by fair dice roll
6905
6906 if ( !this.clipping ) {
6907 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6908 return this;
6909 }
6910
6911 $container = this.$clippableContainer || this.$clippable;
6912 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6913 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6914 ccOffset = $container.offset();
6915 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6916 this.$clippableWindow : this.$clippableScrollableContainer;
6917 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6918 scHeight = $scrollableContainer.innerHeight() - buffer;
6919 scWidth = $scrollableContainer.innerWidth() - buffer;
6920 ccWidth = $container.outerWidth() + buffer;
6921 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6922 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6923 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6924 desiredWidth = ccOffset.left < 0 ?
6925 ccWidth + ccOffset.left :
6926 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6927 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6928 allotedWidth = desiredWidth - extraWidth;
6929 allotedHeight = desiredHeight - extraHeight;
6930 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6931 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6932 clipWidth = allotedWidth < naturalWidth;
6933 clipHeight = allotedHeight < naturalHeight;
6934
6935 if ( clipWidth ) {
6936 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6937 } else {
6938 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6939 }
6940 if ( clipHeight ) {
6941 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6942 } else {
6943 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6944 }
6945
6946 // If we stopped clipping in at least one of the dimensions
6947 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6948 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6949 }
6950
6951 this.clippedHorizontally = clipWidth;
6952 this.clippedVertically = clipHeight;
6953
6954 return this;
6955 };
6956
6957 /**
6958 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6959 * document (for example, in a OO.ui.Window's $overlay).
6960 *
6961 * The elements's position is automatically calculated and maintained when window is resized or the
6962 * page is scrolled. If you reposition the container manually, you have to call #position to make
6963 * sure the element is still placed correctly.
6964 *
6965 * As positioning is only possible when both the element and the container are attached to the DOM
6966 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6967 * the #toggle method to display a floating popup, for example.
6968 *
6969 * @abstract
6970 * @class
6971 *
6972 * @constructor
6973 * @param {Object} [config] Configuration options
6974 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6975 * @cfg {jQuery} [$floatableContainer] Node to position below
6976 */
6977 OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) {
6978 // Configuration initialization
6979 config = config || {};
6980
6981 // Properties
6982 this.$floatable = null;
6983 this.$floatableContainer = null;
6984 this.$floatableWindow = null;
6985 this.$floatableClosestScrollable = null;
6986 this.onFloatableScrollHandler = this.position.bind( this );
6987 this.onFloatableWindowResizeHandler = this.position.bind( this );
6988
6989 // Initialization
6990 this.setFloatableContainer( config.$floatableContainer );
6991 this.setFloatableElement( config.$floatable || this.$element );
6992 };
6993
6994 /* Methods */
6995
6996 /**
6997 * Set floatable element.
6998 *
6999 * If an element is already set, it will be cleaned up before setting up the new element.
7000 *
7001 * @param {jQuery} $floatable Element to make floatable
7002 */
7003 OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) {
7004 if ( this.$floatable ) {
7005 this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' );
7006 this.$floatable.css( { left: '', top: '' } );
7007 }
7008
7009 this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' );
7010 this.position();
7011 };
7012
7013 /**
7014 * Set floatable container.
7015 *
7016 * The element will be always positioned under the specified container.
7017 *
7018 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7019 */
7020 OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) {
7021 this.$floatableContainer = $floatableContainer;
7022 if ( this.$floatable ) {
7023 this.position();
7024 }
7025 };
7026
7027 /**
7028 * Toggle positioning.
7029 *
7030 * Do not turn positioning on until after the element is attached to the DOM and visible.
7031 *
7032 * @param {boolean} [positioning] Enable positioning, omit to toggle
7033 * @chainable
7034 */
7035 OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) {
7036 var closestScrollableOfContainer, closestScrollableOfFloatable;
7037
7038 positioning = positioning === undefined ? !this.positioning : !!positioning;
7039
7040 if ( this.positioning !== positioning ) {
7041 this.positioning = positioning;
7042
7043 closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] );
7044 closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] );
7045 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7046 // If the scrollable is the root, we have to listen to scroll events
7047 // on the window because of browser inconsistencies (or do we? someone should verify this)
7048 if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) {
7049 closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer );
7050 }
7051 }
7052
7053 if ( positioning ) {
7054 this.$floatableWindow = $( this.getElementWindow() );
7055 this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler );
7056
7057 if ( closestScrollableOfContainer !== closestScrollableOfFloatable ) {
7058 this.$floatableClosestScrollable = $( closestScrollableOfContainer );
7059 this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler );
7060 }
7061
7062 // Initial position after visible
7063 this.position();
7064 } else {
7065 if ( this.$floatableWindow ) {
7066 this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler );
7067 this.$floatableWindow = null;
7068 }
7069
7070 if ( this.$floatableClosestScrollable ) {
7071 this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler );
7072 this.$floatableClosestScrollable = null;
7073 }
7074
7075 this.$floatable.css( { left: '', top: '' } );
7076 }
7077 }
7078
7079 return this;
7080 };
7081
7082 /**
7083 * Position the floatable below its container.
7084 *
7085 * This should only be done when both of them are attached to the DOM and visible.
7086 *
7087 * @chainable
7088 */
7089 OO.ui.mixin.FloatableElement.prototype.position = function () {
7090 var pos;
7091
7092 if ( !this.positioning ) {
7093 return this;
7094 }
7095
7096 pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() );
7097
7098 // Position under container
7099 pos.top += this.$floatableContainer.height();
7100 this.$floatable.css( pos );
7101
7102 // We updated the position, so re-evaluate the clipping state.
7103 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7104 // will not notice the need to update itself.)
7105 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7106 // it not listen to the right events in the right places?
7107 if ( this.clip ) {
7108 this.clip();
7109 }
7110
7111 return this;
7112 };
7113
7114 /**
7115 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
7116 * Accesskeys allow an user to go to a specific element by using
7117 * a shortcut combination of a browser specific keys + the key
7118 * set to the field.
7119 *
7120 * @example
7121 * // AccessKeyedElement provides an 'accesskey' attribute to the
7122 * // ButtonWidget class
7123 * var button = new OO.ui.ButtonWidget( {
7124 * label: 'Button with Accesskey',
7125 * accessKey: 'k'
7126 * } );
7127 * $( 'body' ).append( button.$element );
7128 *
7129 * @abstract
7130 * @class
7131 *
7132 * @constructor
7133 * @param {Object} [config] Configuration options
7134 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7135 * If this config is omitted, the accesskey functionality is applied to $element, the
7136 * element created by the class.
7137 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7138 * this config is omitted, no accesskey will be added.
7139 */
7140 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
7141 // Configuration initialization
7142 config = config || {};
7143
7144 // Properties
7145 this.$accessKeyed = null;
7146 this.accessKey = null;
7147
7148 // Initialization
7149 this.setAccessKey( config.accessKey || null );
7150 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
7151 };
7152
7153 /* Setup */
7154
7155 OO.initClass( OO.ui.mixin.AccessKeyedElement );
7156
7157 /* Static Properties */
7158
7159 /**
7160 * The access key, a function that returns a key, or `null` for no accesskey.
7161 *
7162 * @static
7163 * @inheritable
7164 * @property {string|Function|null}
7165 */
7166 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
7167
7168 /* Methods */
7169
7170 /**
7171 * Set the accesskeyed element.
7172 *
7173 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7174 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7175 *
7176 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7177 */
7178 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
7179 if ( this.$accessKeyed ) {
7180 this.$accessKeyed.removeAttr( 'accesskey' );
7181 }
7182
7183 this.$accessKeyed = $accessKeyed;
7184 if ( this.accessKey ) {
7185 this.$accessKeyed.attr( 'accesskey', this.accessKey );
7186 }
7187 };
7188
7189 /**
7190 * Set accesskey.
7191 *
7192 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7193 * @chainable
7194 */
7195 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
7196 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
7197
7198 if ( this.accessKey !== accessKey ) {
7199 if ( this.$accessKeyed ) {
7200 if ( accessKey !== null ) {
7201 this.$accessKeyed.attr( 'accesskey', accessKey );
7202 } else {
7203 this.$accessKeyed.removeAttr( 'accesskey' );
7204 }
7205 }
7206 this.accessKey = accessKey;
7207 }
7208
7209 return this;
7210 };
7211
7212 /**
7213 * Get accesskey.
7214 *
7215 * @return {string} accessKey string
7216 */
7217 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
7218 return this.accessKey;
7219 };
7220
7221 /**
7222 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7223 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7224 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7225 * which creates the tools on demand.
7226 *
7227 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7228 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7229 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7230 *
7231 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7232 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7233 *
7234 * @abstract
7235 * @class
7236 * @extends OO.ui.Widget
7237 * @mixins OO.ui.mixin.IconElement
7238 * @mixins OO.ui.mixin.FlaggedElement
7239 * @mixins OO.ui.mixin.TabIndexedElement
7240 *
7241 * @constructor
7242 * @param {OO.ui.ToolGroup} toolGroup
7243 * @param {Object} [config] Configuration options
7244 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7245 * the {@link #static-title static title} property is used.
7246 *
7247 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7248 * 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
7249 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7250 *
7251 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7252 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7253 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7254 */
7255 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
7256 // Allow passing positional parameters inside the config object
7257 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
7258 config = toolGroup;
7259 toolGroup = config.toolGroup;
7260 }
7261
7262 // Configuration initialization
7263 config = config || {};
7264
7265 // Parent constructor
7266 OO.ui.Tool.parent.call( this, config );
7267
7268 // Properties
7269 this.toolGroup = toolGroup;
7270 this.toolbar = this.toolGroup.getToolbar();
7271 this.active = false;
7272 this.$title = $( '<span>' );
7273 this.$accel = $( '<span>' );
7274 this.$link = $( '<a>' );
7275 this.title = null;
7276
7277 // Mixin constructors
7278 OO.ui.mixin.IconElement.call( this, config );
7279 OO.ui.mixin.FlaggedElement.call( this, config );
7280 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
7281
7282 // Events
7283 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7284
7285 // Initialization
7286 this.$title.addClass( 'oo-ui-tool-title' );
7287 this.$accel
7288 .addClass( 'oo-ui-tool-accel' )
7289 .prop( {
7290 // This may need to be changed if the key names are ever localized,
7291 // but for now they are essentially written in English
7292 dir: 'ltr',
7293 lang: 'en'
7294 } );
7295 this.$link
7296 .addClass( 'oo-ui-tool-link' )
7297 .append( this.$icon, this.$title, this.$accel )
7298 .attr( 'role', 'button' );
7299 this.$element
7300 .data( 'oo-ui-tool', this )
7301 .addClass(
7302 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7303 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7304 )
7305 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
7306 .append( this.$link );
7307 this.setTitle( config.title || this.constructor.static.title );
7308 };
7309
7310 /* Setup */
7311
7312 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
7313 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
7314 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
7315 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
7316
7317 /* Static Properties */
7318
7319 /**
7320 * @static
7321 * @inheritdoc
7322 */
7323 OO.ui.Tool.static.tagName = 'span';
7324
7325 /**
7326 * Symbolic name of tool.
7327 *
7328 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7329 * also be used when adding tools to toolgroups.
7330 *
7331 * @abstract
7332 * @static
7333 * @inheritable
7334 * @property {string}
7335 */
7336 OO.ui.Tool.static.name = '';
7337
7338 /**
7339 * Symbolic name of the group.
7340 *
7341 * The group name is used to associate tools with each other so that they can be selected later by
7342 * a {@link OO.ui.ToolGroup toolgroup}.
7343 *
7344 * @abstract
7345 * @static
7346 * @inheritable
7347 * @property {string}
7348 */
7349 OO.ui.Tool.static.group = '';
7350
7351 /**
7352 * 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.
7353 *
7354 * @abstract
7355 * @static
7356 * @inheritable
7357 * @property {string|Function}
7358 */
7359 OO.ui.Tool.static.title = '';
7360
7361 /**
7362 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7363 * Normally only the icon is displayed, or only the label if no icon is given.
7364 *
7365 * @static
7366 * @inheritable
7367 * @property {boolean}
7368 */
7369 OO.ui.Tool.static.displayBothIconAndLabel = false;
7370
7371 /**
7372 * Add tool to catch-all groups automatically.
7373 *
7374 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7375 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7376 *
7377 * @static
7378 * @inheritable
7379 * @property {boolean}
7380 */
7381 OO.ui.Tool.static.autoAddToCatchall = true;
7382
7383 /**
7384 * Add tool to named groups automatically.
7385 *
7386 * By default, tools that are configured with a static ‘group’ property are added
7387 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7388 * toolgroups include tools by group name).
7389 *
7390 * @static
7391 * @property {boolean}
7392 * @inheritable
7393 */
7394 OO.ui.Tool.static.autoAddToGroup = true;
7395
7396 /**
7397 * Check if this tool is compatible with given data.
7398 *
7399 * This is a stub that can be overriden to provide support for filtering tools based on an
7400 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7401 * must also call this method so that the compatibility check can be performed.
7402 *
7403 * @static
7404 * @inheritable
7405 * @param {Mixed} data Data to check
7406 * @return {boolean} Tool can be used with data
7407 */
7408 OO.ui.Tool.static.isCompatibleWith = function () {
7409 return false;
7410 };
7411
7412 /* Methods */
7413
7414 /**
7415 * Handle the toolbar state being updated.
7416 *
7417 * This is an abstract method that must be overridden in a concrete subclass.
7418 *
7419 * @method
7420 * @protected
7421 * @abstract
7422 */
7423 OO.ui.Tool.prototype.onUpdateState = null;
7424
7425 /**
7426 * Handle the tool being selected.
7427 *
7428 * This is an abstract method that must be overridden in a concrete subclass.
7429 *
7430 * @method
7431 * @protected
7432 * @abstract
7433 */
7434 OO.ui.Tool.prototype.onSelect = null;
7435
7436 /**
7437 * Check if the tool is active.
7438 *
7439 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7440 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7441 *
7442 * @return {boolean} Tool is active
7443 */
7444 OO.ui.Tool.prototype.isActive = function () {
7445 return this.active;
7446 };
7447
7448 /**
7449 * Make the tool appear active or inactive.
7450 *
7451 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7452 * appear pressed or not.
7453 *
7454 * @param {boolean} state Make tool appear active
7455 */
7456 OO.ui.Tool.prototype.setActive = function ( state ) {
7457 this.active = !!state;
7458 if ( this.active ) {
7459 this.$element.addClass( 'oo-ui-tool-active' );
7460 } else {
7461 this.$element.removeClass( 'oo-ui-tool-active' );
7462 }
7463 };
7464
7465 /**
7466 * Set the tool #title.
7467 *
7468 * @param {string|Function} title Title text or a function that returns text
7469 * @chainable
7470 */
7471 OO.ui.Tool.prototype.setTitle = function ( title ) {
7472 this.title = OO.ui.resolveMsg( title );
7473 this.updateTitle();
7474 return this;
7475 };
7476
7477 /**
7478 * Get the tool #title.
7479 *
7480 * @return {string} Title text
7481 */
7482 OO.ui.Tool.prototype.getTitle = function () {
7483 return this.title;
7484 };
7485
7486 /**
7487 * Get the tool's symbolic name.
7488 *
7489 * @return {string} Symbolic name of tool
7490 */
7491 OO.ui.Tool.prototype.getName = function () {
7492 return this.constructor.static.name;
7493 };
7494
7495 /**
7496 * Update the title.
7497 */
7498 OO.ui.Tool.prototype.updateTitle = function () {
7499 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7500 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7501 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7502 tooltipParts = [];
7503
7504 this.$title.text( this.title );
7505 this.$accel.text( accel );
7506
7507 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7508 tooltipParts.push( this.title );
7509 }
7510 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7511 tooltipParts.push( accel );
7512 }
7513 if ( tooltipParts.length ) {
7514 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7515 } else {
7516 this.$link.removeAttr( 'title' );
7517 }
7518 };
7519
7520 /**
7521 * Destroy tool.
7522 *
7523 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7524 * Call this method whenever you are done using a tool.
7525 */
7526 OO.ui.Tool.prototype.destroy = function () {
7527 this.toolbar.disconnect( this );
7528 this.$element.remove();
7529 };
7530
7531 /**
7532 * Toolbars are complex interface components that permit users to easily access a variety
7533 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7534 * part of the toolbar, but not configured as tools.
7535 *
7536 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7537 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7538 * image’), and an icon.
7539 *
7540 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7541 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7542 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7543 * any order, but each can only appear once in the toolbar.
7544 *
7545 * The following is an example of a basic toolbar.
7546 *
7547 * @example
7548 * // Example of a toolbar
7549 * // Create the toolbar
7550 * var toolFactory = new OO.ui.ToolFactory();
7551 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7552 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7553 *
7554 * // We will be placing status text in this element when tools are used
7555 * var $area = $( '<p>' ).text( 'Toolbar example' );
7556 *
7557 * // Define the tools that we're going to place in our toolbar
7558 *
7559 * // Create a class inheriting from OO.ui.Tool
7560 * function ImageTool() {
7561 * ImageTool.parent.apply( this, arguments );
7562 * }
7563 * OO.inheritClass( ImageTool, OO.ui.Tool );
7564 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7565 * // of 'icon' and 'title' (displayed icon and text).
7566 * ImageTool.static.name = 'image';
7567 * ImageTool.static.icon = 'image';
7568 * ImageTool.static.title = 'Insert image';
7569 * // Defines the action that will happen when this tool is selected (clicked).
7570 * ImageTool.prototype.onSelect = function () {
7571 * $area.text( 'Image tool clicked!' );
7572 * // Never display this tool as "active" (selected).
7573 * this.setActive( false );
7574 * };
7575 * // Make this tool available in our toolFactory and thus our toolbar
7576 * toolFactory.register( ImageTool );
7577 *
7578 * // Register two more tools, nothing interesting here
7579 * function SettingsTool() {
7580 * SettingsTool.parent.apply( this, arguments );
7581 * }
7582 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7583 * SettingsTool.static.name = 'settings';
7584 * SettingsTool.static.icon = 'settings';
7585 * SettingsTool.static.title = 'Change settings';
7586 * SettingsTool.prototype.onSelect = function () {
7587 * $area.text( 'Settings tool clicked!' );
7588 * this.setActive( false );
7589 * };
7590 * toolFactory.register( SettingsTool );
7591 *
7592 * // Register two more tools, nothing interesting here
7593 * function StuffTool() {
7594 * StuffTool.parent.apply( this, arguments );
7595 * }
7596 * OO.inheritClass( StuffTool, OO.ui.Tool );
7597 * StuffTool.static.name = 'stuff';
7598 * StuffTool.static.icon = 'ellipsis';
7599 * StuffTool.static.title = 'More stuff';
7600 * StuffTool.prototype.onSelect = function () {
7601 * $area.text( 'More stuff tool clicked!' );
7602 * this.setActive( false );
7603 * };
7604 * toolFactory.register( StuffTool );
7605 *
7606 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7607 * // little popup window (a PopupWidget).
7608 * function HelpTool( toolGroup, config ) {
7609 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7610 * padded: true,
7611 * label: 'Help',
7612 * head: true
7613 * } }, config ) );
7614 * this.popup.$body.append( '<p>I am helpful!</p>' );
7615 * }
7616 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7617 * HelpTool.static.name = 'help';
7618 * HelpTool.static.icon = 'help';
7619 * HelpTool.static.title = 'Help';
7620 * toolFactory.register( HelpTool );
7621 *
7622 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7623 * // used once (but not all defined tools must be used).
7624 * toolbar.setup( [
7625 * {
7626 * // 'bar' tool groups display tools' icons only, side-by-side.
7627 * type: 'bar',
7628 * include: [ 'image', 'help' ]
7629 * },
7630 * {
7631 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7632 * type: 'list',
7633 * indicator: 'down',
7634 * label: 'More',
7635 * include: [ 'settings', 'stuff' ]
7636 * }
7637 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7638 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7639 * // since it's more complicated to use. (See the next example snippet on this page.)
7640 * ] );
7641 *
7642 * // Create some UI around the toolbar and place it in the document
7643 * var frame = new OO.ui.PanelLayout( {
7644 * expanded: false,
7645 * framed: true
7646 * } );
7647 * var contentFrame = new OO.ui.PanelLayout( {
7648 * expanded: false,
7649 * padded: true
7650 * } );
7651 * frame.$element.append(
7652 * toolbar.$element,
7653 * contentFrame.$element.append( $area )
7654 * );
7655 * $( 'body' ).append( frame.$element );
7656 *
7657 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7658 * // document.
7659 * toolbar.initialize();
7660 *
7661 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7662 * 'updateState' event.
7663 *
7664 * @example
7665 * // Create the toolbar
7666 * var toolFactory = new OO.ui.ToolFactory();
7667 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7668 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7669 *
7670 * // We will be placing status text in this element when tools are used
7671 * var $area = $( '<p>' ).text( 'Toolbar example' );
7672 *
7673 * // Define the tools that we're going to place in our toolbar
7674 *
7675 * // Create a class inheriting from OO.ui.Tool
7676 * function ImageTool() {
7677 * ImageTool.parent.apply( this, arguments );
7678 * }
7679 * OO.inheritClass( ImageTool, OO.ui.Tool );
7680 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7681 * // of 'icon' and 'title' (displayed icon and text).
7682 * ImageTool.static.name = 'image';
7683 * ImageTool.static.icon = 'image';
7684 * ImageTool.static.title = 'Insert image';
7685 * // Defines the action that will happen when this tool is selected (clicked).
7686 * ImageTool.prototype.onSelect = function () {
7687 * $area.text( 'Image tool clicked!' );
7688 * // Never display this tool as "active" (selected).
7689 * this.setActive( false );
7690 * };
7691 * // The toolbar can be synchronized with the state of some external stuff, like a text
7692 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7693 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7694 * ImageTool.prototype.onUpdateState = function () {
7695 * };
7696 * // Make this tool available in our toolFactory and thus our toolbar
7697 * toolFactory.register( ImageTool );
7698 *
7699 * // Register two more tools, nothing interesting here
7700 * function SettingsTool() {
7701 * SettingsTool.parent.apply( this, arguments );
7702 * this.reallyActive = false;
7703 * }
7704 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7705 * SettingsTool.static.name = 'settings';
7706 * SettingsTool.static.icon = 'settings';
7707 * SettingsTool.static.title = 'Change settings';
7708 * SettingsTool.prototype.onSelect = function () {
7709 * $area.text( 'Settings tool clicked!' );
7710 * // Toggle the active state on each click
7711 * this.reallyActive = !this.reallyActive;
7712 * this.setActive( this.reallyActive );
7713 * // To update the menu label
7714 * this.toolbar.emit( 'updateState' );
7715 * };
7716 * SettingsTool.prototype.onUpdateState = function () {
7717 * };
7718 * toolFactory.register( SettingsTool );
7719 *
7720 * // Register two more tools, nothing interesting here
7721 * function StuffTool() {
7722 * StuffTool.parent.apply( this, arguments );
7723 * this.reallyActive = false;
7724 * }
7725 * OO.inheritClass( StuffTool, OO.ui.Tool );
7726 * StuffTool.static.name = 'stuff';
7727 * StuffTool.static.icon = 'ellipsis';
7728 * StuffTool.static.title = 'More stuff';
7729 * StuffTool.prototype.onSelect = function () {
7730 * $area.text( 'More stuff tool clicked!' );
7731 * // Toggle the active state on each click
7732 * this.reallyActive = !this.reallyActive;
7733 * this.setActive( this.reallyActive );
7734 * // To update the menu label
7735 * this.toolbar.emit( 'updateState' );
7736 * };
7737 * StuffTool.prototype.onUpdateState = function () {
7738 * };
7739 * toolFactory.register( StuffTool );
7740 *
7741 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7742 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7743 * function HelpTool( toolGroup, config ) {
7744 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7745 * padded: true,
7746 * label: 'Help',
7747 * head: true
7748 * } }, config ) );
7749 * this.popup.$body.append( '<p>I am helpful!</p>' );
7750 * }
7751 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7752 * HelpTool.static.name = 'help';
7753 * HelpTool.static.icon = 'help';
7754 * HelpTool.static.title = 'Help';
7755 * toolFactory.register( HelpTool );
7756 *
7757 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7758 * // used once (but not all defined tools must be used).
7759 * toolbar.setup( [
7760 * {
7761 * // 'bar' tool groups display tools' icons only, side-by-side.
7762 * type: 'bar',
7763 * include: [ 'image', 'help' ]
7764 * },
7765 * {
7766 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7767 * // Menu label indicates which items are selected.
7768 * type: 'menu',
7769 * indicator: 'down',
7770 * include: [ 'settings', 'stuff' ]
7771 * }
7772 * ] );
7773 *
7774 * // Create some UI around the toolbar and place it in the document
7775 * var frame = new OO.ui.PanelLayout( {
7776 * expanded: false,
7777 * framed: true
7778 * } );
7779 * var contentFrame = new OO.ui.PanelLayout( {
7780 * expanded: false,
7781 * padded: true
7782 * } );
7783 * frame.$element.append(
7784 * toolbar.$element,
7785 * contentFrame.$element.append( $area )
7786 * );
7787 * $( 'body' ).append( frame.$element );
7788 *
7789 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7790 * // document.
7791 * toolbar.initialize();
7792 * toolbar.emit( 'updateState' );
7793 *
7794 * @class
7795 * @extends OO.ui.Element
7796 * @mixins OO.EventEmitter
7797 * @mixins OO.ui.mixin.GroupElement
7798 *
7799 * @constructor
7800 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7801 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7802 * @param {Object} [config] Configuration options
7803 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7804 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7805 * the toolbar.
7806 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7807 */
7808 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7809 // Allow passing positional parameters inside the config object
7810 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7811 config = toolFactory;
7812 toolFactory = config.toolFactory;
7813 toolGroupFactory = config.toolGroupFactory;
7814 }
7815
7816 // Configuration initialization
7817 config = config || {};
7818
7819 // Parent constructor
7820 OO.ui.Toolbar.parent.call( this, config );
7821
7822 // Mixin constructors
7823 OO.EventEmitter.call( this );
7824 OO.ui.mixin.GroupElement.call( this, config );
7825
7826 // Properties
7827 this.toolFactory = toolFactory;
7828 this.toolGroupFactory = toolGroupFactory;
7829 this.groups = [];
7830 this.tools = {};
7831 this.$bar = $( '<div>' );
7832 this.$actions = $( '<div>' );
7833 this.initialized = false;
7834 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7835
7836 // Events
7837 this.$element
7838 .add( this.$bar ).add( this.$group ).add( this.$actions )
7839 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7840
7841 // Initialization
7842 this.$group.addClass( 'oo-ui-toolbar-tools' );
7843 if ( config.actions ) {
7844 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7845 }
7846 this.$bar
7847 .addClass( 'oo-ui-toolbar-bar' )
7848 .append( this.$group, '<div style="clear:both"></div>' );
7849 if ( config.shadow ) {
7850 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7851 }
7852 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7853 };
7854
7855 /* Setup */
7856
7857 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7858 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7859 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7860
7861 /* Methods */
7862
7863 /**
7864 * Get the tool factory.
7865 *
7866 * @return {OO.ui.ToolFactory} Tool factory
7867 */
7868 OO.ui.Toolbar.prototype.getToolFactory = function () {
7869 return this.toolFactory;
7870 };
7871
7872 /**
7873 * Get the toolgroup factory.
7874 *
7875 * @return {OO.Factory} Toolgroup factory
7876 */
7877 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7878 return this.toolGroupFactory;
7879 };
7880
7881 /**
7882 * Handles mouse down events.
7883 *
7884 * @private
7885 * @param {jQuery.Event} e Mouse down event
7886 */
7887 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7888 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7889 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7890 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7891 return false;
7892 }
7893 };
7894
7895 /**
7896 * Handle window resize event.
7897 *
7898 * @private
7899 * @param {jQuery.Event} e Window resize event
7900 */
7901 OO.ui.Toolbar.prototype.onWindowResize = function () {
7902 this.$element.toggleClass(
7903 'oo-ui-toolbar-narrow',
7904 this.$bar.width() <= this.narrowThreshold
7905 );
7906 };
7907
7908 /**
7909 * Sets up handles and preloads required information for the toolbar to work.
7910 * This must be called after it is attached to a visible document and before doing anything else.
7911 */
7912 OO.ui.Toolbar.prototype.initialize = function () {
7913 if ( !this.initialized ) {
7914 this.initialized = true;
7915 this.narrowThreshold = this.$group.width() + this.$actions.width();
7916 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7917 this.onWindowResize();
7918 }
7919 };
7920
7921 /**
7922 * Set up the toolbar.
7923 *
7924 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7925 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7926 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7927 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7928 *
7929 * @param {Object.<string,Array>} groups List of toolgroup configurations
7930 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7931 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7932 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7933 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7934 */
7935 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7936 var i, len, type, group,
7937 items = [],
7938 defaultType = 'bar';
7939
7940 // Cleanup previous groups
7941 this.reset();
7942
7943 // Build out new groups
7944 for ( i = 0, len = groups.length; i < len; i++ ) {
7945 group = groups[ i ];
7946 if ( group.include === '*' ) {
7947 // Apply defaults to catch-all groups
7948 if ( group.type === undefined ) {
7949 group.type = 'list';
7950 }
7951 if ( group.label === undefined ) {
7952 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7953 }
7954 }
7955 // Check type has been registered
7956 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7957 items.push(
7958 this.getToolGroupFactory().create( type, this, group )
7959 );
7960 }
7961 this.addItems( items );
7962 };
7963
7964 /**
7965 * Remove all tools and toolgroups from the toolbar.
7966 */
7967 OO.ui.Toolbar.prototype.reset = function () {
7968 var i, len;
7969
7970 this.groups = [];
7971 this.tools = {};
7972 for ( i = 0, len = this.items.length; i < len; i++ ) {
7973 this.items[ i ].destroy();
7974 }
7975 this.clearItems();
7976 };
7977
7978 /**
7979 * Destroy the toolbar.
7980 *
7981 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7982 * this method whenever you are done using a toolbar.
7983 */
7984 OO.ui.Toolbar.prototype.destroy = function () {
7985 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7986 this.reset();
7987 this.$element.remove();
7988 };
7989
7990 /**
7991 * Check if the tool is available.
7992 *
7993 * Available tools are ones that have not yet been added to the toolbar.
7994 *
7995 * @param {string} name Symbolic name of tool
7996 * @return {boolean} Tool is available
7997 */
7998 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7999 return !this.tools[ name ];
8000 };
8001
8002 /**
8003 * Prevent tool from being used again.
8004 *
8005 * @param {OO.ui.Tool} tool Tool to reserve
8006 */
8007 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
8008 this.tools[ tool.getName() ] = tool;
8009 };
8010
8011 /**
8012 * Allow tool to be used again.
8013 *
8014 * @param {OO.ui.Tool} tool Tool to release
8015 */
8016 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
8017 delete this.tools[ tool.getName() ];
8018 };
8019
8020 /**
8021 * Get accelerator label for tool.
8022 *
8023 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
8024 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
8025 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
8026 *
8027 * @param {string} name Symbolic name of tool
8028 * @return {string|undefined} Tool accelerator label if available
8029 */
8030 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
8031 return undefined;
8032 };
8033
8034 /**
8035 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
8036 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
8037 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
8038 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
8039 *
8040 * Toolgroups can contain individual tools, groups of tools, or all available tools:
8041 *
8042 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
8043 *
8044 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
8045 *
8046 * 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.)
8047 *
8048 * include: [ { group: 'group-name' } ]
8049 *
8050 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
8051 *
8052 * include: '*'
8053 *
8054 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
8055 * please see the [OOjs UI documentation on MediaWiki][1].
8056 *
8057 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
8058 *
8059 * @abstract
8060 * @class
8061 * @extends OO.ui.Widget
8062 * @mixins OO.ui.mixin.GroupElement
8063 *
8064 * @constructor
8065 * @param {OO.ui.Toolbar} toolbar
8066 * @param {Object} [config] Configuration options
8067 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
8068 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
8069 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
8070 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
8071 * This setting is particularly useful when tools have been added to the toolgroup
8072 * en masse (e.g., via the catch-all selector).
8073 */
8074 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
8075 // Allow passing positional parameters inside the config object
8076 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
8077 config = toolbar;
8078 toolbar = config.toolbar;
8079 }
8080
8081 // Configuration initialization
8082 config = config || {};
8083
8084 // Parent constructor
8085 OO.ui.ToolGroup.parent.call( this, config );
8086
8087 // Mixin constructors
8088 OO.ui.mixin.GroupElement.call( this, config );
8089
8090 // Properties
8091 this.toolbar = toolbar;
8092 this.tools = {};
8093 this.pressed = null;
8094 this.autoDisabled = false;
8095 this.include = config.include || [];
8096 this.exclude = config.exclude || [];
8097 this.promote = config.promote || [];
8098 this.demote = config.demote || [];
8099 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
8100
8101 // Events
8102 this.$element.on( {
8103 mousedown: this.onMouseKeyDown.bind( this ),
8104 mouseup: this.onMouseKeyUp.bind( this ),
8105 keydown: this.onMouseKeyDown.bind( this ),
8106 keyup: this.onMouseKeyUp.bind( this ),
8107 focus: this.onMouseOverFocus.bind( this ),
8108 blur: this.onMouseOutBlur.bind( this ),
8109 mouseover: this.onMouseOverFocus.bind( this ),
8110 mouseout: this.onMouseOutBlur.bind( this )
8111 } );
8112 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
8113 this.aggregate( { disable: 'itemDisable' } );
8114 this.connect( this, { itemDisable: 'updateDisabled' } );
8115
8116 // Initialization
8117 this.$group.addClass( 'oo-ui-toolGroup-tools' );
8118 this.$element
8119 .addClass( 'oo-ui-toolGroup' )
8120 .append( this.$group );
8121 this.populate();
8122 };
8123
8124 /* Setup */
8125
8126 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
8127 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
8128
8129 /* Events */
8130
8131 /**
8132 * @event update
8133 */
8134
8135 /* Static Properties */
8136
8137 /**
8138 * Show labels in tooltips.
8139 *
8140 * @static
8141 * @inheritable
8142 * @property {boolean}
8143 */
8144 OO.ui.ToolGroup.static.titleTooltips = false;
8145
8146 /**
8147 * Show acceleration labels in tooltips.
8148 *
8149 * Note: The OOjs UI library does not include an accelerator system, but does contain
8150 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8151 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8152 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8153 *
8154 * @static
8155 * @inheritable
8156 * @property {boolean}
8157 */
8158 OO.ui.ToolGroup.static.accelTooltips = false;
8159
8160 /**
8161 * Automatically disable the toolgroup when all tools are disabled
8162 *
8163 * @static
8164 * @inheritable
8165 * @property {boolean}
8166 */
8167 OO.ui.ToolGroup.static.autoDisable = true;
8168
8169 /* Methods */
8170
8171 /**
8172 * @inheritdoc
8173 */
8174 OO.ui.ToolGroup.prototype.isDisabled = function () {
8175 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
8176 };
8177
8178 /**
8179 * @inheritdoc
8180 */
8181 OO.ui.ToolGroup.prototype.updateDisabled = function () {
8182 var i, item, allDisabled = true;
8183
8184 if ( this.constructor.static.autoDisable ) {
8185 for ( i = this.items.length - 1; i >= 0; i-- ) {
8186 item = this.items[ i ];
8187 if ( !item.isDisabled() ) {
8188 allDisabled = false;
8189 break;
8190 }
8191 }
8192 this.autoDisabled = allDisabled;
8193 }
8194 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
8195 };
8196
8197 /**
8198 * Handle mouse down and key down events.
8199 *
8200 * @protected
8201 * @param {jQuery.Event} e Mouse down or key down event
8202 */
8203 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
8204 if (
8205 !this.isDisabled() &&
8206 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8207 ) {
8208 this.pressed = this.getTargetTool( e );
8209 if ( this.pressed ) {
8210 this.pressed.setActive( true );
8211 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8212 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8213 }
8214 return false;
8215 }
8216 };
8217
8218 /**
8219 * Handle captured mouse up and key up events.
8220 *
8221 * @protected
8222 * @param {Event} e Mouse up or key up event
8223 */
8224 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
8225 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
8226 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
8227 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8228 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8229 this.onMouseKeyUp( e );
8230 };
8231
8232 /**
8233 * Handle mouse up and key up events.
8234 *
8235 * @protected
8236 * @param {jQuery.Event} e Mouse up or key up event
8237 */
8238 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
8239 var tool = this.getTargetTool( e );
8240
8241 if (
8242 !this.isDisabled() && this.pressed && this.pressed === tool &&
8243 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
8244 ) {
8245 this.pressed.onSelect();
8246 this.pressed = null;
8247 return false;
8248 }
8249
8250 this.pressed = null;
8251 };
8252
8253 /**
8254 * Handle mouse over and focus events.
8255 *
8256 * @protected
8257 * @param {jQuery.Event} e Mouse over or focus event
8258 */
8259 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
8260 var tool = this.getTargetTool( e );
8261
8262 if ( this.pressed && this.pressed === tool ) {
8263 this.pressed.setActive( true );
8264 }
8265 };
8266
8267 /**
8268 * Handle mouse out and blur events.
8269 *
8270 * @protected
8271 * @param {jQuery.Event} e Mouse out or blur event
8272 */
8273 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
8274 var tool = this.getTargetTool( e );
8275
8276 if ( this.pressed && this.pressed === tool ) {
8277 this.pressed.setActive( false );
8278 }
8279 };
8280
8281 /**
8282 * Get the closest tool to a jQuery.Event.
8283 *
8284 * Only tool links are considered, which prevents other elements in the tool such as popups from
8285 * triggering tool group interactions.
8286 *
8287 * @private
8288 * @param {jQuery.Event} e
8289 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8290 */
8291 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
8292 var tool,
8293 $item = $( e.target ).closest( '.oo-ui-tool-link' );
8294
8295 if ( $item.length ) {
8296 tool = $item.parent().data( 'oo-ui-tool' );
8297 }
8298
8299 return tool && !tool.isDisabled() ? tool : null;
8300 };
8301
8302 /**
8303 * Handle tool registry register events.
8304 *
8305 * If a tool is registered after the group is created, we must repopulate the list to account for:
8306 *
8307 * - a tool being added that may be included
8308 * - a tool already included being overridden
8309 *
8310 * @protected
8311 * @param {string} name Symbolic name of tool
8312 */
8313 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
8314 this.populate();
8315 };
8316
8317 /**
8318 * Get the toolbar that contains the toolgroup.
8319 *
8320 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8321 */
8322 OO.ui.ToolGroup.prototype.getToolbar = function () {
8323 return this.toolbar;
8324 };
8325
8326 /**
8327 * Add and remove tools based on configuration.
8328 */
8329 OO.ui.ToolGroup.prototype.populate = function () {
8330 var i, len, name, tool,
8331 toolFactory = this.toolbar.getToolFactory(),
8332 names = {},
8333 add = [],
8334 remove = [],
8335 list = this.toolbar.getToolFactory().getTools(
8336 this.include, this.exclude, this.promote, this.demote
8337 );
8338
8339 // Build a list of needed tools
8340 for ( i = 0, len = list.length; i < len; i++ ) {
8341 name = list[ i ];
8342 if (
8343 // Tool exists
8344 toolFactory.lookup( name ) &&
8345 // Tool is available or is already in this group
8346 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
8347 ) {
8348 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8349 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8350 this.toolbar.tools[ name ] = true;
8351 tool = this.tools[ name ];
8352 if ( !tool ) {
8353 // Auto-initialize tools on first use
8354 this.tools[ name ] = tool = toolFactory.create( name, this );
8355 tool.updateTitle();
8356 }
8357 this.toolbar.reserveTool( tool );
8358 add.push( tool );
8359 names[ name ] = true;
8360 }
8361 }
8362 // Remove tools that are no longer needed
8363 for ( name in this.tools ) {
8364 if ( !names[ name ] ) {
8365 this.tools[ name ].destroy();
8366 this.toolbar.releaseTool( this.tools[ name ] );
8367 remove.push( this.tools[ name ] );
8368 delete this.tools[ name ];
8369 }
8370 }
8371 if ( remove.length ) {
8372 this.removeItems( remove );
8373 }
8374 // Update emptiness state
8375 if ( add.length ) {
8376 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8377 } else {
8378 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8379 }
8380 // Re-add tools (moving existing ones to new locations)
8381 this.addItems( add );
8382 // Disabled state may depend on items
8383 this.updateDisabled();
8384 };
8385
8386 /**
8387 * Destroy toolgroup.
8388 */
8389 OO.ui.ToolGroup.prototype.destroy = function () {
8390 var name;
8391
8392 this.clearItems();
8393 this.toolbar.getToolFactory().disconnect( this );
8394 for ( name in this.tools ) {
8395 this.toolbar.releaseTool( this.tools[ name ] );
8396 this.tools[ name ].disconnect( this ).destroy();
8397 delete this.tools[ name ];
8398 }
8399 this.$element.remove();
8400 };
8401
8402 /**
8403 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8404 * consists of a header that contains the dialog title, a body with the message, and a footer that
8405 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8406 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8407 *
8408 * There are two basic types of message dialogs, confirmation and alert:
8409 *
8410 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8411 * more details about the consequences.
8412 * - **alert**: the dialog title describes which event occurred and the message provides more information
8413 * about why the event occurred.
8414 *
8415 * The MessageDialog class specifies two actions: ‘accept’, the primary
8416 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8417 * passing along the selected action.
8418 *
8419 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8420 *
8421 * @example
8422 * // Example: Creating and opening a message dialog window.
8423 * var messageDialog = new OO.ui.MessageDialog();
8424 *
8425 * // Create and append a window manager.
8426 * var windowManager = new OO.ui.WindowManager();
8427 * $( 'body' ).append( windowManager.$element );
8428 * windowManager.addWindows( [ messageDialog ] );
8429 * // Open the window.
8430 * windowManager.openWindow( messageDialog, {
8431 * title: 'Basic message dialog',
8432 * message: 'This is the message'
8433 * } );
8434 *
8435 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8436 *
8437 * @class
8438 * @extends OO.ui.Dialog
8439 *
8440 * @constructor
8441 * @param {Object} [config] Configuration options
8442 */
8443 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8444 // Parent constructor
8445 OO.ui.MessageDialog.parent.call( this, config );
8446
8447 // Properties
8448 this.verticalActionLayout = null;
8449
8450 // Initialization
8451 this.$element.addClass( 'oo-ui-messageDialog' );
8452 };
8453
8454 /* Setup */
8455
8456 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8457
8458 /* Static Properties */
8459
8460 OO.ui.MessageDialog.static.name = 'message';
8461
8462 OO.ui.MessageDialog.static.size = 'small';
8463
8464 OO.ui.MessageDialog.static.verbose = false;
8465
8466 /**
8467 * Dialog title.
8468 *
8469 * The title of a confirmation dialog describes what a progressive action will do. The
8470 * title of an alert dialog describes which event occurred.
8471 *
8472 * @static
8473 * @inheritable
8474 * @property {jQuery|string|Function|null}
8475 */
8476 OO.ui.MessageDialog.static.title = null;
8477
8478 /**
8479 * The message displayed in the dialog body.
8480 *
8481 * A confirmation message describes the consequences of a progressive action. An alert
8482 * message describes why an event occurred.
8483 *
8484 * @static
8485 * @inheritable
8486 * @property {jQuery|string|Function|null}
8487 */
8488 OO.ui.MessageDialog.static.message = null;
8489
8490 OO.ui.MessageDialog.static.actions = [
8491 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8492 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8493 ];
8494
8495 /* Methods */
8496
8497 /**
8498 * @inheritdoc
8499 */
8500 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8501 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8502
8503 // Events
8504 this.manager.connect( this, {
8505 resize: 'onResize'
8506 } );
8507
8508 return this;
8509 };
8510
8511 /**
8512 * @inheritdoc
8513 */
8514 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8515 this.fitActions();
8516 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8517 };
8518
8519 /**
8520 * Handle window resized events.
8521 *
8522 * @private
8523 */
8524 OO.ui.MessageDialog.prototype.onResize = function () {
8525 var dialog = this;
8526 dialog.fitActions();
8527 // Wait for CSS transition to finish and do it again :(
8528 setTimeout( function () {
8529 dialog.fitActions();
8530 }, 300 );
8531 };
8532
8533 /**
8534 * Toggle action layout between vertical and horizontal.
8535 *
8536 * @private
8537 * @param {boolean} [value] Layout actions vertically, omit to toggle
8538 * @chainable
8539 */
8540 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8541 value = value === undefined ? !this.verticalActionLayout : !!value;
8542
8543 if ( value !== this.verticalActionLayout ) {
8544 this.verticalActionLayout = value;
8545 this.$actions
8546 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8547 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8548 }
8549
8550 return this;
8551 };
8552
8553 /**
8554 * @inheritdoc
8555 */
8556 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8557 if ( action ) {
8558 return new OO.ui.Process( function () {
8559 this.close( { action: action } );
8560 }, this );
8561 }
8562 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8563 };
8564
8565 /**
8566 * @inheritdoc
8567 *
8568 * @param {Object} [data] Dialog opening data
8569 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8570 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8571 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8572 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8573 * action item
8574 */
8575 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8576 data = data || {};
8577
8578 // Parent method
8579 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8580 .next( function () {
8581 this.title.setLabel(
8582 data.title !== undefined ? data.title : this.constructor.static.title
8583 );
8584 this.message.setLabel(
8585 data.message !== undefined ? data.message : this.constructor.static.message
8586 );
8587 this.message.$element.toggleClass(
8588 'oo-ui-messageDialog-message-verbose',
8589 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8590 );
8591 }, this );
8592 };
8593
8594 /**
8595 * @inheritdoc
8596 */
8597 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8598 data = data || {};
8599
8600 // Parent method
8601 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8602 .next( function () {
8603 // Focus the primary action button
8604 var actions = this.actions.get();
8605 actions = actions.filter( function ( action ) {
8606 return action.getFlags().indexOf( 'primary' ) > -1;
8607 } );
8608 if ( actions.length > 0 ) {
8609 actions[ 0 ].$button.focus();
8610 }
8611 }, this );
8612 };
8613
8614 /**
8615 * @inheritdoc
8616 */
8617 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8618 var bodyHeight, oldOverflow,
8619 $scrollable = this.container.$element;
8620
8621 oldOverflow = $scrollable[ 0 ].style.overflow;
8622 $scrollable[ 0 ].style.overflow = 'hidden';
8623
8624 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8625
8626 bodyHeight = this.text.$element.outerHeight( true );
8627 $scrollable[ 0 ].style.overflow = oldOverflow;
8628
8629 return bodyHeight;
8630 };
8631
8632 /**
8633 * @inheritdoc
8634 */
8635 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8636 var $scrollable = this.container.$element;
8637 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8638
8639 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8640 // Need to do it after transition completes (250ms), add 50ms just in case.
8641 setTimeout( function () {
8642 var oldOverflow = $scrollable[ 0 ].style.overflow;
8643 $scrollable[ 0 ].style.overflow = 'hidden';
8644
8645 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8646
8647 $scrollable[ 0 ].style.overflow = oldOverflow;
8648 }, 300 );
8649
8650 return this;
8651 };
8652
8653 /**
8654 * @inheritdoc
8655 */
8656 OO.ui.MessageDialog.prototype.initialize = function () {
8657 // Parent method
8658 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8659
8660 // Properties
8661 this.$actions = $( '<div>' );
8662 this.container = new OO.ui.PanelLayout( {
8663 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8664 } );
8665 this.text = new OO.ui.PanelLayout( {
8666 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8667 } );
8668 this.message = new OO.ui.LabelWidget( {
8669 classes: [ 'oo-ui-messageDialog-message' ]
8670 } );
8671
8672 // Initialization
8673 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8674 this.$content.addClass( 'oo-ui-messageDialog-content' );
8675 this.container.$element.append( this.text.$element );
8676 this.text.$element.append( this.title.$element, this.message.$element );
8677 this.$body.append( this.container.$element );
8678 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8679 this.$foot.append( this.$actions );
8680 };
8681
8682 /**
8683 * @inheritdoc
8684 */
8685 OO.ui.MessageDialog.prototype.attachActions = function () {
8686 var i, len, other, special, others;
8687
8688 // Parent method
8689 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8690
8691 special = this.actions.getSpecial();
8692 others = this.actions.getOthers();
8693
8694 if ( special.safe ) {
8695 this.$actions.append( special.safe.$element );
8696 special.safe.toggleFramed( false );
8697 }
8698 if ( others.length ) {
8699 for ( i = 0, len = others.length; i < len; i++ ) {
8700 other = others[ i ];
8701 this.$actions.append( other.$element );
8702 other.toggleFramed( false );
8703 }
8704 }
8705 if ( special.primary ) {
8706 this.$actions.append( special.primary.$element );
8707 special.primary.toggleFramed( false );
8708 }
8709
8710 if ( !this.isOpening() ) {
8711 // If the dialog is currently opening, this will be called automatically soon.
8712 // This also calls #fitActions.
8713 this.updateSize();
8714 }
8715 };
8716
8717 /**
8718 * Fit action actions into columns or rows.
8719 *
8720 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8721 *
8722 * @private
8723 */
8724 OO.ui.MessageDialog.prototype.fitActions = function () {
8725 var i, len, action,
8726 previous = this.verticalActionLayout,
8727 actions = this.actions.get();
8728
8729 // Detect clipping
8730 this.toggleVerticalActionLayout( false );
8731 for ( i = 0, len = actions.length; i < len; i++ ) {
8732 action = actions[ i ];
8733 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8734 this.toggleVerticalActionLayout( true );
8735 break;
8736 }
8737 }
8738
8739 // Move the body out of the way of the foot
8740 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8741
8742 if ( this.verticalActionLayout !== previous ) {
8743 // We changed the layout, window height might need to be updated.
8744 this.updateSize();
8745 }
8746 };
8747
8748 /**
8749 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8750 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8751 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8752 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8753 * required for each process.
8754 *
8755 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8756 * processes with an animation. The header contains the dialog title as well as
8757 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8758 * a ‘primary’ action on the right (e.g., ‘Done’).
8759 *
8760 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8761 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8762 *
8763 * @example
8764 * // Example: Creating and opening a process dialog window.
8765 * function MyProcessDialog( config ) {
8766 * MyProcessDialog.parent.call( this, config );
8767 * }
8768 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8769 *
8770 * MyProcessDialog.static.title = 'Process dialog';
8771 * MyProcessDialog.static.actions = [
8772 * { action: 'save', label: 'Done', flags: 'primary' },
8773 * { label: 'Cancel', flags: 'safe' }
8774 * ];
8775 *
8776 * MyProcessDialog.prototype.initialize = function () {
8777 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8778 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8779 * 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>' );
8780 * this.$body.append( this.content.$element );
8781 * };
8782 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8783 * var dialog = this;
8784 * if ( action ) {
8785 * return new OO.ui.Process( function () {
8786 * dialog.close( { action: action } );
8787 * } );
8788 * }
8789 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8790 * };
8791 *
8792 * var windowManager = new OO.ui.WindowManager();
8793 * $( 'body' ).append( windowManager.$element );
8794 *
8795 * var dialog = new MyProcessDialog();
8796 * windowManager.addWindows( [ dialog ] );
8797 * windowManager.openWindow( dialog );
8798 *
8799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8800 *
8801 * @abstract
8802 * @class
8803 * @extends OO.ui.Dialog
8804 *
8805 * @constructor
8806 * @param {Object} [config] Configuration options
8807 */
8808 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8809 // Parent constructor
8810 OO.ui.ProcessDialog.parent.call( this, config );
8811
8812 // Properties
8813 this.fitOnOpen = false;
8814
8815 // Initialization
8816 this.$element.addClass( 'oo-ui-processDialog' );
8817 };
8818
8819 /* Setup */
8820
8821 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8822
8823 /* Methods */
8824
8825 /**
8826 * Handle dismiss button click events.
8827 *
8828 * Hides errors.
8829 *
8830 * @private
8831 */
8832 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8833 this.hideErrors();
8834 };
8835
8836 /**
8837 * Handle retry button click events.
8838 *
8839 * Hides errors and then tries again.
8840 *
8841 * @private
8842 */
8843 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8844 this.hideErrors();
8845 this.executeAction( this.currentAction );
8846 };
8847
8848 /**
8849 * @inheritdoc
8850 */
8851 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8852 if ( this.actions.isSpecial( action ) ) {
8853 this.fitLabel();
8854 }
8855 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8856 };
8857
8858 /**
8859 * @inheritdoc
8860 */
8861 OO.ui.ProcessDialog.prototype.initialize = function () {
8862 // Parent method
8863 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8864
8865 // Properties
8866 this.$navigation = $( '<div>' );
8867 this.$location = $( '<div>' );
8868 this.$safeActions = $( '<div>' );
8869 this.$primaryActions = $( '<div>' );
8870 this.$otherActions = $( '<div>' );
8871 this.dismissButton = new OO.ui.ButtonWidget( {
8872 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8873 } );
8874 this.retryButton = new OO.ui.ButtonWidget();
8875 this.$errors = $( '<div>' );
8876 this.$errorsTitle = $( '<div>' );
8877
8878 // Events
8879 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8880 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8881
8882 // Initialization
8883 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8884 this.$location
8885 .append( this.title.$element )
8886 .addClass( 'oo-ui-processDialog-location' );
8887 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8888 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8889 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8890 this.$errorsTitle
8891 .addClass( 'oo-ui-processDialog-errors-title' )
8892 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8893 this.$errors
8894 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8895 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8896 this.$content
8897 .addClass( 'oo-ui-processDialog-content' )
8898 .append( this.$errors );
8899 this.$navigation
8900 .addClass( 'oo-ui-processDialog-navigation' )
8901 .append( this.$safeActions, this.$location, this.$primaryActions );
8902 this.$head.append( this.$navigation );
8903 this.$foot.append( this.$otherActions );
8904 };
8905
8906 /**
8907 * @inheritdoc
8908 */
8909 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8910 var i, len, widgets = [];
8911 for ( i = 0, len = actions.length; i < len; i++ ) {
8912 widgets.push(
8913 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8914 );
8915 }
8916 return widgets;
8917 };
8918
8919 /**
8920 * @inheritdoc
8921 */
8922 OO.ui.ProcessDialog.prototype.attachActions = function () {
8923 var i, len, other, special, others;
8924
8925 // Parent method
8926 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8927
8928 special = this.actions.getSpecial();
8929 others = this.actions.getOthers();
8930 if ( special.primary ) {
8931 this.$primaryActions.append( special.primary.$element );
8932 }
8933 for ( i = 0, len = others.length; i < len; i++ ) {
8934 other = others[ i ];
8935 this.$otherActions.append( other.$element );
8936 }
8937 if ( special.safe ) {
8938 this.$safeActions.append( special.safe.$element );
8939 }
8940
8941 this.fitLabel();
8942 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8943 };
8944
8945 /**
8946 * @inheritdoc
8947 */
8948 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8949 var process = this;
8950 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8951 .fail( function ( errors ) {
8952 process.showErrors( errors || [] );
8953 } );
8954 };
8955
8956 /**
8957 * @inheritdoc
8958 */
8959 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8960 // Parent method
8961 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8962
8963 this.fitLabel();
8964 };
8965
8966 /**
8967 * Fit label between actions.
8968 *
8969 * @private
8970 * @chainable
8971 */
8972 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8973 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8974 size = this.getSizeProperties();
8975
8976 if ( typeof size.width !== 'number' ) {
8977 if ( this.isOpened() ) {
8978 navigationWidth = this.$head.width() - 20;
8979 } else if ( this.isOpening() ) {
8980 if ( !this.fitOnOpen ) {
8981 // Size is relative and the dialog isn't open yet, so wait.
8982 this.manager.opening.done( this.fitLabel.bind( this ) );
8983 this.fitOnOpen = true;
8984 }
8985 return;
8986 } else {
8987 return;
8988 }
8989 } else {
8990 navigationWidth = size.width - 20;
8991 }
8992
8993 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8994 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8995 biggerWidth = Math.max( safeWidth, primaryWidth );
8996
8997 labelWidth = this.title.$element.width();
8998
8999 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
9000 // We have enough space to center the label
9001 leftWidth = rightWidth = biggerWidth;
9002 } else {
9003 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
9004 if ( this.getDir() === 'ltr' ) {
9005 leftWidth = safeWidth;
9006 rightWidth = primaryWidth;
9007 } else {
9008 leftWidth = primaryWidth;
9009 rightWidth = safeWidth;
9010 }
9011 }
9012
9013 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
9014
9015 return this;
9016 };
9017
9018 /**
9019 * Handle errors that occurred during accept or reject processes.
9020 *
9021 * @private
9022 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
9023 */
9024 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
9025 var i, len, $item, actions,
9026 items = [],
9027 abilities = {},
9028 recoverable = true,
9029 warning = false;
9030
9031 if ( errors instanceof OO.ui.Error ) {
9032 errors = [ errors ];
9033 }
9034
9035 for ( i = 0, len = errors.length; i < len; i++ ) {
9036 if ( !errors[ i ].isRecoverable() ) {
9037 recoverable = false;
9038 }
9039 if ( errors[ i ].isWarning() ) {
9040 warning = true;
9041 }
9042 $item = $( '<div>' )
9043 .addClass( 'oo-ui-processDialog-error' )
9044 .append( errors[ i ].getMessage() );
9045 items.push( $item[ 0 ] );
9046 }
9047 this.$errorItems = $( items );
9048 if ( recoverable ) {
9049 abilities[ this.currentAction ] = true;
9050 // Copy the flags from the first matching action
9051 actions = this.actions.get( { actions: this.currentAction } );
9052 if ( actions.length ) {
9053 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
9054 }
9055 } else {
9056 abilities[ this.currentAction ] = false;
9057 this.actions.setAbilities( abilities );
9058 }
9059 if ( warning ) {
9060 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
9061 } else {
9062 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
9063 }
9064 this.retryButton.toggle( recoverable );
9065 this.$errorsTitle.after( this.$errorItems );
9066 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
9067 };
9068
9069 /**
9070 * Hide errors.
9071 *
9072 * @private
9073 */
9074 OO.ui.ProcessDialog.prototype.hideErrors = function () {
9075 this.$errors.addClass( 'oo-ui-element-hidden' );
9076 if ( this.$errorItems ) {
9077 this.$errorItems.remove();
9078 this.$errorItems = null;
9079 }
9080 };
9081
9082 /**
9083 * @inheritdoc
9084 */
9085 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
9086 // Parent method
9087 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
9088 .first( function () {
9089 // Make sure to hide errors
9090 this.hideErrors();
9091 this.fitOnOpen = false;
9092 }, this );
9093 };
9094
9095 /**
9096 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9097 * which is a widget that is specified by reference before any optional configuration settings.
9098 *
9099 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9100 *
9101 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9102 * A left-alignment is used for forms with many fields.
9103 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9104 * A right-alignment is used for long but familiar forms which users tab through,
9105 * verifying the current field with a quick glance at the label.
9106 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9107 * that users fill out from top to bottom.
9108 * - **inline**: The label is placed after the field-widget and aligned to the left.
9109 * An inline-alignment is best used with checkboxes or radio buttons.
9110 *
9111 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9112 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9113 *
9114 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9115 * @class
9116 * @extends OO.ui.Layout
9117 * @mixins OO.ui.mixin.LabelElement
9118 * @mixins OO.ui.mixin.TitledElement
9119 *
9120 * @constructor
9121 * @param {OO.ui.Widget} fieldWidget Field widget
9122 * @param {Object} [config] Configuration options
9123 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9124 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9125 * The array may contain strings or OO.ui.HtmlSnippet instances.
9126 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9127 * The array may contain strings or OO.ui.HtmlSnippet instances.
9128 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9129 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9130 * For important messages, you are advised to use `notices`, as they are always shown.
9131 *
9132 * @throws {Error} An error is thrown if no widget is specified
9133 */
9134 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
9135 var hasInputWidget, div;
9136
9137 // Allow passing positional parameters inside the config object
9138 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9139 config = fieldWidget;
9140 fieldWidget = config.fieldWidget;
9141 }
9142
9143 // Make sure we have required constructor arguments
9144 if ( fieldWidget === undefined ) {
9145 throw new Error( 'Widget not found' );
9146 }
9147
9148 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
9149
9150 // Configuration initialization
9151 config = $.extend( { align: 'left' }, config );
9152
9153 // Parent constructor
9154 OO.ui.FieldLayout.parent.call( this, config );
9155
9156 // Mixin constructors
9157 OO.ui.mixin.LabelElement.call( this, config );
9158 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9159
9160 // Properties
9161 this.fieldWidget = fieldWidget;
9162 this.errors = [];
9163 this.notices = [];
9164 this.$field = $( '<div>' );
9165 this.$messages = $( '<ul>' );
9166 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
9167 this.align = null;
9168 if ( config.help ) {
9169 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9170 classes: [ 'oo-ui-fieldLayout-help' ],
9171 framed: false,
9172 icon: 'info'
9173 } );
9174
9175 div = $( '<div>' );
9176 if ( config.help instanceof OO.ui.HtmlSnippet ) {
9177 div.html( config.help.toString() );
9178 } else {
9179 div.text( config.help );
9180 }
9181 this.popupButtonWidget.getPopup().$body.append(
9182 div.addClass( 'oo-ui-fieldLayout-help-content' )
9183 );
9184 this.$help = this.popupButtonWidget.$element;
9185 } else {
9186 this.$help = $( [] );
9187 }
9188
9189 // Events
9190 if ( hasInputWidget ) {
9191 this.$label.on( 'click', this.onLabelClick.bind( this ) );
9192 }
9193 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
9194
9195 // Initialization
9196 this.$element
9197 .addClass( 'oo-ui-fieldLayout' )
9198 .append( this.$help, this.$body );
9199 this.$body.addClass( 'oo-ui-fieldLayout-body' );
9200 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
9201 this.$field
9202 .addClass( 'oo-ui-fieldLayout-field' )
9203 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
9204 .append( this.fieldWidget.$element );
9205
9206 this.setErrors( config.errors || [] );
9207 this.setNotices( config.notices || [] );
9208 this.setAlignment( config.align );
9209 };
9210
9211 /* Setup */
9212
9213 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
9214 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
9215 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
9216
9217 /* Methods */
9218
9219 /**
9220 * Handle field disable events.
9221 *
9222 * @private
9223 * @param {boolean} value Field is disabled
9224 */
9225 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
9226 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
9227 };
9228
9229 /**
9230 * Handle label mouse click events.
9231 *
9232 * @private
9233 * @param {jQuery.Event} e Mouse click event
9234 */
9235 OO.ui.FieldLayout.prototype.onLabelClick = function () {
9236 this.fieldWidget.simulateLabelClick();
9237 return false;
9238 };
9239
9240 /**
9241 * Get the widget contained by the field.
9242 *
9243 * @return {OO.ui.Widget} Field widget
9244 */
9245 OO.ui.FieldLayout.prototype.getField = function () {
9246 return this.fieldWidget;
9247 };
9248
9249 /**
9250 * @protected
9251 * @param {string} kind 'error' or 'notice'
9252 * @param {string|OO.ui.HtmlSnippet} text
9253 * @return {jQuery}
9254 */
9255 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
9256 var $listItem, $icon, message;
9257 $listItem = $( '<li>' );
9258 if ( kind === 'error' ) {
9259 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
9260 } else if ( kind === 'notice' ) {
9261 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
9262 } else {
9263 $icon = '';
9264 }
9265 message = new OO.ui.LabelWidget( { label: text } );
9266 $listItem
9267 .append( $icon, message.$element )
9268 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
9269 return $listItem;
9270 };
9271
9272 /**
9273 * Set the field alignment mode.
9274 *
9275 * @private
9276 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9277 * @chainable
9278 */
9279 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
9280 if ( value !== this.align ) {
9281 // Default to 'left'
9282 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
9283 value = 'left';
9284 }
9285 // Reorder elements
9286 if ( value === 'inline' ) {
9287 this.$body.append( this.$field, this.$label );
9288 } else {
9289 this.$body.append( this.$label, this.$field );
9290 }
9291 // Set classes. The following classes can be used here:
9292 // * oo-ui-fieldLayout-align-left
9293 // * oo-ui-fieldLayout-align-right
9294 // * oo-ui-fieldLayout-align-top
9295 // * oo-ui-fieldLayout-align-inline
9296 if ( this.align ) {
9297 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
9298 }
9299 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
9300 this.align = value;
9301 }
9302
9303 return this;
9304 };
9305
9306 /**
9307 * Set the list of error messages.
9308 *
9309 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9310 * The array may contain strings or OO.ui.HtmlSnippet instances.
9311 * @chainable
9312 */
9313 OO.ui.FieldLayout.prototype.setErrors = function ( errors ) {
9314 this.errors = errors.slice();
9315 this.updateMessages();
9316 return this;
9317 };
9318
9319 /**
9320 * Set the list of notice messages.
9321 *
9322 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9323 * The array may contain strings or OO.ui.HtmlSnippet instances.
9324 * @chainable
9325 */
9326 OO.ui.FieldLayout.prototype.setNotices = function ( notices ) {
9327 this.notices = notices.slice();
9328 this.updateMessages();
9329 return this;
9330 };
9331
9332 /**
9333 * Update the rendering of error and notice messages.
9334 *
9335 * @private
9336 */
9337 OO.ui.FieldLayout.prototype.updateMessages = function () {
9338 var i;
9339 this.$messages.empty();
9340
9341 if ( this.errors.length || this.notices.length ) {
9342 this.$body.after( this.$messages );
9343 } else {
9344 this.$messages.remove();
9345 return;
9346 }
9347
9348 for ( i = 0; i < this.notices.length; i++ ) {
9349 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
9350 }
9351 for ( i = 0; i < this.errors.length; i++ ) {
9352 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
9353 }
9354 };
9355
9356 /**
9357 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9358 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9359 * is required and is specified before any optional configuration settings.
9360 *
9361 * Labels can be aligned in one of four ways:
9362 *
9363 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9364 * A left-alignment is used for forms with many fields.
9365 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9366 * A right-alignment is used for long but familiar forms which users tab through,
9367 * verifying the current field with a quick glance at the label.
9368 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9369 * that users fill out from top to bottom.
9370 * - **inline**: The label is placed after the field-widget and aligned to the left.
9371 * An inline-alignment is best used with checkboxes or radio buttons.
9372 *
9373 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9374 * text is specified.
9375 *
9376 * @example
9377 * // Example of an ActionFieldLayout
9378 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9379 * new OO.ui.TextInputWidget( {
9380 * placeholder: 'Field widget'
9381 * } ),
9382 * new OO.ui.ButtonWidget( {
9383 * label: 'Button'
9384 * } ),
9385 * {
9386 * label: 'An ActionFieldLayout. This label is aligned top',
9387 * align: 'top',
9388 * help: 'This is help text'
9389 * }
9390 * );
9391 *
9392 * $( 'body' ).append( actionFieldLayout.$element );
9393 *
9394 * @class
9395 * @extends OO.ui.FieldLayout
9396 *
9397 * @constructor
9398 * @param {OO.ui.Widget} fieldWidget Field widget
9399 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9400 */
9401 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9402 // Allow passing positional parameters inside the config object
9403 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9404 config = fieldWidget;
9405 fieldWidget = config.fieldWidget;
9406 buttonWidget = config.buttonWidget;
9407 }
9408
9409 // Parent constructor
9410 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9411
9412 // Properties
9413 this.buttonWidget = buttonWidget;
9414 this.$button = $( '<div>' );
9415 this.$input = $( '<div>' );
9416
9417 // Initialization
9418 this.$element
9419 .addClass( 'oo-ui-actionFieldLayout' );
9420 this.$button
9421 .addClass( 'oo-ui-actionFieldLayout-button' )
9422 .append( this.buttonWidget.$element );
9423 this.$input
9424 .addClass( 'oo-ui-actionFieldLayout-input' )
9425 .append( this.fieldWidget.$element );
9426 this.$field
9427 .append( this.$input, this.$button );
9428 };
9429
9430 /* Setup */
9431
9432 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9433
9434 /**
9435 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9436 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9437 * configured with a label as well. For more information and examples,
9438 * please see the [OOjs UI documentation on MediaWiki][1].
9439 *
9440 * @example
9441 * // Example of a fieldset layout
9442 * var input1 = new OO.ui.TextInputWidget( {
9443 * placeholder: 'A text input field'
9444 * } );
9445 *
9446 * var input2 = new OO.ui.TextInputWidget( {
9447 * placeholder: 'A text input field'
9448 * } );
9449 *
9450 * var fieldset = new OO.ui.FieldsetLayout( {
9451 * label: 'Example of a fieldset layout'
9452 * } );
9453 *
9454 * fieldset.addItems( [
9455 * new OO.ui.FieldLayout( input1, {
9456 * label: 'Field One'
9457 * } ),
9458 * new OO.ui.FieldLayout( input2, {
9459 * label: 'Field Two'
9460 * } )
9461 * ] );
9462 * $( 'body' ).append( fieldset.$element );
9463 *
9464 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9465 *
9466 * @class
9467 * @extends OO.ui.Layout
9468 * @mixins OO.ui.mixin.IconElement
9469 * @mixins OO.ui.mixin.LabelElement
9470 * @mixins OO.ui.mixin.GroupElement
9471 *
9472 * @constructor
9473 * @param {Object} [config] Configuration options
9474 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9475 */
9476 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9477 // Configuration initialization
9478 config = config || {};
9479
9480 // Parent constructor
9481 OO.ui.FieldsetLayout.parent.call( this, config );
9482
9483 // Mixin constructors
9484 OO.ui.mixin.IconElement.call( this, config );
9485 OO.ui.mixin.LabelElement.call( this, config );
9486 OO.ui.mixin.GroupElement.call( this, config );
9487
9488 if ( config.help ) {
9489 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9490 classes: [ 'oo-ui-fieldsetLayout-help' ],
9491 framed: false,
9492 icon: 'info'
9493 } );
9494
9495 this.popupButtonWidget.getPopup().$body.append(
9496 $( '<div>' )
9497 .text( config.help )
9498 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9499 );
9500 this.$help = this.popupButtonWidget.$element;
9501 } else {
9502 this.$help = $( [] );
9503 }
9504
9505 // Initialization
9506 this.$element
9507 .addClass( 'oo-ui-fieldsetLayout' )
9508 .prepend( this.$help, this.$icon, this.$label, this.$group );
9509 if ( Array.isArray( config.items ) ) {
9510 this.addItems( config.items );
9511 }
9512 };
9513
9514 /* Setup */
9515
9516 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9517 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9518 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9519 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9520
9521 /**
9522 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9523 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9524 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9525 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9526 *
9527 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9528 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9529 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9530 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9531 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9532 * often have simplified APIs to match the capabilities of HTML forms.
9533 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9534 *
9535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9536 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9537 *
9538 * @example
9539 * // Example of a form layout that wraps a fieldset layout
9540 * var input1 = new OO.ui.TextInputWidget( {
9541 * placeholder: 'Username'
9542 * } );
9543 * var input2 = new OO.ui.TextInputWidget( {
9544 * placeholder: 'Password',
9545 * type: 'password'
9546 * } );
9547 * var submit = new OO.ui.ButtonInputWidget( {
9548 * label: 'Submit'
9549 * } );
9550 *
9551 * var fieldset = new OO.ui.FieldsetLayout( {
9552 * label: 'A form layout'
9553 * } );
9554 * fieldset.addItems( [
9555 * new OO.ui.FieldLayout( input1, {
9556 * label: 'Username',
9557 * align: 'top'
9558 * } ),
9559 * new OO.ui.FieldLayout( input2, {
9560 * label: 'Password',
9561 * align: 'top'
9562 * } ),
9563 * new OO.ui.FieldLayout( submit )
9564 * ] );
9565 * var form = new OO.ui.FormLayout( {
9566 * items: [ fieldset ],
9567 * action: '/api/formhandler',
9568 * method: 'get'
9569 * } )
9570 * $( 'body' ).append( form.$element );
9571 *
9572 * @class
9573 * @extends OO.ui.Layout
9574 * @mixins OO.ui.mixin.GroupElement
9575 *
9576 * @constructor
9577 * @param {Object} [config] Configuration options
9578 * @cfg {string} [method] HTML form `method` attribute
9579 * @cfg {string} [action] HTML form `action` attribute
9580 * @cfg {string} [enctype] HTML form `enctype` attribute
9581 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9582 */
9583 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9584 // Configuration initialization
9585 config = config || {};
9586
9587 // Parent constructor
9588 OO.ui.FormLayout.parent.call( this, config );
9589
9590 // Mixin constructors
9591 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9592
9593 // Events
9594 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9595
9596 // Make sure the action is safe
9597 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9598 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9599 }
9600
9601 // Initialization
9602 this.$element
9603 .addClass( 'oo-ui-formLayout' )
9604 .attr( {
9605 method: config.method,
9606 action: config.action,
9607 enctype: config.enctype
9608 } );
9609 if ( Array.isArray( config.items ) ) {
9610 this.addItems( config.items );
9611 }
9612 };
9613
9614 /* Setup */
9615
9616 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9617 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9618
9619 /* Events */
9620
9621 /**
9622 * A 'submit' event is emitted when the form is submitted.
9623 *
9624 * @event submit
9625 */
9626
9627 /* Static Properties */
9628
9629 OO.ui.FormLayout.static.tagName = 'form';
9630
9631 /* Methods */
9632
9633 /**
9634 * Handle form submit events.
9635 *
9636 * @private
9637 * @param {jQuery.Event} e Submit event
9638 * @fires submit
9639 */
9640 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9641 if ( this.emit( 'submit' ) ) {
9642 return false;
9643 }
9644 };
9645
9646 /**
9647 * 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)
9648 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9649 *
9650 * @example
9651 * var menuLayout = new OO.ui.MenuLayout( {
9652 * position: 'top'
9653 * } ),
9654 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9655 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9656 * select = new OO.ui.SelectWidget( {
9657 * items: [
9658 * new OO.ui.OptionWidget( {
9659 * data: 'before',
9660 * label: 'Before',
9661 * } ),
9662 * new OO.ui.OptionWidget( {
9663 * data: 'after',
9664 * label: 'After',
9665 * } ),
9666 * new OO.ui.OptionWidget( {
9667 * data: 'top',
9668 * label: 'Top',
9669 * } ),
9670 * new OO.ui.OptionWidget( {
9671 * data: 'bottom',
9672 * label: 'Bottom',
9673 * } )
9674 * ]
9675 * } ).on( 'select', function ( item ) {
9676 * menuLayout.setMenuPosition( item.getData() );
9677 * } );
9678 *
9679 * menuLayout.$menu.append(
9680 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9681 * );
9682 * menuLayout.$content.append(
9683 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9684 * );
9685 * $( 'body' ).append( menuLayout.$element );
9686 *
9687 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9688 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9689 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9690 * may be omitted.
9691 *
9692 * .oo-ui-menuLayout-menu {
9693 * height: 200px;
9694 * width: 200px;
9695 * }
9696 * .oo-ui-menuLayout-content {
9697 * top: 200px;
9698 * left: 200px;
9699 * right: 200px;
9700 * bottom: 200px;
9701 * }
9702 *
9703 * @class
9704 * @extends OO.ui.Layout
9705 *
9706 * @constructor
9707 * @param {Object} [config] Configuration options
9708 * @cfg {boolean} [showMenu=true] Show menu
9709 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9710 */
9711 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9712 // Configuration initialization
9713 config = $.extend( {
9714 showMenu: true,
9715 menuPosition: 'before'
9716 }, config );
9717
9718 // Parent constructor
9719 OO.ui.MenuLayout.parent.call( this, config );
9720
9721 /**
9722 * Menu DOM node
9723 *
9724 * @property {jQuery}
9725 */
9726 this.$menu = $( '<div>' );
9727 /**
9728 * Content DOM node
9729 *
9730 * @property {jQuery}
9731 */
9732 this.$content = $( '<div>' );
9733
9734 // Initialization
9735 this.$menu
9736 .addClass( 'oo-ui-menuLayout-menu' );
9737 this.$content.addClass( 'oo-ui-menuLayout-content' );
9738 this.$element
9739 .addClass( 'oo-ui-menuLayout' )
9740 .append( this.$content, this.$menu );
9741 this.setMenuPosition( config.menuPosition );
9742 this.toggleMenu( config.showMenu );
9743 };
9744
9745 /* Setup */
9746
9747 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9748
9749 /* Methods */
9750
9751 /**
9752 * Toggle menu.
9753 *
9754 * @param {boolean} showMenu Show menu, omit to toggle
9755 * @chainable
9756 */
9757 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9758 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9759
9760 if ( this.showMenu !== showMenu ) {
9761 this.showMenu = showMenu;
9762 this.$element
9763 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9764 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9765 }
9766
9767 return this;
9768 };
9769
9770 /**
9771 * Check if menu is visible
9772 *
9773 * @return {boolean} Menu is visible
9774 */
9775 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9776 return this.showMenu;
9777 };
9778
9779 /**
9780 * Set menu position.
9781 *
9782 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9783 * @throws {Error} If position value is not supported
9784 * @chainable
9785 */
9786 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9787 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9788 this.menuPosition = position;
9789 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9790
9791 return this;
9792 };
9793
9794 /**
9795 * Get menu position.
9796 *
9797 * @return {string} Menu position
9798 */
9799 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9800 return this.menuPosition;
9801 };
9802
9803 /**
9804 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9805 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9806 * through the pages and select which one to display. By default, only one page is
9807 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9808 * the booklet layout automatically focuses on the first focusable element, unless the
9809 * default setting is changed. Optionally, booklets can be configured to show
9810 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9811 *
9812 * @example
9813 * // Example of a BookletLayout that contains two PageLayouts.
9814 *
9815 * function PageOneLayout( name, config ) {
9816 * PageOneLayout.parent.call( this, name, config );
9817 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9818 * }
9819 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9820 * PageOneLayout.prototype.setupOutlineItem = function () {
9821 * this.outlineItem.setLabel( 'Page One' );
9822 * };
9823 *
9824 * function PageTwoLayout( name, config ) {
9825 * PageTwoLayout.parent.call( this, name, config );
9826 * this.$element.append( '<p>Second page</p>' );
9827 * }
9828 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9829 * PageTwoLayout.prototype.setupOutlineItem = function () {
9830 * this.outlineItem.setLabel( 'Page Two' );
9831 * };
9832 *
9833 * var page1 = new PageOneLayout( 'one' ),
9834 * page2 = new PageTwoLayout( 'two' );
9835 *
9836 * var booklet = new OO.ui.BookletLayout( {
9837 * outlined: true
9838 * } );
9839 *
9840 * booklet.addPages ( [ page1, page2 ] );
9841 * $( 'body' ).append( booklet.$element );
9842 *
9843 * @class
9844 * @extends OO.ui.MenuLayout
9845 *
9846 * @constructor
9847 * @param {Object} [config] Configuration options
9848 * @cfg {boolean} [continuous=false] Show all pages, one after another
9849 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9850 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9851 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9852 */
9853 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9854 // Configuration initialization
9855 config = config || {};
9856
9857 // Parent constructor
9858 OO.ui.BookletLayout.parent.call( this, config );
9859
9860 // Properties
9861 this.currentPageName = null;
9862 this.pages = {};
9863 this.ignoreFocus = false;
9864 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9865 this.$content.append( this.stackLayout.$element );
9866 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9867 this.outlineVisible = false;
9868 this.outlined = !!config.outlined;
9869 if ( this.outlined ) {
9870 this.editable = !!config.editable;
9871 this.outlineControlsWidget = null;
9872 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9873 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9874 this.$menu.append( this.outlinePanel.$element );
9875 this.outlineVisible = true;
9876 if ( this.editable ) {
9877 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9878 this.outlineSelectWidget
9879 );
9880 }
9881 }
9882 this.toggleMenu( this.outlined );
9883
9884 // Events
9885 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9886 if ( this.outlined ) {
9887 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9888 this.scrolling = false;
9889 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
9890 }
9891 if ( this.autoFocus ) {
9892 // Event 'focus' does not bubble, but 'focusin' does
9893 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9894 }
9895
9896 // Initialization
9897 this.$element.addClass( 'oo-ui-bookletLayout' );
9898 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9899 if ( this.outlined ) {
9900 this.outlinePanel.$element
9901 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9902 .append( this.outlineSelectWidget.$element );
9903 if ( this.editable ) {
9904 this.outlinePanel.$element
9905 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9906 .append( this.outlineControlsWidget.$element );
9907 }
9908 }
9909 };
9910
9911 /* Setup */
9912
9913 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9914
9915 /* Events */
9916
9917 /**
9918 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9919 * @event set
9920 * @param {OO.ui.PageLayout} page Current page
9921 */
9922
9923 /**
9924 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9925 *
9926 * @event add
9927 * @param {OO.ui.PageLayout[]} page Added pages
9928 * @param {number} index Index pages were added at
9929 */
9930
9931 /**
9932 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9933 * {@link #removePages removed} from the booklet.
9934 *
9935 * @event remove
9936 * @param {OO.ui.PageLayout[]} pages Removed pages
9937 */
9938
9939 /* Methods */
9940
9941 /**
9942 * Handle stack layout focus.
9943 *
9944 * @private
9945 * @param {jQuery.Event} e Focusin event
9946 */
9947 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9948 var name, $target;
9949
9950 // Find the page that an element was focused within
9951 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9952 for ( name in this.pages ) {
9953 // Check for page match, exclude current page to find only page changes
9954 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9955 this.setPage( name );
9956 break;
9957 }
9958 }
9959 };
9960
9961 /**
9962 * Handle visibleItemChange events from the stackLayout
9963 *
9964 * The next visible page is set as the current page by selecting it
9965 * in the outline
9966 *
9967 * @param {OO.ui.PageLayout} page The next visible page in the layout
9968 */
9969 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
9970 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
9971 // try and scroll the item into view again.
9972 this.scrolling = true;
9973 this.outlineSelectWidget.selectItemByData( page.getName() );
9974 this.scrolling = false;
9975 };
9976
9977 /**
9978 * Handle stack layout set events.
9979 *
9980 * @private
9981 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9982 */
9983 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9984 var layout = this;
9985 if ( !this.scrolling && page ) {
9986 page.scrollElementIntoView( { complete: function () {
9987 if ( layout.autoFocus ) {
9988 layout.focus();
9989 }
9990 } } );
9991 }
9992 };
9993
9994 /**
9995 * Focus the first input in the current page.
9996 *
9997 * If no page is selected, the first selectable page will be selected.
9998 * If the focus is already in an element on the current page, nothing will happen.
9999 * @param {number} [itemIndex] A specific item to focus on
10000 */
10001 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
10002 var page,
10003 items = this.stackLayout.getItems();
10004
10005 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10006 page = items[ itemIndex ];
10007 } else {
10008 page = this.stackLayout.getCurrentItem();
10009 }
10010
10011 if ( !page && this.outlined ) {
10012 this.selectFirstSelectablePage();
10013 page = this.stackLayout.getCurrentItem();
10014 }
10015 if ( !page ) {
10016 return;
10017 }
10018 // Only change the focus if is not already in the current page
10019 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10020 page.focus();
10021 }
10022 };
10023
10024 /**
10025 * Find the first focusable input in the booklet layout and focus
10026 * on it.
10027 */
10028 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
10029 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10030 };
10031
10032 /**
10033 * Handle outline widget select events.
10034 *
10035 * @private
10036 * @param {OO.ui.OptionWidget|null} item Selected item
10037 */
10038 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
10039 if ( item ) {
10040 this.setPage( item.getData() );
10041 }
10042 };
10043
10044 /**
10045 * Check if booklet has an outline.
10046 *
10047 * @return {boolean} Booklet has an outline
10048 */
10049 OO.ui.BookletLayout.prototype.isOutlined = function () {
10050 return this.outlined;
10051 };
10052
10053 /**
10054 * Check if booklet has editing controls.
10055 *
10056 * @return {boolean} Booklet is editable
10057 */
10058 OO.ui.BookletLayout.prototype.isEditable = function () {
10059 return this.editable;
10060 };
10061
10062 /**
10063 * Check if booklet has a visible outline.
10064 *
10065 * @return {boolean} Outline is visible
10066 */
10067 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
10068 return this.outlined && this.outlineVisible;
10069 };
10070
10071 /**
10072 * Hide or show the outline.
10073 *
10074 * @param {boolean} [show] Show outline, omit to invert current state
10075 * @chainable
10076 */
10077 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
10078 if ( this.outlined ) {
10079 show = show === undefined ? !this.outlineVisible : !!show;
10080 this.outlineVisible = show;
10081 this.toggleMenu( show );
10082 }
10083
10084 return this;
10085 };
10086
10087 /**
10088 * Get the page closest to the specified page.
10089 *
10090 * @param {OO.ui.PageLayout} page Page to use as a reference point
10091 * @return {OO.ui.PageLayout|null} Page closest to the specified page
10092 */
10093 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
10094 var next, prev, level,
10095 pages = this.stackLayout.getItems(),
10096 index = pages.indexOf( page );
10097
10098 if ( index !== -1 ) {
10099 next = pages[ index + 1 ];
10100 prev = pages[ index - 1 ];
10101 // Prefer adjacent pages at the same level
10102 if ( this.outlined ) {
10103 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
10104 if (
10105 prev &&
10106 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
10107 ) {
10108 return prev;
10109 }
10110 if (
10111 next &&
10112 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
10113 ) {
10114 return next;
10115 }
10116 }
10117 }
10118 return prev || next || null;
10119 };
10120
10121 /**
10122 * Get the outline widget.
10123 *
10124 * If the booklet is not outlined, the method will return `null`.
10125 *
10126 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
10127 */
10128 OO.ui.BookletLayout.prototype.getOutline = function () {
10129 return this.outlineSelectWidget;
10130 };
10131
10132 /**
10133 * Get the outline controls widget.
10134 *
10135 * If the outline is not editable, the method will return `null`.
10136 *
10137 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
10138 */
10139 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
10140 return this.outlineControlsWidget;
10141 };
10142
10143 /**
10144 * Get a page by its symbolic name.
10145 *
10146 * @param {string} name Symbolic name of page
10147 * @return {OO.ui.PageLayout|undefined} Page, if found
10148 */
10149 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
10150 return this.pages[ name ];
10151 };
10152
10153 /**
10154 * Get the current page.
10155 *
10156 * @return {OO.ui.PageLayout|undefined} Current page, if found
10157 */
10158 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
10159 var name = this.getCurrentPageName();
10160 return name ? this.getPage( name ) : undefined;
10161 };
10162
10163 /**
10164 * Get the symbolic name of the current page.
10165 *
10166 * @return {string|null} Symbolic name of the current page
10167 */
10168 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
10169 return this.currentPageName;
10170 };
10171
10172 /**
10173 * Add pages to the booklet layout
10174 *
10175 * When pages are added with the same names as existing pages, the existing pages will be
10176 * automatically removed before the new pages are added.
10177 *
10178 * @param {OO.ui.PageLayout[]} pages Pages to add
10179 * @param {number} index Index of the insertion point
10180 * @fires add
10181 * @chainable
10182 */
10183 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
10184 var i, len, name, page, item, currentIndex,
10185 stackLayoutPages = this.stackLayout.getItems(),
10186 remove = [],
10187 items = [];
10188
10189 // Remove pages with same names
10190 for ( i = 0, len = pages.length; i < len; i++ ) {
10191 page = pages[ i ];
10192 name = page.getName();
10193
10194 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
10195 // Correct the insertion index
10196 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
10197 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10198 index--;
10199 }
10200 remove.push( this.pages[ name ] );
10201 }
10202 }
10203 if ( remove.length ) {
10204 this.removePages( remove );
10205 }
10206
10207 // Add new pages
10208 for ( i = 0, len = pages.length; i < len; i++ ) {
10209 page = pages[ i ];
10210 name = page.getName();
10211 this.pages[ page.getName() ] = page;
10212 if ( this.outlined ) {
10213 item = new OO.ui.OutlineOptionWidget( { data: name } );
10214 page.setOutlineItem( item );
10215 items.push( item );
10216 }
10217 }
10218
10219 if ( this.outlined && items.length ) {
10220 this.outlineSelectWidget.addItems( items, index );
10221 this.selectFirstSelectablePage();
10222 }
10223 this.stackLayout.addItems( pages, index );
10224 this.emit( 'add', pages, index );
10225
10226 return this;
10227 };
10228
10229 /**
10230 * Remove the specified pages from the booklet layout.
10231 *
10232 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10233 *
10234 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10235 * @fires remove
10236 * @chainable
10237 */
10238 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
10239 var i, len, name, page,
10240 items = [];
10241
10242 for ( i = 0, len = pages.length; i < len; i++ ) {
10243 page = pages[ i ];
10244 name = page.getName();
10245 delete this.pages[ name ];
10246 if ( this.outlined ) {
10247 items.push( this.outlineSelectWidget.getItemFromData( name ) );
10248 page.setOutlineItem( null );
10249 }
10250 }
10251 if ( this.outlined && items.length ) {
10252 this.outlineSelectWidget.removeItems( items );
10253 this.selectFirstSelectablePage();
10254 }
10255 this.stackLayout.removeItems( pages );
10256 this.emit( 'remove', pages );
10257
10258 return this;
10259 };
10260
10261 /**
10262 * Clear all pages from the booklet layout.
10263 *
10264 * To remove only a subset of pages from the booklet, use the #removePages method.
10265 *
10266 * @fires remove
10267 * @chainable
10268 */
10269 OO.ui.BookletLayout.prototype.clearPages = function () {
10270 var i, len,
10271 pages = this.stackLayout.getItems();
10272
10273 this.pages = {};
10274 this.currentPageName = null;
10275 if ( this.outlined ) {
10276 this.outlineSelectWidget.clearItems();
10277 for ( i = 0, len = pages.length; i < len; i++ ) {
10278 pages[ i ].setOutlineItem( null );
10279 }
10280 }
10281 this.stackLayout.clearItems();
10282
10283 this.emit( 'remove', pages );
10284
10285 return this;
10286 };
10287
10288 /**
10289 * Set the current page by symbolic name.
10290 *
10291 * @fires set
10292 * @param {string} name Symbolic name of page
10293 */
10294 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
10295 var selectedItem,
10296 $focused,
10297 page = this.pages[ name ],
10298 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
10299
10300 if ( name !== this.currentPageName ) {
10301 if ( this.outlined ) {
10302 selectedItem = this.outlineSelectWidget.getSelectedItem();
10303 if ( selectedItem && selectedItem.getData() !== name ) {
10304 this.outlineSelectWidget.selectItemByData( name );
10305 }
10306 }
10307 if ( page ) {
10308 if ( previousPage ) {
10309 previousPage.setActive( false );
10310 // Blur anything focused if the next page doesn't have anything focusable.
10311 // This is not needed if the next page has something focusable (because once it is focused
10312 // this blur happens automatically). If the layout is non-continuous, this check is
10313 // meaningless because the next page is not visible yet and thus can't hold focus.
10314 if (
10315 this.autoFocus &&
10316 this.stackLayout.continuous &&
10317 OO.ui.findFocusable( page.$element ).length !== 0
10318 ) {
10319 $focused = previousPage.$element.find( ':focus' );
10320 if ( $focused.length ) {
10321 $focused[ 0 ].blur();
10322 }
10323 }
10324 }
10325 this.currentPageName = name;
10326 page.setActive( true );
10327 this.stackLayout.setItem( page );
10328 if ( !this.stackLayout.continuous && previousPage ) {
10329 // This should not be necessary, since any inputs on the previous page should have been
10330 // blurred when it was hidden, but browsers are not very consistent about this.
10331 $focused = previousPage.$element.find( ':focus' );
10332 if ( $focused.length ) {
10333 $focused[ 0 ].blur();
10334 }
10335 }
10336 this.emit( 'set', page );
10337 }
10338 }
10339 };
10340
10341 /**
10342 * Select the first selectable page.
10343 *
10344 * @chainable
10345 */
10346 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
10347 if ( !this.outlineSelectWidget.getSelectedItem() ) {
10348 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
10349 }
10350
10351 return this;
10352 };
10353
10354 /**
10355 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10356 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10357 * select which one to display. By default, only one card is displayed at a time. When a user
10358 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10359 * unless the default setting is changed.
10360 *
10361 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10362 *
10363 * @example
10364 * // Example of a IndexLayout that contains two CardLayouts.
10365 *
10366 * function CardOneLayout( name, config ) {
10367 * CardOneLayout.parent.call( this, name, config );
10368 * this.$element.append( '<p>First card</p>' );
10369 * }
10370 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10371 * CardOneLayout.prototype.setupTabItem = function () {
10372 * this.tabItem.setLabel( 'Card one' );
10373 * };
10374 *
10375 * var card1 = new CardOneLayout( 'one' ),
10376 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10377 *
10378 * card2.$element.append( '<p>Second card</p>' );
10379 *
10380 * var index = new OO.ui.IndexLayout();
10381 *
10382 * index.addCards ( [ card1, card2 ] );
10383 * $( 'body' ).append( index.$element );
10384 *
10385 * @class
10386 * @extends OO.ui.MenuLayout
10387 *
10388 * @constructor
10389 * @param {Object} [config] Configuration options
10390 * @cfg {boolean} [continuous=false] Show all cards, one after another
10391 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10392 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10393 */
10394 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10395 // Configuration initialization
10396 config = $.extend( {}, config, { menuPosition: 'top' } );
10397
10398 // Parent constructor
10399 OO.ui.IndexLayout.parent.call( this, config );
10400
10401 // Properties
10402 this.currentCardName = null;
10403 this.cards = {};
10404 this.ignoreFocus = false;
10405 this.stackLayout = new OO.ui.StackLayout( {
10406 continuous: !!config.continuous,
10407 expanded: config.expanded
10408 } );
10409 this.$content.append( this.stackLayout.$element );
10410 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10411
10412 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10413 this.tabPanel = new OO.ui.PanelLayout();
10414 this.$menu.append( this.tabPanel.$element );
10415
10416 this.toggleMenu( true );
10417
10418 // Events
10419 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10420 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10421 if ( this.autoFocus ) {
10422 // Event 'focus' does not bubble, but 'focusin' does
10423 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10424 }
10425
10426 // Initialization
10427 this.$element.addClass( 'oo-ui-indexLayout' );
10428 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10429 this.tabPanel.$element
10430 .addClass( 'oo-ui-indexLayout-tabPanel' )
10431 .append( this.tabSelectWidget.$element );
10432 };
10433
10434 /* Setup */
10435
10436 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10437
10438 /* Events */
10439
10440 /**
10441 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10442 * @event set
10443 * @param {OO.ui.CardLayout} card Current card
10444 */
10445
10446 /**
10447 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10448 *
10449 * @event add
10450 * @param {OO.ui.CardLayout[]} card Added cards
10451 * @param {number} index Index cards were added at
10452 */
10453
10454 /**
10455 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10456 * {@link #removeCards removed} from the index.
10457 *
10458 * @event remove
10459 * @param {OO.ui.CardLayout[]} cards Removed cards
10460 */
10461
10462 /* Methods */
10463
10464 /**
10465 * Handle stack layout focus.
10466 *
10467 * @private
10468 * @param {jQuery.Event} e Focusin event
10469 */
10470 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10471 var name, $target;
10472
10473 // Find the card that an element was focused within
10474 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10475 for ( name in this.cards ) {
10476 // Check for card match, exclude current card to find only card changes
10477 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10478 this.setCard( name );
10479 break;
10480 }
10481 }
10482 };
10483
10484 /**
10485 * Handle stack layout set events.
10486 *
10487 * @private
10488 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10489 */
10490 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10491 var layout = this;
10492 if ( card ) {
10493 card.scrollElementIntoView( { complete: function () {
10494 if ( layout.autoFocus ) {
10495 layout.focus();
10496 }
10497 } } );
10498 }
10499 };
10500
10501 /**
10502 * Focus the first input in the current card.
10503 *
10504 * If no card is selected, the first selectable card will be selected.
10505 * If the focus is already in an element on the current card, nothing will happen.
10506 * @param {number} [itemIndex] A specific item to focus on
10507 */
10508 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10509 var card,
10510 items = this.stackLayout.getItems();
10511
10512 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10513 card = items[ itemIndex ];
10514 } else {
10515 card = this.stackLayout.getCurrentItem();
10516 }
10517
10518 if ( !card ) {
10519 this.selectFirstSelectableCard();
10520 card = this.stackLayout.getCurrentItem();
10521 }
10522 if ( !card ) {
10523 return;
10524 }
10525 // Only change the focus if is not already in the current page
10526 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
10527 card.focus();
10528 }
10529 };
10530
10531 /**
10532 * Find the first focusable input in the index layout and focus
10533 * on it.
10534 */
10535 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10536 OO.ui.findFocusable( this.stackLayout.$element ).focus();
10537 };
10538
10539 /**
10540 * Handle tab widget select events.
10541 *
10542 * @private
10543 * @param {OO.ui.OptionWidget|null} item Selected item
10544 */
10545 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10546 if ( item ) {
10547 this.setCard( item.getData() );
10548 }
10549 };
10550
10551 /**
10552 * Get the card closest to the specified card.
10553 *
10554 * @param {OO.ui.CardLayout} card Card to use as a reference point
10555 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10556 */
10557 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10558 var next, prev, level,
10559 cards = this.stackLayout.getItems(),
10560 index = cards.indexOf( card );
10561
10562 if ( index !== -1 ) {
10563 next = cards[ index + 1 ];
10564 prev = cards[ index - 1 ];
10565 // Prefer adjacent cards at the same level
10566 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10567 if (
10568 prev &&
10569 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10570 ) {
10571 return prev;
10572 }
10573 if (
10574 next &&
10575 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10576 ) {
10577 return next;
10578 }
10579 }
10580 return prev || next || null;
10581 };
10582
10583 /**
10584 * Get the tabs widget.
10585 *
10586 * @return {OO.ui.TabSelectWidget} Tabs widget
10587 */
10588 OO.ui.IndexLayout.prototype.getTabs = function () {
10589 return this.tabSelectWidget;
10590 };
10591
10592 /**
10593 * Get a card by its symbolic name.
10594 *
10595 * @param {string} name Symbolic name of card
10596 * @return {OO.ui.CardLayout|undefined} Card, if found
10597 */
10598 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10599 return this.cards[ name ];
10600 };
10601
10602 /**
10603 * Get the current card.
10604 *
10605 * @return {OO.ui.CardLayout|undefined} Current card, if found
10606 */
10607 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10608 var name = this.getCurrentCardName();
10609 return name ? this.getCard( name ) : undefined;
10610 };
10611
10612 /**
10613 * Get the symbolic name of the current card.
10614 *
10615 * @return {string|null} Symbolic name of the current card
10616 */
10617 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10618 return this.currentCardName;
10619 };
10620
10621 /**
10622 * Add cards to the index layout
10623 *
10624 * When cards are added with the same names as existing cards, the existing cards will be
10625 * automatically removed before the new cards are added.
10626 *
10627 * @param {OO.ui.CardLayout[]} cards Cards to add
10628 * @param {number} index Index of the insertion point
10629 * @fires add
10630 * @chainable
10631 */
10632 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10633 var i, len, name, card, item, currentIndex,
10634 stackLayoutCards = this.stackLayout.getItems(),
10635 remove = [],
10636 items = [];
10637
10638 // Remove cards with same names
10639 for ( i = 0, len = cards.length; i < len; i++ ) {
10640 card = cards[ i ];
10641 name = card.getName();
10642
10643 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10644 // Correct the insertion index
10645 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10646 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10647 index--;
10648 }
10649 remove.push( this.cards[ name ] );
10650 }
10651 }
10652 if ( remove.length ) {
10653 this.removeCards( remove );
10654 }
10655
10656 // Add new cards
10657 for ( i = 0, len = cards.length; i < len; i++ ) {
10658 card = cards[ i ];
10659 name = card.getName();
10660 this.cards[ card.getName() ] = card;
10661 item = new OO.ui.TabOptionWidget( { data: name } );
10662 card.setTabItem( item );
10663 items.push( item );
10664 }
10665
10666 if ( items.length ) {
10667 this.tabSelectWidget.addItems( items, index );
10668 this.selectFirstSelectableCard();
10669 }
10670 this.stackLayout.addItems( cards, index );
10671 this.emit( 'add', cards, index );
10672
10673 return this;
10674 };
10675
10676 /**
10677 * Remove the specified cards from the index layout.
10678 *
10679 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10680 *
10681 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10682 * @fires remove
10683 * @chainable
10684 */
10685 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10686 var i, len, name, card,
10687 items = [];
10688
10689 for ( i = 0, len = cards.length; i < len; i++ ) {
10690 card = cards[ i ];
10691 name = card.getName();
10692 delete this.cards[ name ];
10693 items.push( this.tabSelectWidget.getItemFromData( name ) );
10694 card.setTabItem( null );
10695 }
10696 if ( items.length ) {
10697 this.tabSelectWidget.removeItems( items );
10698 this.selectFirstSelectableCard();
10699 }
10700 this.stackLayout.removeItems( cards );
10701 this.emit( 'remove', cards );
10702
10703 return this;
10704 };
10705
10706 /**
10707 * Clear all cards from the index layout.
10708 *
10709 * To remove only a subset of cards from the index, use the #removeCards method.
10710 *
10711 * @fires remove
10712 * @chainable
10713 */
10714 OO.ui.IndexLayout.prototype.clearCards = function () {
10715 var i, len,
10716 cards = this.stackLayout.getItems();
10717
10718 this.cards = {};
10719 this.currentCardName = null;
10720 this.tabSelectWidget.clearItems();
10721 for ( i = 0, len = cards.length; i < len; i++ ) {
10722 cards[ i ].setTabItem( null );
10723 }
10724 this.stackLayout.clearItems();
10725
10726 this.emit( 'remove', cards );
10727
10728 return this;
10729 };
10730
10731 /**
10732 * Set the current card by symbolic name.
10733 *
10734 * @fires set
10735 * @param {string} name Symbolic name of card
10736 */
10737 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10738 var selectedItem,
10739 $focused,
10740 card = this.cards[ name ],
10741 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
10742
10743 if ( name !== this.currentCardName ) {
10744 selectedItem = this.tabSelectWidget.getSelectedItem();
10745 if ( selectedItem && selectedItem.getData() !== name ) {
10746 this.tabSelectWidget.selectItemByData( name );
10747 }
10748 if ( card ) {
10749 if ( previousCard ) {
10750 previousCard.setActive( false );
10751 // Blur anything focused if the next card doesn't have anything focusable.
10752 // This is not needed if the next card has something focusable (because once it is focused
10753 // this blur happens automatically). If the layout is non-continuous, this check is
10754 // meaningless because the next card is not visible yet and thus can't hold focus.
10755 if (
10756 this.autoFocus &&
10757 this.stackLayout.continuous &&
10758 OO.ui.findFocusable( card.$element ).length !== 0
10759 ) {
10760 $focused = previousCard.$element.find( ':focus' );
10761 if ( $focused.length ) {
10762 $focused[ 0 ].blur();
10763 }
10764 }
10765 }
10766 this.currentCardName = name;
10767 card.setActive( true );
10768 this.stackLayout.setItem( card );
10769 if ( !this.stackLayout.continuous && previousCard ) {
10770 // This should not be necessary, since any inputs on the previous card should have been
10771 // blurred when it was hidden, but browsers are not very consistent about this.
10772 $focused = previousCard.$element.find( ':focus' );
10773 if ( $focused.length ) {
10774 $focused[ 0 ].blur();
10775 }
10776 }
10777 this.emit( 'set', card );
10778 }
10779 }
10780 };
10781
10782 /**
10783 * Select the first selectable card.
10784 *
10785 * @chainable
10786 */
10787 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10788 if ( !this.tabSelectWidget.getSelectedItem() ) {
10789 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10790 }
10791
10792 return this;
10793 };
10794
10795 /**
10796 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10797 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10798 *
10799 * @example
10800 * // Example of a panel layout
10801 * var panel = new OO.ui.PanelLayout( {
10802 * expanded: false,
10803 * framed: true,
10804 * padded: true,
10805 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10806 * } );
10807 * $( 'body' ).append( panel.$element );
10808 *
10809 * @class
10810 * @extends OO.ui.Layout
10811 *
10812 * @constructor
10813 * @param {Object} [config] Configuration options
10814 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10815 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10816 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10817 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10818 */
10819 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10820 // Configuration initialization
10821 config = $.extend( {
10822 scrollable: false,
10823 padded: false,
10824 expanded: true,
10825 framed: false
10826 }, config );
10827
10828 // Parent constructor
10829 OO.ui.PanelLayout.parent.call( this, config );
10830
10831 // Initialization
10832 this.$element.addClass( 'oo-ui-panelLayout' );
10833 if ( config.scrollable ) {
10834 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10835 }
10836 if ( config.padded ) {
10837 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10838 }
10839 if ( config.expanded ) {
10840 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10841 }
10842 if ( config.framed ) {
10843 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10844 }
10845 };
10846
10847 /* Setup */
10848
10849 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10850
10851 /* Methods */
10852
10853 /**
10854 * Focus the panel layout
10855 *
10856 * The default implementation just focuses the first focusable element in the panel
10857 */
10858 OO.ui.PanelLayout.prototype.focus = function () {
10859 OO.ui.findFocusable( this.$element ).focus();
10860 };
10861
10862 /**
10863 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10864 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10865 * rather extended to include the required content and functionality.
10866 *
10867 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10868 * item is customized (with a label) using the #setupTabItem method. See
10869 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10870 *
10871 * @class
10872 * @extends OO.ui.PanelLayout
10873 *
10874 * @constructor
10875 * @param {string} name Unique symbolic name of card
10876 * @param {Object} [config] Configuration options
10877 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10878 */
10879 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10880 // Allow passing positional parameters inside the config object
10881 if ( OO.isPlainObject( name ) && config === undefined ) {
10882 config = name;
10883 name = config.name;
10884 }
10885
10886 // Configuration initialization
10887 config = $.extend( { scrollable: true }, config );
10888
10889 // Parent constructor
10890 OO.ui.CardLayout.parent.call( this, config );
10891
10892 // Properties
10893 this.name = name;
10894 this.label = config.label;
10895 this.tabItem = null;
10896 this.active = false;
10897
10898 // Initialization
10899 this.$element.addClass( 'oo-ui-cardLayout' );
10900 };
10901
10902 /* Setup */
10903
10904 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10905
10906 /* Events */
10907
10908 /**
10909 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10910 * shown in a index layout that is configured to display only one card at a time.
10911 *
10912 * @event active
10913 * @param {boolean} active Card is active
10914 */
10915
10916 /* Methods */
10917
10918 /**
10919 * Get the symbolic name of the card.
10920 *
10921 * @return {string} Symbolic name of card
10922 */
10923 OO.ui.CardLayout.prototype.getName = function () {
10924 return this.name;
10925 };
10926
10927 /**
10928 * Check if card is active.
10929 *
10930 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10931 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10932 *
10933 * @return {boolean} Card is active
10934 */
10935 OO.ui.CardLayout.prototype.isActive = function () {
10936 return this.active;
10937 };
10938
10939 /**
10940 * Get tab item.
10941 *
10942 * The tab item allows users to access the card from the index's tab
10943 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10944 *
10945 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10946 */
10947 OO.ui.CardLayout.prototype.getTabItem = function () {
10948 return this.tabItem;
10949 };
10950
10951 /**
10952 * Set or unset the tab item.
10953 *
10954 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10955 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10956 * level), use #setupTabItem instead of this method.
10957 *
10958 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10959 * @chainable
10960 */
10961 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10962 this.tabItem = tabItem || null;
10963 if ( tabItem ) {
10964 this.setupTabItem();
10965 }
10966 return this;
10967 };
10968
10969 /**
10970 * Set up the tab item.
10971 *
10972 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10973 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10974 * the #setTabItem method instead.
10975 *
10976 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10977 * @chainable
10978 */
10979 OO.ui.CardLayout.prototype.setupTabItem = function () {
10980 if ( this.label ) {
10981 this.tabItem.setLabel( this.label );
10982 }
10983 return this;
10984 };
10985
10986 /**
10987 * Set the card to its 'active' state.
10988 *
10989 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10990 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10991 * context, setting the active state on a card does nothing.
10992 *
10993 * @param {boolean} value Card is active
10994 * @fires active
10995 */
10996 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10997 active = !!active;
10998
10999 if ( active !== this.active ) {
11000 this.active = active;
11001 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
11002 this.emit( 'active', this.active );
11003 }
11004 };
11005
11006 /**
11007 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
11008 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
11009 * rather extended to include the required content and functionality.
11010 *
11011 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
11012 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
11013 * {@link OO.ui.BookletLayout BookletLayout} for an example.
11014 *
11015 * @class
11016 * @extends OO.ui.PanelLayout
11017 *
11018 * @constructor
11019 * @param {string} name Unique symbolic name of page
11020 * @param {Object} [config] Configuration options
11021 */
11022 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
11023 // Allow passing positional parameters inside the config object
11024 if ( OO.isPlainObject( name ) && config === undefined ) {
11025 config = name;
11026 name = config.name;
11027 }
11028
11029 // Configuration initialization
11030 config = $.extend( { scrollable: true }, config );
11031
11032 // Parent constructor
11033 OO.ui.PageLayout.parent.call( this, config );
11034
11035 // Properties
11036 this.name = name;
11037 this.outlineItem = null;
11038 this.active = false;
11039
11040 // Initialization
11041 this.$element.addClass( 'oo-ui-pageLayout' );
11042 };
11043
11044 /* Setup */
11045
11046 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
11047
11048 /* Events */
11049
11050 /**
11051 * An 'active' event is emitted when the page becomes active. Pages become active when they are
11052 * shown in a booklet layout that is configured to display only one page at a time.
11053 *
11054 * @event active
11055 * @param {boolean} active Page is active
11056 */
11057
11058 /* Methods */
11059
11060 /**
11061 * Get the symbolic name of the page.
11062 *
11063 * @return {string} Symbolic name of page
11064 */
11065 OO.ui.PageLayout.prototype.getName = function () {
11066 return this.name;
11067 };
11068
11069 /**
11070 * Check if page is active.
11071 *
11072 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
11073 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
11074 *
11075 * @return {boolean} Page is active
11076 */
11077 OO.ui.PageLayout.prototype.isActive = function () {
11078 return this.active;
11079 };
11080
11081 /**
11082 * Get outline item.
11083 *
11084 * The outline item allows users to access the page from the booklet's outline
11085 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
11086 *
11087 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
11088 */
11089 OO.ui.PageLayout.prototype.getOutlineItem = function () {
11090 return this.outlineItem;
11091 };
11092
11093 /**
11094 * Set or unset the outline item.
11095 *
11096 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
11097 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
11098 * level), use #setupOutlineItem instead of this method.
11099 *
11100 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
11101 * @chainable
11102 */
11103 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
11104 this.outlineItem = outlineItem || null;
11105 if ( outlineItem ) {
11106 this.setupOutlineItem();
11107 }
11108 return this;
11109 };
11110
11111 /**
11112 * Set up the outline item.
11113 *
11114 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
11115 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
11116 * the #setOutlineItem method instead.
11117 *
11118 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
11119 * @chainable
11120 */
11121 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
11122 return this;
11123 };
11124
11125 /**
11126 * Set the page to its 'active' state.
11127 *
11128 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
11129 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
11130 * context, setting the active state on a page does nothing.
11131 *
11132 * @param {boolean} value Page is active
11133 * @fires active
11134 */
11135 OO.ui.PageLayout.prototype.setActive = function ( active ) {
11136 active = !!active;
11137
11138 if ( active !== this.active ) {
11139 this.active = active;
11140 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
11141 this.emit( 'active', this.active );
11142 }
11143 };
11144
11145 /**
11146 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
11147 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
11148 * by setting the #continuous option to 'true'.
11149 *
11150 * @example
11151 * // A stack layout with two panels, configured to be displayed continously
11152 * var myStack = new OO.ui.StackLayout( {
11153 * items: [
11154 * new OO.ui.PanelLayout( {
11155 * $content: $( '<p>Panel One</p>' ),
11156 * padded: true,
11157 * framed: true
11158 * } ),
11159 * new OO.ui.PanelLayout( {
11160 * $content: $( '<p>Panel Two</p>' ),
11161 * padded: true,
11162 * framed: true
11163 * } )
11164 * ],
11165 * continuous: true
11166 * } );
11167 * $( 'body' ).append( myStack.$element );
11168 *
11169 * @class
11170 * @extends OO.ui.PanelLayout
11171 * @mixins OO.ui.mixin.GroupElement
11172 *
11173 * @constructor
11174 * @param {Object} [config] Configuration options
11175 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
11176 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
11177 */
11178 OO.ui.StackLayout = function OoUiStackLayout( config ) {
11179 // Configuration initialization
11180 config = $.extend( { scrollable: true }, config );
11181
11182 // Parent constructor
11183 OO.ui.StackLayout.parent.call( this, config );
11184
11185 // Mixin constructors
11186 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11187
11188 // Properties
11189 this.currentItem = null;
11190 this.continuous = !!config.continuous;
11191
11192 // Initialization
11193 this.$element.addClass( 'oo-ui-stackLayout' );
11194 if ( this.continuous ) {
11195 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
11196 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
11197 }
11198 if ( Array.isArray( config.items ) ) {
11199 this.addItems( config.items );
11200 }
11201 };
11202
11203 /* Setup */
11204
11205 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
11206 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
11207
11208 /* Events */
11209
11210 /**
11211 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11212 * {@link #clearItems cleared} or {@link #setItem displayed}.
11213 *
11214 * @event set
11215 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11216 */
11217
11218 /**
11219 * When used in continuous mode, this event is emitted when the user scrolls down
11220 * far enough such that currentItem is no longer visible.
11221 *
11222 * @event visibleItemChange
11223 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
11224 */
11225
11226 /* Methods */
11227
11228 /**
11229 * Handle scroll events from the layout element
11230 *
11231 * @param {jQuery.Event} e
11232 * @fires visibleItemChange
11233 */
11234 OO.ui.StackLayout.prototype.onScroll = function () {
11235 var currentRect,
11236 len = this.items.length,
11237 currentIndex = this.items.indexOf( this.currentItem ),
11238 newIndex = currentIndex,
11239 containerRect = this.$element[ 0 ].getBoundingClientRect();
11240
11241 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
11242 // Can't get bounding rect, possibly not attached.
11243 return;
11244 }
11245
11246 function getRect( item ) {
11247 return item.$element[ 0 ].getBoundingClientRect();
11248 }
11249
11250 function isVisible( item ) {
11251 var rect = getRect( item );
11252 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
11253 }
11254
11255 currentRect = getRect( this.currentItem );
11256
11257 if ( currentRect.bottom < containerRect.top ) {
11258 // Scrolled down past current item
11259 while ( ++newIndex < len ) {
11260 if ( isVisible( this.items[ newIndex ] ) ) {
11261 break;
11262 }
11263 }
11264 } else if ( currentRect.top > containerRect.bottom ) {
11265 // Scrolled up past current item
11266 while ( --newIndex >= 0 ) {
11267 if ( isVisible( this.items[ newIndex ] ) ) {
11268 break;
11269 }
11270 }
11271 }
11272
11273 if ( newIndex !== currentIndex ) {
11274 this.emit( 'visibleItemChange', this.items[ newIndex ] );
11275 }
11276 };
11277
11278 /**
11279 * Get the current panel.
11280 *
11281 * @return {OO.ui.Layout|null}
11282 */
11283 OO.ui.StackLayout.prototype.getCurrentItem = function () {
11284 return this.currentItem;
11285 };
11286
11287 /**
11288 * Unset the current item.
11289 *
11290 * @private
11291 * @param {OO.ui.StackLayout} layout
11292 * @fires set
11293 */
11294 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
11295 var prevItem = this.currentItem;
11296 if ( prevItem === null ) {
11297 return;
11298 }
11299
11300 this.currentItem = null;
11301 this.emit( 'set', null );
11302 };
11303
11304 /**
11305 * Add panel layouts to the stack layout.
11306 *
11307 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11308 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11309 * by the index.
11310 *
11311 * @param {OO.ui.Layout[]} items Panels to add
11312 * @param {number} [index] Index of the insertion point
11313 * @chainable
11314 */
11315 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
11316 // Update the visibility
11317 this.updateHiddenState( items, this.currentItem );
11318
11319 // Mixin method
11320 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
11321
11322 if ( !this.currentItem && items.length ) {
11323 this.setItem( items[ 0 ] );
11324 }
11325
11326 return this;
11327 };
11328
11329 /**
11330 * Remove the specified panels from the stack layout.
11331 *
11332 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11333 * you may wish to use the #clearItems method instead.
11334 *
11335 * @param {OO.ui.Layout[]} items Panels to remove
11336 * @chainable
11337 * @fires set
11338 */
11339 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
11340 // Mixin method
11341 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
11342
11343 if ( items.indexOf( this.currentItem ) !== -1 ) {
11344 if ( this.items.length ) {
11345 this.setItem( this.items[ 0 ] );
11346 } else {
11347 this.unsetCurrentItem();
11348 }
11349 }
11350
11351 return this;
11352 };
11353
11354 /**
11355 * Clear all panels from the stack layout.
11356 *
11357 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11358 * a subset of panels, use the #removeItems method.
11359 *
11360 * @chainable
11361 * @fires set
11362 */
11363 OO.ui.StackLayout.prototype.clearItems = function () {
11364 this.unsetCurrentItem();
11365 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
11366
11367 return this;
11368 };
11369
11370 /**
11371 * Show the specified panel.
11372 *
11373 * If another panel is currently displayed, it will be hidden.
11374 *
11375 * @param {OO.ui.Layout} item Panel to show
11376 * @chainable
11377 * @fires set
11378 */
11379 OO.ui.StackLayout.prototype.setItem = function ( item ) {
11380 if ( item !== this.currentItem ) {
11381 this.updateHiddenState( this.items, item );
11382
11383 if ( this.items.indexOf( item ) !== -1 ) {
11384 this.currentItem = item;
11385 this.emit( 'set', item );
11386 } else {
11387 this.unsetCurrentItem();
11388 }
11389 }
11390
11391 return this;
11392 };
11393
11394 /**
11395 * Update the visibility of all items in case of non-continuous view.
11396 *
11397 * Ensure all items are hidden except for the selected one.
11398 * This method does nothing when the stack is continuous.
11399 *
11400 * @private
11401 * @param {OO.ui.Layout[]} items Item list iterate over
11402 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11403 */
11404 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
11405 var i, len;
11406
11407 if ( !this.continuous ) {
11408 for ( i = 0, len = items.length; i < len; i++ ) {
11409 if ( !selectedItem || selectedItem !== items[ i ] ) {
11410 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
11411 }
11412 }
11413 if ( selectedItem ) {
11414 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
11415 }
11416 }
11417 };
11418
11419 /**
11420 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11421 * items), with small margins between them. Convenient when you need to put a number of block-level
11422 * widgets on a single line next to each other.
11423 *
11424 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11425 *
11426 * @example
11427 * // HorizontalLayout with a text input and a label
11428 * var layout = new OO.ui.HorizontalLayout( {
11429 * items: [
11430 * new OO.ui.LabelWidget( { label: 'Label' } ),
11431 * new OO.ui.TextInputWidget( { value: 'Text' } )
11432 * ]
11433 * } );
11434 * $( 'body' ).append( layout.$element );
11435 *
11436 * @class
11437 * @extends OO.ui.Layout
11438 * @mixins OO.ui.mixin.GroupElement
11439 *
11440 * @constructor
11441 * @param {Object} [config] Configuration options
11442 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11443 */
11444 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
11445 // Configuration initialization
11446 config = config || {};
11447
11448 // Parent constructor
11449 OO.ui.HorizontalLayout.parent.call( this, config );
11450
11451 // Mixin constructors
11452 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11453
11454 // Initialization
11455 this.$element.addClass( 'oo-ui-horizontalLayout' );
11456 if ( Array.isArray( config.items ) ) {
11457 this.addItems( config.items );
11458 }
11459 };
11460
11461 /* Setup */
11462
11463 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11464 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11465
11466 /**
11467 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11468 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11469 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11470 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11471 * the tool.
11472 *
11473 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11474 * set up.
11475 *
11476 * @example
11477 * // Example of a BarToolGroup with two tools
11478 * var toolFactory = new OO.ui.ToolFactory();
11479 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11480 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11481 *
11482 * // We will be placing status text in this element when tools are used
11483 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11484 *
11485 * // Define the tools that we're going to place in our toolbar
11486 *
11487 * // Create a class inheriting from OO.ui.Tool
11488 * function ImageTool() {
11489 * ImageTool.parent.apply( this, arguments );
11490 * }
11491 * OO.inheritClass( ImageTool, OO.ui.Tool );
11492 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11493 * // of 'icon' and 'title' (displayed icon and text).
11494 * ImageTool.static.name = 'image';
11495 * ImageTool.static.icon = 'image';
11496 * ImageTool.static.title = 'Insert image';
11497 * // Defines the action that will happen when this tool is selected (clicked).
11498 * ImageTool.prototype.onSelect = function () {
11499 * $area.text( 'Image tool clicked!' );
11500 * // Never display this tool as "active" (selected).
11501 * this.setActive( false );
11502 * };
11503 * // Make this tool available in our toolFactory and thus our toolbar
11504 * toolFactory.register( ImageTool );
11505 *
11506 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11507 * // little popup window (a PopupWidget).
11508 * function HelpTool( toolGroup, config ) {
11509 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11510 * padded: true,
11511 * label: 'Help',
11512 * head: true
11513 * } }, config ) );
11514 * this.popup.$body.append( '<p>I am helpful!</p>' );
11515 * }
11516 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11517 * HelpTool.static.name = 'help';
11518 * HelpTool.static.icon = 'help';
11519 * HelpTool.static.title = 'Help';
11520 * toolFactory.register( HelpTool );
11521 *
11522 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11523 * // used once (but not all defined tools must be used).
11524 * toolbar.setup( [
11525 * {
11526 * // 'bar' tool groups display tools by icon only
11527 * type: 'bar',
11528 * include: [ 'image', 'help' ]
11529 * }
11530 * ] );
11531 *
11532 * // Create some UI around the toolbar and place it in the document
11533 * var frame = new OO.ui.PanelLayout( {
11534 * expanded: false,
11535 * framed: true
11536 * } );
11537 * var contentFrame = new OO.ui.PanelLayout( {
11538 * expanded: false,
11539 * padded: true
11540 * } );
11541 * frame.$element.append(
11542 * toolbar.$element,
11543 * contentFrame.$element.append( $area )
11544 * );
11545 * $( 'body' ).append( frame.$element );
11546 *
11547 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11548 * // document.
11549 * toolbar.initialize();
11550 *
11551 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11552 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11553 *
11554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11555 *
11556 * @class
11557 * @extends OO.ui.ToolGroup
11558 *
11559 * @constructor
11560 * @param {OO.ui.Toolbar} toolbar
11561 * @param {Object} [config] Configuration options
11562 */
11563 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11564 // Allow passing positional parameters inside the config object
11565 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11566 config = toolbar;
11567 toolbar = config.toolbar;
11568 }
11569
11570 // Parent constructor
11571 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11572
11573 // Initialization
11574 this.$element.addClass( 'oo-ui-barToolGroup' );
11575 };
11576
11577 /* Setup */
11578
11579 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11580
11581 /* Static Properties */
11582
11583 OO.ui.BarToolGroup.static.titleTooltips = true;
11584
11585 OO.ui.BarToolGroup.static.accelTooltips = true;
11586
11587 OO.ui.BarToolGroup.static.name = 'bar';
11588
11589 /**
11590 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11591 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11592 * optional icon and label. This class can be used for other base classes that also use this functionality.
11593 *
11594 * @abstract
11595 * @class
11596 * @extends OO.ui.ToolGroup
11597 * @mixins OO.ui.mixin.IconElement
11598 * @mixins OO.ui.mixin.IndicatorElement
11599 * @mixins OO.ui.mixin.LabelElement
11600 * @mixins OO.ui.mixin.TitledElement
11601 * @mixins OO.ui.mixin.ClippableElement
11602 * @mixins OO.ui.mixin.TabIndexedElement
11603 *
11604 * @constructor
11605 * @param {OO.ui.Toolbar} toolbar
11606 * @param {Object} [config] Configuration options
11607 * @cfg {string} [header] Text to display at the top of the popup
11608 */
11609 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11610 // Allow passing positional parameters inside the config object
11611 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11612 config = toolbar;
11613 toolbar = config.toolbar;
11614 }
11615
11616 // Configuration initialization
11617 config = config || {};
11618
11619 // Parent constructor
11620 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11621
11622 // Properties
11623 this.active = false;
11624 this.dragging = false;
11625 this.onBlurHandler = this.onBlur.bind( this );
11626 this.$handle = $( '<span>' );
11627
11628 // Mixin constructors
11629 OO.ui.mixin.IconElement.call( this, config );
11630 OO.ui.mixin.IndicatorElement.call( this, config );
11631 OO.ui.mixin.LabelElement.call( this, config );
11632 OO.ui.mixin.TitledElement.call( this, config );
11633 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11634 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11635
11636 // Events
11637 this.$handle.on( {
11638 keydown: this.onHandleMouseKeyDown.bind( this ),
11639 keyup: this.onHandleMouseKeyUp.bind( this ),
11640 mousedown: this.onHandleMouseKeyDown.bind( this ),
11641 mouseup: this.onHandleMouseKeyUp.bind( this )
11642 } );
11643
11644 // Initialization
11645 this.$handle
11646 .addClass( 'oo-ui-popupToolGroup-handle' )
11647 .append( this.$icon, this.$label, this.$indicator );
11648 // If the pop-up should have a header, add it to the top of the toolGroup.
11649 // Note: If this feature is useful for other widgets, we could abstract it into an
11650 // OO.ui.HeaderedElement mixin constructor.
11651 if ( config.header !== undefined ) {
11652 this.$group
11653 .prepend( $( '<span>' )
11654 .addClass( 'oo-ui-popupToolGroup-header' )
11655 .text( config.header )
11656 );
11657 }
11658 this.$element
11659 .addClass( 'oo-ui-popupToolGroup' )
11660 .prepend( this.$handle );
11661 };
11662
11663 /* Setup */
11664
11665 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11666 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11667 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11668 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11669 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11670 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11671 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11672
11673 /* Methods */
11674
11675 /**
11676 * @inheritdoc
11677 */
11678 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11679 // Parent method
11680 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11681
11682 if ( this.isDisabled() && this.isElementAttached() ) {
11683 this.setActive( false );
11684 }
11685 };
11686
11687 /**
11688 * Handle focus being lost.
11689 *
11690 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11691 *
11692 * @protected
11693 * @param {jQuery.Event} e Mouse up or key up event
11694 */
11695 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11696 // Only deactivate when clicking outside the dropdown element
11697 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11698 this.setActive( false );
11699 }
11700 };
11701
11702 /**
11703 * @inheritdoc
11704 */
11705 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11706 // Only close toolgroup when a tool was actually selected
11707 if (
11708 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11709 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11710 ) {
11711 this.setActive( false );
11712 }
11713 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11714 };
11715
11716 /**
11717 * Handle mouse up and key up events.
11718 *
11719 * @protected
11720 * @param {jQuery.Event} e Mouse up or key up event
11721 */
11722 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11723 if (
11724 !this.isDisabled() &&
11725 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11726 ) {
11727 return false;
11728 }
11729 };
11730
11731 /**
11732 * Handle mouse down and key down events.
11733 *
11734 * @protected
11735 * @param {jQuery.Event} e Mouse down or key down event
11736 */
11737 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11738 if (
11739 !this.isDisabled() &&
11740 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11741 ) {
11742 this.setActive( !this.active );
11743 return false;
11744 }
11745 };
11746
11747 /**
11748 * Switch into 'active' mode.
11749 *
11750 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11751 * deactivation.
11752 */
11753 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11754 var containerWidth, containerLeft;
11755 value = !!value;
11756 if ( this.active !== value ) {
11757 this.active = value;
11758 if ( value ) {
11759 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11760 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11761
11762 this.$clippable.css( 'left', '' );
11763 // Try anchoring the popup to the left first
11764 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11765 this.toggleClipping( true );
11766 if ( this.isClippedHorizontally() ) {
11767 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11768 this.toggleClipping( false );
11769 this.$element
11770 .removeClass( 'oo-ui-popupToolGroup-left' )
11771 .addClass( 'oo-ui-popupToolGroup-right' );
11772 this.toggleClipping( true );
11773 }
11774 if ( this.isClippedHorizontally() ) {
11775 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11776 containerWidth = this.$clippableScrollableContainer.width();
11777 containerLeft = this.$clippableScrollableContainer.offset().left;
11778
11779 this.toggleClipping( false );
11780 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11781
11782 this.$clippable.css( {
11783 left: -( this.$element.offset().left - containerLeft ),
11784 width: containerWidth
11785 } );
11786 }
11787 } else {
11788 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11789 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11790 this.$element.removeClass(
11791 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11792 );
11793 this.toggleClipping( false );
11794 }
11795 }
11796 };
11797
11798 /**
11799 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11800 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11801 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11802 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11803 * with a label, icon, indicator, header, and title.
11804 *
11805 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11806 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11807 * users to collapse the list again.
11808 *
11809 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11810 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11811 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11812 *
11813 * @example
11814 * // Example of a ListToolGroup
11815 * var toolFactory = new OO.ui.ToolFactory();
11816 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11817 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11818 *
11819 * // Configure and register two tools
11820 * function SettingsTool() {
11821 * SettingsTool.parent.apply( this, arguments );
11822 * }
11823 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11824 * SettingsTool.static.name = 'settings';
11825 * SettingsTool.static.icon = 'settings';
11826 * SettingsTool.static.title = 'Change settings';
11827 * SettingsTool.prototype.onSelect = function () {
11828 * this.setActive( false );
11829 * };
11830 * toolFactory.register( SettingsTool );
11831 * // Register two more tools, nothing interesting here
11832 * function StuffTool() {
11833 * StuffTool.parent.apply( this, arguments );
11834 * }
11835 * OO.inheritClass( StuffTool, OO.ui.Tool );
11836 * StuffTool.static.name = 'stuff';
11837 * StuffTool.static.icon = 'ellipsis';
11838 * StuffTool.static.title = 'Change the world';
11839 * StuffTool.prototype.onSelect = function () {
11840 * this.setActive( false );
11841 * };
11842 * toolFactory.register( StuffTool );
11843 * toolbar.setup( [
11844 * {
11845 * // Configurations for list toolgroup.
11846 * type: 'list',
11847 * label: 'ListToolGroup',
11848 * indicator: 'down',
11849 * icon: 'image',
11850 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11851 * header: 'This is the header',
11852 * include: [ 'settings', 'stuff' ],
11853 * allowCollapse: ['stuff']
11854 * }
11855 * ] );
11856 *
11857 * // Create some UI around the toolbar and place it in the document
11858 * var frame = new OO.ui.PanelLayout( {
11859 * expanded: false,
11860 * framed: true
11861 * } );
11862 * frame.$element.append(
11863 * toolbar.$element
11864 * );
11865 * $( 'body' ).append( frame.$element );
11866 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11867 * toolbar.initialize();
11868 *
11869 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11870 *
11871 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11872 *
11873 * @class
11874 * @extends OO.ui.PopupToolGroup
11875 *
11876 * @constructor
11877 * @param {OO.ui.Toolbar} toolbar
11878 * @param {Object} [config] Configuration options
11879 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11880 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11881 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11882 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11883 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11884 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11885 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11886 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11887 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11888 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11889 */
11890 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11891 // Allow passing positional parameters inside the config object
11892 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11893 config = toolbar;
11894 toolbar = config.toolbar;
11895 }
11896
11897 // Configuration initialization
11898 config = config || {};
11899
11900 // Properties (must be set before parent constructor, which calls #populate)
11901 this.allowCollapse = config.allowCollapse;
11902 this.forceExpand = config.forceExpand;
11903 this.expanded = config.expanded !== undefined ? config.expanded : false;
11904 this.collapsibleTools = [];
11905
11906 // Parent constructor
11907 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11908
11909 // Initialization
11910 this.$element.addClass( 'oo-ui-listToolGroup' );
11911 };
11912
11913 /* Setup */
11914
11915 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11916
11917 /* Static Properties */
11918
11919 OO.ui.ListToolGroup.static.name = 'list';
11920
11921 /* Methods */
11922
11923 /**
11924 * @inheritdoc
11925 */
11926 OO.ui.ListToolGroup.prototype.populate = function () {
11927 var i, len, allowCollapse = [];
11928
11929 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11930
11931 // Update the list of collapsible tools
11932 if ( this.allowCollapse !== undefined ) {
11933 allowCollapse = this.allowCollapse;
11934 } else if ( this.forceExpand !== undefined ) {
11935 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11936 }
11937
11938 this.collapsibleTools = [];
11939 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11940 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11941 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11942 }
11943 }
11944
11945 // Keep at the end, even when tools are added
11946 this.$group.append( this.getExpandCollapseTool().$element );
11947
11948 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11949 this.updateCollapsibleState();
11950 };
11951
11952 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11953 var ExpandCollapseTool;
11954 if ( this.expandCollapseTool === undefined ) {
11955 ExpandCollapseTool = function () {
11956 ExpandCollapseTool.parent.apply( this, arguments );
11957 };
11958
11959 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11960
11961 ExpandCollapseTool.prototype.onSelect = function () {
11962 this.toolGroup.expanded = !this.toolGroup.expanded;
11963 this.toolGroup.updateCollapsibleState();
11964 this.setActive( false );
11965 };
11966 ExpandCollapseTool.prototype.onUpdateState = function () {
11967 // Do nothing. Tool interface requires an implementation of this function.
11968 };
11969
11970 ExpandCollapseTool.static.name = 'more-fewer';
11971
11972 this.expandCollapseTool = new ExpandCollapseTool( this );
11973 }
11974 return this.expandCollapseTool;
11975 };
11976
11977 /**
11978 * @inheritdoc
11979 */
11980 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11981 // Do not close the popup when the user wants to show more/fewer tools
11982 if (
11983 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11984 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11985 ) {
11986 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11987 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11988 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11989 } else {
11990 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11991 }
11992 };
11993
11994 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11995 var i, len;
11996
11997 this.getExpandCollapseTool()
11998 .setIcon( this.expanded ? 'collapse' : 'expand' )
11999 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
12000
12001 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
12002 this.collapsibleTools[ i ].toggle( this.expanded );
12003 }
12004 };
12005
12006 /**
12007 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
12008 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
12009 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
12010 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
12011 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
12012 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
12013 *
12014 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
12015 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
12016 * a MenuToolGroup is used.
12017 *
12018 * @example
12019 * // Example of a MenuToolGroup
12020 * var toolFactory = new OO.ui.ToolFactory();
12021 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
12022 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
12023 *
12024 * // We will be placing status text in this element when tools are used
12025 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
12026 *
12027 * // Define the tools that we're going to place in our toolbar
12028 *
12029 * function SettingsTool() {
12030 * SettingsTool.parent.apply( this, arguments );
12031 * this.reallyActive = false;
12032 * }
12033 * OO.inheritClass( SettingsTool, OO.ui.Tool );
12034 * SettingsTool.static.name = 'settings';
12035 * SettingsTool.static.icon = 'settings';
12036 * SettingsTool.static.title = 'Change settings';
12037 * SettingsTool.prototype.onSelect = function () {
12038 * $area.text( 'Settings tool clicked!' );
12039 * // Toggle the active state on each click
12040 * this.reallyActive = !this.reallyActive;
12041 * this.setActive( this.reallyActive );
12042 * // To update the menu label
12043 * this.toolbar.emit( 'updateState' );
12044 * };
12045 * SettingsTool.prototype.onUpdateState = function () {
12046 * };
12047 * toolFactory.register( SettingsTool );
12048 *
12049 * function StuffTool() {
12050 * StuffTool.parent.apply( this, arguments );
12051 * this.reallyActive = false;
12052 * }
12053 * OO.inheritClass( StuffTool, OO.ui.Tool );
12054 * StuffTool.static.name = 'stuff';
12055 * StuffTool.static.icon = 'ellipsis';
12056 * StuffTool.static.title = 'More stuff';
12057 * StuffTool.prototype.onSelect = function () {
12058 * $area.text( 'More stuff tool clicked!' );
12059 * // Toggle the active state on each click
12060 * this.reallyActive = !this.reallyActive;
12061 * this.setActive( this.reallyActive );
12062 * // To update the menu label
12063 * this.toolbar.emit( 'updateState' );
12064 * };
12065 * StuffTool.prototype.onUpdateState = function () {
12066 * };
12067 * toolFactory.register( StuffTool );
12068 *
12069 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
12070 * // used once (but not all defined tools must be used).
12071 * toolbar.setup( [
12072 * {
12073 * type: 'menu',
12074 * header: 'This is the (optional) header',
12075 * title: 'This is the (optional) title',
12076 * indicator: 'down',
12077 * include: [ 'settings', 'stuff' ]
12078 * }
12079 * ] );
12080 *
12081 * // Create some UI around the toolbar and place it in the document
12082 * var frame = new OO.ui.PanelLayout( {
12083 * expanded: false,
12084 * framed: true
12085 * } );
12086 * var contentFrame = new OO.ui.PanelLayout( {
12087 * expanded: false,
12088 * padded: true
12089 * } );
12090 * frame.$element.append(
12091 * toolbar.$element,
12092 * contentFrame.$element.append( $area )
12093 * );
12094 * $( 'body' ).append( frame.$element );
12095 *
12096 * // Here is where the toolbar is actually built. This must be done after inserting it into the
12097 * // document.
12098 * toolbar.initialize();
12099 * toolbar.emit( 'updateState' );
12100 *
12101 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
12102 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
12103 *
12104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12105 *
12106 * @class
12107 * @extends OO.ui.PopupToolGroup
12108 *
12109 * @constructor
12110 * @param {OO.ui.Toolbar} toolbar
12111 * @param {Object} [config] Configuration options
12112 */
12113 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
12114 // Allow passing positional parameters inside the config object
12115 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
12116 config = toolbar;
12117 toolbar = config.toolbar;
12118 }
12119
12120 // Configuration initialization
12121 config = config || {};
12122
12123 // Parent constructor
12124 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
12125
12126 // Events
12127 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
12128
12129 // Initialization
12130 this.$element.addClass( 'oo-ui-menuToolGroup' );
12131 };
12132
12133 /* Setup */
12134
12135 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
12136
12137 /* Static Properties */
12138
12139 OO.ui.MenuToolGroup.static.name = 'menu';
12140
12141 /* Methods */
12142
12143 /**
12144 * Handle the toolbar state being updated.
12145 *
12146 * When the state changes, the title of each active item in the menu will be joined together and
12147 * used as a label for the group. The label will be empty if none of the items are active.
12148 *
12149 * @private
12150 */
12151 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
12152 var name,
12153 labelTexts = [];
12154
12155 for ( name in this.tools ) {
12156 if ( this.tools[ name ].isActive() ) {
12157 labelTexts.push( this.tools[ name ].getTitle() );
12158 }
12159 }
12160
12161 this.setLabel( labelTexts.join( ', ' ) || ' ' );
12162 };
12163
12164 /**
12165 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
12166 * 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
12167 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
12168 *
12169 * // Example of a popup tool. When selected, a popup tool displays
12170 * // a popup window.
12171 * function HelpTool( toolGroup, config ) {
12172 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
12173 * padded: true,
12174 * label: 'Help',
12175 * head: true
12176 * } }, config ) );
12177 * this.popup.$body.append( '<p>I am helpful!</p>' );
12178 * };
12179 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
12180 * HelpTool.static.name = 'help';
12181 * HelpTool.static.icon = 'help';
12182 * HelpTool.static.title = 'Help';
12183 * toolFactory.register( HelpTool );
12184 *
12185 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
12186 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
12187 *
12188 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
12189 *
12190 * @abstract
12191 * @class
12192 * @extends OO.ui.Tool
12193 * @mixins OO.ui.mixin.PopupElement
12194 *
12195 * @constructor
12196 * @param {OO.ui.ToolGroup} toolGroup
12197 * @param {Object} [config] Configuration options
12198 */
12199 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
12200 // Allow passing positional parameters inside the config object
12201 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12202 config = toolGroup;
12203 toolGroup = config.toolGroup;
12204 }
12205
12206 // Parent constructor
12207 OO.ui.PopupTool.parent.call( this, toolGroup, config );
12208
12209 // Mixin constructors
12210 OO.ui.mixin.PopupElement.call( this, config );
12211
12212 // Initialization
12213 this.$element
12214 .addClass( 'oo-ui-popupTool' )
12215 .append( this.popup.$element );
12216 };
12217
12218 /* Setup */
12219
12220 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
12221 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
12222
12223 /* Methods */
12224
12225 /**
12226 * Handle the tool being selected.
12227 *
12228 * @inheritdoc
12229 */
12230 OO.ui.PopupTool.prototype.onSelect = function () {
12231 if ( !this.isDisabled() ) {
12232 this.popup.toggle();
12233 }
12234 this.setActive( false );
12235 return false;
12236 };
12237
12238 /**
12239 * Handle the toolbar state being updated.
12240 *
12241 * @inheritdoc
12242 */
12243 OO.ui.PopupTool.prototype.onUpdateState = function () {
12244 this.setActive( false );
12245 };
12246
12247 /**
12248 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
12249 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
12250 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
12251 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
12252 * when the ToolGroupTool is selected.
12253 *
12254 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12255 *
12256 * function SettingsTool() {
12257 * SettingsTool.parent.apply( this, arguments );
12258 * };
12259 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12260 * SettingsTool.static.name = 'settings';
12261 * SettingsTool.static.title = 'Change settings';
12262 * SettingsTool.static.groupConfig = {
12263 * icon: 'settings',
12264 * label: 'ToolGroupTool',
12265 * include: [ 'setting1', 'setting2' ]
12266 * };
12267 * toolFactory.register( SettingsTool );
12268 *
12269 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12270 *
12271 * Please note that this implementation is subject to change per [T74159] [2].
12272 *
12273 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12274 * [2]: https://phabricator.wikimedia.org/T74159
12275 *
12276 * @abstract
12277 * @class
12278 * @extends OO.ui.Tool
12279 *
12280 * @constructor
12281 * @param {OO.ui.ToolGroup} toolGroup
12282 * @param {Object} [config] Configuration options
12283 */
12284 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
12285 // Allow passing positional parameters inside the config object
12286 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
12287 config = toolGroup;
12288 toolGroup = config.toolGroup;
12289 }
12290
12291 // Parent constructor
12292 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
12293
12294 // Properties
12295 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
12296
12297 // Events
12298 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
12299
12300 // Initialization
12301 this.$link.remove();
12302 this.$element
12303 .addClass( 'oo-ui-toolGroupTool' )
12304 .append( this.innerToolGroup.$element );
12305 };
12306
12307 /* Setup */
12308
12309 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
12310
12311 /* Static Properties */
12312
12313 /**
12314 * Toolgroup configuration.
12315 *
12316 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12317 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12318 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12319 *
12320 * @property {Object.<string,Array>}
12321 */
12322 OO.ui.ToolGroupTool.static.groupConfig = {};
12323
12324 /* Methods */
12325
12326 /**
12327 * Handle the tool being selected.
12328 *
12329 * @inheritdoc
12330 */
12331 OO.ui.ToolGroupTool.prototype.onSelect = function () {
12332 this.innerToolGroup.setActive( !this.innerToolGroup.active );
12333 return false;
12334 };
12335
12336 /**
12337 * Synchronize disabledness state of the tool with the inner toolgroup.
12338 *
12339 * @private
12340 * @param {boolean} disabled Element is disabled
12341 */
12342 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
12343 this.setDisabled( disabled );
12344 };
12345
12346 /**
12347 * Handle the toolbar state being updated.
12348 *
12349 * @inheritdoc
12350 */
12351 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
12352 this.setActive( false );
12353 };
12354
12355 /**
12356 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12357 *
12358 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12359 * more information.
12360 * @return {OO.ui.ListToolGroup}
12361 */
12362 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
12363 if ( group.include === '*' ) {
12364 // Apply defaults to catch-all groups
12365 if ( group.label === undefined ) {
12366 group.label = OO.ui.msg( 'ooui-toolbar-more' );
12367 }
12368 }
12369
12370 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
12371 };
12372
12373 /**
12374 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12375 *
12376 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12377 *
12378 * @private
12379 * @abstract
12380 * @class
12381 * @extends OO.ui.mixin.GroupElement
12382 *
12383 * @constructor
12384 * @param {Object} [config] Configuration options
12385 */
12386 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
12387 // Parent constructor
12388 OO.ui.mixin.GroupWidget.parent.call( this, config );
12389 };
12390
12391 /* Setup */
12392
12393 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
12394
12395 /* Methods */
12396
12397 /**
12398 * Set the disabled state of the widget.
12399 *
12400 * This will also update the disabled state of child widgets.
12401 *
12402 * @param {boolean} disabled Disable widget
12403 * @chainable
12404 */
12405 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
12406 var i, len;
12407
12408 // Parent method
12409 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12410 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
12411
12412 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12413 if ( this.items ) {
12414 for ( i = 0, len = this.items.length; i < len; i++ ) {
12415 this.items[ i ].updateDisabled();
12416 }
12417 }
12418
12419 return this;
12420 };
12421
12422 /**
12423 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12424 *
12425 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12426 * allows bidirectional communication.
12427 *
12428 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12429 *
12430 * @private
12431 * @abstract
12432 * @class
12433 *
12434 * @constructor
12435 */
12436 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
12437 //
12438 };
12439
12440 /* Methods */
12441
12442 /**
12443 * Check if widget is disabled.
12444 *
12445 * Checks parent if present, making disabled state inheritable.
12446 *
12447 * @return {boolean} Widget is disabled
12448 */
12449 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
12450 return this.disabled ||
12451 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
12452 };
12453
12454 /**
12455 * Set group element is in.
12456 *
12457 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12458 * @chainable
12459 */
12460 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
12461 // Parent method
12462 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12463 OO.ui.Element.prototype.setElementGroup.call( this, group );
12464
12465 // Initialize item disabled states
12466 this.updateDisabled();
12467
12468 return this;
12469 };
12470
12471 /**
12472 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12473 * Controls include moving items up and down, removing items, and adding different kinds of items.
12474 *
12475 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12476 *
12477 * @class
12478 * @extends OO.ui.Widget
12479 * @mixins OO.ui.mixin.GroupElement
12480 * @mixins OO.ui.mixin.IconElement
12481 *
12482 * @constructor
12483 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12484 * @param {Object} [config] Configuration options
12485 * @cfg {Object} [abilities] List of abilties
12486 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12487 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12488 */
12489 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12490 // Allow passing positional parameters inside the config object
12491 if ( OO.isPlainObject( outline ) && config === undefined ) {
12492 config = outline;
12493 outline = config.outline;
12494 }
12495
12496 // Configuration initialization
12497 config = $.extend( { icon: 'add' }, config );
12498
12499 // Parent constructor
12500 OO.ui.OutlineControlsWidget.parent.call( this, config );
12501
12502 // Mixin constructors
12503 OO.ui.mixin.GroupElement.call( this, config );
12504 OO.ui.mixin.IconElement.call( this, config );
12505
12506 // Properties
12507 this.outline = outline;
12508 this.$movers = $( '<div>' );
12509 this.upButton = new OO.ui.ButtonWidget( {
12510 framed: false,
12511 icon: 'collapse',
12512 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12513 } );
12514 this.downButton = new OO.ui.ButtonWidget( {
12515 framed: false,
12516 icon: 'expand',
12517 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12518 } );
12519 this.removeButton = new OO.ui.ButtonWidget( {
12520 framed: false,
12521 icon: 'remove',
12522 title: OO.ui.msg( 'ooui-outline-control-remove' )
12523 } );
12524 this.abilities = { move: true, remove: true };
12525
12526 // Events
12527 outline.connect( this, {
12528 select: 'onOutlineChange',
12529 add: 'onOutlineChange',
12530 remove: 'onOutlineChange'
12531 } );
12532 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12533 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12534 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12535
12536 // Initialization
12537 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12538 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12539 this.$movers
12540 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12541 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12542 this.$element.append( this.$icon, this.$group, this.$movers );
12543 this.setAbilities( config.abilities || {} );
12544 };
12545
12546 /* Setup */
12547
12548 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12549 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12550 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12551
12552 /* Events */
12553
12554 /**
12555 * @event move
12556 * @param {number} places Number of places to move
12557 */
12558
12559 /**
12560 * @event remove
12561 */
12562
12563 /* Methods */
12564
12565 /**
12566 * Set abilities.
12567 *
12568 * @param {Object} abilities List of abilties
12569 * @param {boolean} [abilities.move] Allow moving movable items
12570 * @param {boolean} [abilities.remove] Allow removing removable items
12571 */
12572 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12573 var ability;
12574
12575 for ( ability in this.abilities ) {
12576 if ( abilities[ ability ] !== undefined ) {
12577 this.abilities[ ability ] = !!abilities[ ability ];
12578 }
12579 }
12580
12581 this.onOutlineChange();
12582 };
12583
12584 /**
12585 * @private
12586 * Handle outline change events.
12587 */
12588 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12589 var i, len, firstMovable, lastMovable,
12590 items = this.outline.getItems(),
12591 selectedItem = this.outline.getSelectedItem(),
12592 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12593 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12594
12595 if ( movable ) {
12596 i = -1;
12597 len = items.length;
12598 while ( ++i < len ) {
12599 if ( items[ i ].isMovable() ) {
12600 firstMovable = items[ i ];
12601 break;
12602 }
12603 }
12604 i = len;
12605 while ( i-- ) {
12606 if ( items[ i ].isMovable() ) {
12607 lastMovable = items[ i ];
12608 break;
12609 }
12610 }
12611 }
12612 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12613 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12614 this.removeButton.setDisabled( !removable );
12615 };
12616
12617 /**
12618 * ToggleWidget implements basic behavior of widgets with an on/off state.
12619 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12620 *
12621 * @abstract
12622 * @class
12623 * @extends OO.ui.Widget
12624 *
12625 * @constructor
12626 * @param {Object} [config] Configuration options
12627 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12628 * By default, the toggle is in the 'off' state.
12629 */
12630 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12631 // Configuration initialization
12632 config = config || {};
12633
12634 // Parent constructor
12635 OO.ui.ToggleWidget.parent.call( this, config );
12636
12637 // Properties
12638 this.value = null;
12639
12640 // Initialization
12641 this.$element.addClass( 'oo-ui-toggleWidget' );
12642 this.setValue( !!config.value );
12643 };
12644
12645 /* Setup */
12646
12647 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12648
12649 /* Events */
12650
12651 /**
12652 * @event change
12653 *
12654 * A change event is emitted when the on/off state of the toggle changes.
12655 *
12656 * @param {boolean} value Value representing the new state of the toggle
12657 */
12658
12659 /* Methods */
12660
12661 /**
12662 * Get the value representing the toggle’s state.
12663 *
12664 * @return {boolean} The on/off state of the toggle
12665 */
12666 OO.ui.ToggleWidget.prototype.getValue = function () {
12667 return this.value;
12668 };
12669
12670 /**
12671 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12672 *
12673 * @param {boolean} value The state of the toggle
12674 * @fires change
12675 * @chainable
12676 */
12677 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12678 value = !!value;
12679 if ( this.value !== value ) {
12680 this.value = value;
12681 this.emit( 'change', value );
12682 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12683 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12684 this.$element.attr( 'aria-checked', value.toString() );
12685 }
12686 return this;
12687 };
12688
12689 /**
12690 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12691 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12692 * removed, and cleared from the group.
12693 *
12694 * @example
12695 * // Example: A ButtonGroupWidget with two buttons
12696 * var button1 = new OO.ui.PopupButtonWidget( {
12697 * label: 'Select a category',
12698 * icon: 'menu',
12699 * popup: {
12700 * $content: $( '<p>List of categories...</p>' ),
12701 * padded: true,
12702 * align: 'left'
12703 * }
12704 * } );
12705 * var button2 = new OO.ui.ButtonWidget( {
12706 * label: 'Add item'
12707 * });
12708 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12709 * items: [button1, button2]
12710 * } );
12711 * $( 'body' ).append( buttonGroup.$element );
12712 *
12713 * @class
12714 * @extends OO.ui.Widget
12715 * @mixins OO.ui.mixin.GroupElement
12716 *
12717 * @constructor
12718 * @param {Object} [config] Configuration options
12719 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12720 */
12721 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12722 // Configuration initialization
12723 config = config || {};
12724
12725 // Parent constructor
12726 OO.ui.ButtonGroupWidget.parent.call( this, config );
12727
12728 // Mixin constructors
12729 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12730
12731 // Initialization
12732 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12733 if ( Array.isArray( config.items ) ) {
12734 this.addItems( config.items );
12735 }
12736 };
12737
12738 /* Setup */
12739
12740 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12741 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12742
12743 /**
12744 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12745 * feels, and functionality can be customized via the class’s configuration options
12746 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12747 * and examples.
12748 *
12749 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12750 *
12751 * @example
12752 * // A button widget
12753 * var button = new OO.ui.ButtonWidget( {
12754 * label: 'Button with Icon',
12755 * icon: 'remove',
12756 * iconTitle: 'Remove'
12757 * } );
12758 * $( 'body' ).append( button.$element );
12759 *
12760 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12761 *
12762 * @class
12763 * @extends OO.ui.Widget
12764 * @mixins OO.ui.mixin.ButtonElement
12765 * @mixins OO.ui.mixin.IconElement
12766 * @mixins OO.ui.mixin.IndicatorElement
12767 * @mixins OO.ui.mixin.LabelElement
12768 * @mixins OO.ui.mixin.TitledElement
12769 * @mixins OO.ui.mixin.FlaggedElement
12770 * @mixins OO.ui.mixin.TabIndexedElement
12771 * @mixins OO.ui.mixin.AccessKeyedElement
12772 *
12773 * @constructor
12774 * @param {Object} [config] Configuration options
12775 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12776 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12777 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12778 */
12779 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12780 // Configuration initialization
12781 config = config || {};
12782
12783 // Parent constructor
12784 OO.ui.ButtonWidget.parent.call( this, config );
12785
12786 // Mixin constructors
12787 OO.ui.mixin.ButtonElement.call( this, config );
12788 OO.ui.mixin.IconElement.call( this, config );
12789 OO.ui.mixin.IndicatorElement.call( this, config );
12790 OO.ui.mixin.LabelElement.call( this, config );
12791 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12792 OO.ui.mixin.FlaggedElement.call( this, config );
12793 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12794 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12795
12796 // Properties
12797 this.href = null;
12798 this.target = null;
12799 this.noFollow = false;
12800
12801 // Events
12802 this.connect( this, { disable: 'onDisable' } );
12803
12804 // Initialization
12805 this.$button.append( this.$icon, this.$label, this.$indicator );
12806 this.$element
12807 .addClass( 'oo-ui-buttonWidget' )
12808 .append( this.$button );
12809 this.setHref( config.href );
12810 this.setTarget( config.target );
12811 this.setNoFollow( config.noFollow );
12812 };
12813
12814 /* Setup */
12815
12816 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12817 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12818 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12819 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12820 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12821 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12822 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12823 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12824 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12825
12826 /* Methods */
12827
12828 /**
12829 * @inheritdoc
12830 */
12831 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12832 if ( !this.isDisabled() ) {
12833 // Remove the tab-index while the button is down to prevent the button from stealing focus
12834 this.$button.removeAttr( 'tabindex' );
12835 }
12836
12837 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12838 };
12839
12840 /**
12841 * @inheritdoc
12842 */
12843 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12844 if ( !this.isDisabled() ) {
12845 // Restore the tab-index after the button is up to restore the button's accessibility
12846 this.$button.attr( 'tabindex', this.tabIndex );
12847 }
12848
12849 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12850 };
12851
12852 /**
12853 * Get hyperlink location.
12854 *
12855 * @return {string} Hyperlink location
12856 */
12857 OO.ui.ButtonWidget.prototype.getHref = function () {
12858 return this.href;
12859 };
12860
12861 /**
12862 * Get hyperlink target.
12863 *
12864 * @return {string} Hyperlink target
12865 */
12866 OO.ui.ButtonWidget.prototype.getTarget = function () {
12867 return this.target;
12868 };
12869
12870 /**
12871 * Get search engine traversal hint.
12872 *
12873 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12874 */
12875 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12876 return this.noFollow;
12877 };
12878
12879 /**
12880 * Set hyperlink location.
12881 *
12882 * @param {string|null} href Hyperlink location, null to remove
12883 */
12884 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12885 href = typeof href === 'string' ? href : null;
12886 if ( href !== null ) {
12887 if ( !OO.ui.isSafeUrl( href ) ) {
12888 throw new Error( 'Potentially unsafe href provided: ' + href );
12889 }
12890
12891 }
12892
12893 if ( href !== this.href ) {
12894 this.href = href;
12895 this.updateHref();
12896 }
12897
12898 return this;
12899 };
12900
12901 /**
12902 * Update the `href` attribute, in case of changes to href or
12903 * disabled state.
12904 *
12905 * @private
12906 * @chainable
12907 */
12908 OO.ui.ButtonWidget.prototype.updateHref = function () {
12909 if ( this.href !== null && !this.isDisabled() ) {
12910 this.$button.attr( 'href', this.href );
12911 } else {
12912 this.$button.removeAttr( 'href' );
12913 }
12914
12915 return this;
12916 };
12917
12918 /**
12919 * Handle disable events.
12920 *
12921 * @private
12922 * @param {boolean} disabled Element is disabled
12923 */
12924 OO.ui.ButtonWidget.prototype.onDisable = function () {
12925 this.updateHref();
12926 };
12927
12928 /**
12929 * Set hyperlink target.
12930 *
12931 * @param {string|null} target Hyperlink target, null to remove
12932 */
12933 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12934 target = typeof target === 'string' ? target : null;
12935
12936 if ( target !== this.target ) {
12937 this.target = target;
12938 if ( target !== null ) {
12939 this.$button.attr( 'target', target );
12940 } else {
12941 this.$button.removeAttr( 'target' );
12942 }
12943 }
12944
12945 return this;
12946 };
12947
12948 /**
12949 * Set search engine traversal hint.
12950 *
12951 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12952 */
12953 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12954 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12955
12956 if ( noFollow !== this.noFollow ) {
12957 this.noFollow = noFollow;
12958 if ( noFollow ) {
12959 this.$button.attr( 'rel', 'nofollow' );
12960 } else {
12961 this.$button.removeAttr( 'rel' );
12962 }
12963 }
12964
12965 return this;
12966 };
12967
12968 /**
12969 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12970 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12971 * of the actions.
12972 *
12973 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12974 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12975 * and examples.
12976 *
12977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12978 *
12979 * @class
12980 * @extends OO.ui.ButtonWidget
12981 * @mixins OO.ui.mixin.PendingElement
12982 *
12983 * @constructor
12984 * @param {Object} [config] Configuration options
12985 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12986 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12987 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12988 * for more information about setting modes.
12989 * @cfg {boolean} [framed=false] Render the action button with a frame
12990 */
12991 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12992 // Configuration initialization
12993 config = $.extend( { framed: false }, config );
12994
12995 // Parent constructor
12996 OO.ui.ActionWidget.parent.call( this, config );
12997
12998 // Mixin constructors
12999 OO.ui.mixin.PendingElement.call( this, config );
13000
13001 // Properties
13002 this.action = config.action || '';
13003 this.modes = config.modes || [];
13004 this.width = 0;
13005 this.height = 0;
13006
13007 // Initialization
13008 this.$element.addClass( 'oo-ui-actionWidget' );
13009 };
13010
13011 /* Setup */
13012
13013 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
13014 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
13015
13016 /* Events */
13017
13018 /**
13019 * A resize event is emitted when the size of the widget changes.
13020 *
13021 * @event resize
13022 */
13023
13024 /* Methods */
13025
13026 /**
13027 * Check if the action is configured to be available in the specified `mode`.
13028 *
13029 * @param {string} mode Name of mode
13030 * @return {boolean} The action is configured with the mode
13031 */
13032 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
13033 return this.modes.indexOf( mode ) !== -1;
13034 };
13035
13036 /**
13037 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
13038 *
13039 * @return {string}
13040 */
13041 OO.ui.ActionWidget.prototype.getAction = function () {
13042 return this.action;
13043 };
13044
13045 /**
13046 * Get the symbolic name of the mode or modes for which the action is configured to be available.
13047 *
13048 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
13049 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
13050 * are hidden.
13051 *
13052 * @return {string[]}
13053 */
13054 OO.ui.ActionWidget.prototype.getModes = function () {
13055 return this.modes.slice();
13056 };
13057
13058 /**
13059 * Emit a resize event if the size has changed.
13060 *
13061 * @private
13062 * @chainable
13063 */
13064 OO.ui.ActionWidget.prototype.propagateResize = function () {
13065 var width, height;
13066
13067 if ( this.isElementAttached() ) {
13068 width = this.$element.width();
13069 height = this.$element.height();
13070
13071 if ( width !== this.width || height !== this.height ) {
13072 this.width = width;
13073 this.height = height;
13074 this.emit( 'resize' );
13075 }
13076 }
13077
13078 return this;
13079 };
13080
13081 /**
13082 * @inheritdoc
13083 */
13084 OO.ui.ActionWidget.prototype.setIcon = function () {
13085 // Mixin method
13086 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
13087 this.propagateResize();
13088
13089 return this;
13090 };
13091
13092 /**
13093 * @inheritdoc
13094 */
13095 OO.ui.ActionWidget.prototype.setLabel = function () {
13096 // Mixin method
13097 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
13098 this.propagateResize();
13099
13100 return this;
13101 };
13102
13103 /**
13104 * @inheritdoc
13105 */
13106 OO.ui.ActionWidget.prototype.setFlags = function () {
13107 // Mixin method
13108 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
13109 this.propagateResize();
13110
13111 return this;
13112 };
13113
13114 /**
13115 * @inheritdoc
13116 */
13117 OO.ui.ActionWidget.prototype.clearFlags = function () {
13118 // Mixin method
13119 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
13120 this.propagateResize();
13121
13122 return this;
13123 };
13124
13125 /**
13126 * Toggle the visibility of the action button.
13127 *
13128 * @param {boolean} [show] Show button, omit to toggle visibility
13129 * @chainable
13130 */
13131 OO.ui.ActionWidget.prototype.toggle = function () {
13132 // Parent method
13133 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
13134 this.propagateResize();
13135
13136 return this;
13137 };
13138
13139 /**
13140 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
13141 * which is used to display additional information or options.
13142 *
13143 * @example
13144 * // Example of a popup button.
13145 * var popupButton = new OO.ui.PopupButtonWidget( {
13146 * label: 'Popup button with options',
13147 * icon: 'menu',
13148 * popup: {
13149 * $content: $( '<p>Additional options here.</p>' ),
13150 * padded: true,
13151 * align: 'force-left'
13152 * }
13153 * } );
13154 * // Append the button to the DOM.
13155 * $( 'body' ).append( popupButton.$element );
13156 *
13157 * @class
13158 * @extends OO.ui.ButtonWidget
13159 * @mixins OO.ui.mixin.PopupElement
13160 *
13161 * @constructor
13162 * @param {Object} [config] Configuration options
13163 */
13164 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
13165 // Parent constructor
13166 OO.ui.PopupButtonWidget.parent.call( this, config );
13167
13168 // Mixin constructors
13169 OO.ui.mixin.PopupElement.call( this, config );
13170
13171 // Events
13172 this.connect( this, { click: 'onAction' } );
13173
13174 // Initialization
13175 this.$element
13176 .addClass( 'oo-ui-popupButtonWidget' )
13177 .attr( 'aria-haspopup', 'true' )
13178 .append( this.popup.$element );
13179 };
13180
13181 /* Setup */
13182
13183 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
13184 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
13185
13186 /* Methods */
13187
13188 /**
13189 * Handle the button action being triggered.
13190 *
13191 * @private
13192 */
13193 OO.ui.PopupButtonWidget.prototype.onAction = function () {
13194 this.popup.toggle();
13195 };
13196
13197 /**
13198 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
13199 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
13200 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
13201 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
13202 * and {@link OO.ui.mixin.LabelElement labels}. Please see
13203 * the [OOjs UI documentation][1] on MediaWiki for more information.
13204 *
13205 * @example
13206 * // Toggle buttons in the 'off' and 'on' state.
13207 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
13208 * label: 'Toggle Button off'
13209 * } );
13210 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
13211 * label: 'Toggle Button on',
13212 * value: true
13213 * } );
13214 * // Append the buttons to the DOM.
13215 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
13216 *
13217 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
13218 *
13219 * @class
13220 * @extends OO.ui.ToggleWidget
13221 * @mixins OO.ui.mixin.ButtonElement
13222 * @mixins OO.ui.mixin.IconElement
13223 * @mixins OO.ui.mixin.IndicatorElement
13224 * @mixins OO.ui.mixin.LabelElement
13225 * @mixins OO.ui.mixin.TitledElement
13226 * @mixins OO.ui.mixin.FlaggedElement
13227 * @mixins OO.ui.mixin.TabIndexedElement
13228 *
13229 * @constructor
13230 * @param {Object} [config] Configuration options
13231 * @cfg {boolean} [value=false] The toggle button’s initial on/off
13232 * state. By default, the button is in the 'off' state.
13233 */
13234 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
13235 // Configuration initialization
13236 config = config || {};
13237
13238 // Parent constructor
13239 OO.ui.ToggleButtonWidget.parent.call( this, config );
13240
13241 // Mixin constructors
13242 OO.ui.mixin.ButtonElement.call( this, config );
13243 OO.ui.mixin.IconElement.call( this, config );
13244 OO.ui.mixin.IndicatorElement.call( this, config );
13245 OO.ui.mixin.LabelElement.call( this, config );
13246 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
13247 OO.ui.mixin.FlaggedElement.call( this, config );
13248 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13249
13250 // Events
13251 this.connect( this, { click: 'onAction' } );
13252
13253 // Initialization
13254 this.$button.append( this.$icon, this.$label, this.$indicator );
13255 this.$element
13256 .addClass( 'oo-ui-toggleButtonWidget' )
13257 .append( this.$button );
13258 };
13259
13260 /* Setup */
13261
13262 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
13263 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
13264 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
13265 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
13266 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
13267 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
13268 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
13269 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
13270
13271 /* Methods */
13272
13273 /**
13274 * Handle the button action being triggered.
13275 *
13276 * @private
13277 */
13278 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
13279 this.setValue( !this.value );
13280 };
13281
13282 /**
13283 * @inheritdoc
13284 */
13285 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
13286 value = !!value;
13287 if ( value !== this.value ) {
13288 // Might be called from parent constructor before ButtonElement constructor
13289 if ( this.$button ) {
13290 this.$button.attr( 'aria-pressed', value.toString() );
13291 }
13292 this.setActive( value );
13293 }
13294
13295 // Parent method
13296 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
13297
13298 return this;
13299 };
13300
13301 /**
13302 * @inheritdoc
13303 */
13304 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
13305 if ( this.$button ) {
13306 this.$button.removeAttr( 'aria-pressed' );
13307 }
13308 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
13309 this.$button.attr( 'aria-pressed', this.value.toString() );
13310 };
13311
13312 /**
13313 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
13314 * that allows for selecting multiple values.
13315 *
13316 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13317 *
13318 * @example
13319 * // Example: A CapsuleMultiSelectWidget.
13320 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13321 * label: 'CapsuleMultiSelectWidget',
13322 * selected: [ 'Option 1', 'Option 3' ],
13323 * menu: {
13324 * items: [
13325 * new OO.ui.MenuOptionWidget( {
13326 * data: 'Option 1',
13327 * label: 'Option One'
13328 * } ),
13329 * new OO.ui.MenuOptionWidget( {
13330 * data: 'Option 2',
13331 * label: 'Option Two'
13332 * } ),
13333 * new OO.ui.MenuOptionWidget( {
13334 * data: 'Option 3',
13335 * label: 'Option Three'
13336 * } ),
13337 * new OO.ui.MenuOptionWidget( {
13338 * data: 'Option 4',
13339 * label: 'Option Four'
13340 * } ),
13341 * new OO.ui.MenuOptionWidget( {
13342 * data: 'Option 5',
13343 * label: 'Option Five'
13344 * } )
13345 * ]
13346 * }
13347 * } );
13348 * $( 'body' ).append( capsule.$element );
13349 *
13350 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13351 *
13352 * @class
13353 * @extends OO.ui.Widget
13354 * @mixins OO.ui.mixin.TabIndexedElement
13355 * @mixins OO.ui.mixin.GroupElement
13356 *
13357 * @constructor
13358 * @param {Object} [config] Configuration options
13359 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13360 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13361 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13362 * If specified, this popup will be shown instead of the menu (but the menu
13363 * will still be used for item labels and allowArbitrary=false). The widgets
13364 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13365 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13366 * This configuration is useful in cases where the expanded menu is larger than
13367 * its containing `<div>`. The specified overlay layer is usually on top of
13368 * the containing `<div>` and has a larger area. By default, the menu uses
13369 * relative positioning.
13370 */
13371 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
13372 var $tabFocus;
13373
13374 // Configuration initialization
13375 config = config || {};
13376
13377 // Parent constructor
13378 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
13379
13380 // Properties (must be set before mixin constructor calls)
13381 this.$input = config.popup ? null : $( '<input>' );
13382 this.$handle = $( '<div>' );
13383
13384 // Mixin constructors
13385 OO.ui.mixin.GroupElement.call( this, config );
13386 if ( config.popup ) {
13387 config.popup = $.extend( {}, config.popup, {
13388 align: 'forwards',
13389 anchor: false
13390 } );
13391 OO.ui.mixin.PopupElement.call( this, config );
13392 $tabFocus = $( '<span>' );
13393 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
13394 } else {
13395 this.popup = null;
13396 $tabFocus = null;
13397 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
13398 }
13399 OO.ui.mixin.IndicatorElement.call( this, config );
13400 OO.ui.mixin.IconElement.call( this, config );
13401
13402 // Properties
13403 this.allowArbitrary = !!config.allowArbitrary;
13404 this.$overlay = config.$overlay || this.$element;
13405 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
13406 {
13407 widget: this,
13408 $input: this.$input,
13409 $container: this.$element,
13410 filterFromInput: true,
13411 disabled: this.isDisabled()
13412 },
13413 config.menu
13414 ) );
13415
13416 // Events
13417 if ( this.popup ) {
13418 $tabFocus.on( {
13419 focus: this.onFocusForPopup.bind( this )
13420 } );
13421 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13422 if ( this.popup.$autoCloseIgnore ) {
13423 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
13424 }
13425 this.popup.connect( this, {
13426 toggle: function ( visible ) {
13427 $tabFocus.toggle( !visible );
13428 }
13429 } );
13430 } else {
13431 this.$input.on( {
13432 focus: this.onInputFocus.bind( this ),
13433 blur: this.onInputBlur.bind( this ),
13434 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
13435 keydown: this.onKeyDown.bind( this ),
13436 keypress: this.onKeyPress.bind( this )
13437 } );
13438 }
13439 this.menu.connect( this, {
13440 choose: 'onMenuChoose',
13441 add: 'onMenuItemsChange',
13442 remove: 'onMenuItemsChange'
13443 } );
13444 this.$handle.on( {
13445 click: this.onClick.bind( this )
13446 } );
13447
13448 // Initialization
13449 if ( this.$input ) {
13450 this.$input.prop( 'disabled', this.isDisabled() );
13451 this.$input.attr( {
13452 role: 'combobox',
13453 'aria-autocomplete': 'list'
13454 } );
13455 this.$input.width( '1em' );
13456 }
13457 if ( config.data ) {
13458 this.setItemsFromData( config.data );
13459 }
13460 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13461 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13462 .append( this.$indicator, this.$icon, this.$group );
13463 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13464 .append( this.$handle );
13465 if ( this.popup ) {
13466 this.$handle.append( $tabFocus );
13467 this.$overlay.append( this.popup.$element );
13468 } else {
13469 this.$handle.append( this.$input );
13470 this.$overlay.append( this.menu.$element );
13471 }
13472 this.onMenuItemsChange();
13473 };
13474
13475 /* Setup */
13476
13477 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13478 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13479 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13480 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13481 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13482 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13483
13484 /* Events */
13485
13486 /**
13487 * @event change
13488 *
13489 * A change event is emitted when the set of selected items changes.
13490 *
13491 * @param {Mixed[]} datas Data of the now-selected items
13492 */
13493
13494 /* Methods */
13495
13496 /**
13497 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13498 *
13499 * @protected
13500 * @param {Mixed} data Custom data of any type.
13501 * @param {string} label The label text.
13502 * @return {OO.ui.CapsuleItemWidget}
13503 */
13504 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
13505 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13506 };
13507
13508 /**
13509 * Get the data of the items in the capsule
13510 * @return {Mixed[]}
13511 */
13512 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13513 return $.map( this.getItems(), function ( e ) { return e.data; } );
13514 };
13515
13516 /**
13517 * Set the items in the capsule by providing data
13518 * @chainable
13519 * @param {Mixed[]} datas
13520 * @return {OO.ui.CapsuleMultiSelectWidget}
13521 */
13522 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13523 var widget = this,
13524 menu = this.menu,
13525 items = this.getItems();
13526
13527 $.each( datas, function ( i, data ) {
13528 var j, label,
13529 item = menu.getItemFromData( data );
13530
13531 if ( item ) {
13532 label = item.label;
13533 } else if ( widget.allowArbitrary ) {
13534 label = String( data );
13535 } else {
13536 return;
13537 }
13538
13539 item = null;
13540 for ( j = 0; j < items.length; j++ ) {
13541 if ( items[ j ].data === data && items[ j ].label === label ) {
13542 item = items[ j ];
13543 items.splice( j, 1 );
13544 break;
13545 }
13546 }
13547 if ( !item ) {
13548 item = widget.createItemWidget( data, label );
13549 }
13550 widget.addItems( [ item ], i );
13551 } );
13552
13553 if ( items.length ) {
13554 widget.removeItems( items );
13555 }
13556
13557 return this;
13558 };
13559
13560 /**
13561 * Add items to the capsule by providing their data
13562 * @chainable
13563 * @param {Mixed[]} datas
13564 * @return {OO.ui.CapsuleMultiSelectWidget}
13565 */
13566 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13567 var widget = this,
13568 menu = this.menu,
13569 items = [];
13570
13571 $.each( datas, function ( i, data ) {
13572 var item;
13573
13574 if ( !widget.getItemFromData( data ) ) {
13575 item = menu.getItemFromData( data );
13576 if ( item ) {
13577 items.push( widget.createItemWidget( data, item.label ) );
13578 } else if ( widget.allowArbitrary ) {
13579 items.push( widget.createItemWidget( data, String( data ) ) );
13580 }
13581 }
13582 } );
13583
13584 if ( items.length ) {
13585 this.addItems( items );
13586 }
13587
13588 return this;
13589 };
13590
13591 /**
13592 * Remove items by data
13593 * @chainable
13594 * @param {Mixed[]} datas
13595 * @return {OO.ui.CapsuleMultiSelectWidget}
13596 */
13597 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13598 var widget = this,
13599 items = [];
13600
13601 $.each( datas, function ( i, data ) {
13602 var item = widget.getItemFromData( data );
13603 if ( item ) {
13604 items.push( item );
13605 }
13606 } );
13607
13608 if ( items.length ) {
13609 this.removeItems( items );
13610 }
13611
13612 return this;
13613 };
13614
13615 /**
13616 * @inheritdoc
13617 */
13618 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13619 var same, i, l,
13620 oldItems = this.items.slice();
13621
13622 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13623
13624 if ( this.items.length !== oldItems.length ) {
13625 same = false;
13626 } else {
13627 same = true;
13628 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13629 same = same && this.items[ i ] === oldItems[ i ];
13630 }
13631 }
13632 if ( !same ) {
13633 this.emit( 'change', this.getItemsData() );
13634 }
13635
13636 return this;
13637 };
13638
13639 /**
13640 * @inheritdoc
13641 */
13642 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13643 var same, i, l,
13644 oldItems = this.items.slice();
13645
13646 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13647
13648 if ( this.items.length !== oldItems.length ) {
13649 same = false;
13650 } else {
13651 same = true;
13652 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13653 same = same && this.items[ i ] === oldItems[ i ];
13654 }
13655 }
13656 if ( !same ) {
13657 this.emit( 'change', this.getItemsData() );
13658 }
13659
13660 return this;
13661 };
13662
13663 /**
13664 * @inheritdoc
13665 */
13666 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13667 if ( this.items.length ) {
13668 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13669 this.emit( 'change', this.getItemsData() );
13670 }
13671 return this;
13672 };
13673
13674 /**
13675 * Get the capsule widget's menu.
13676 * @return {OO.ui.MenuSelectWidget} Menu widget
13677 */
13678 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13679 return this.menu;
13680 };
13681
13682 /**
13683 * Handle focus events
13684 *
13685 * @private
13686 * @param {jQuery.Event} event
13687 */
13688 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13689 if ( !this.isDisabled() ) {
13690 this.menu.toggle( true );
13691 }
13692 };
13693
13694 /**
13695 * Handle blur events
13696 *
13697 * @private
13698 * @param {jQuery.Event} event
13699 */
13700 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13701 if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13702 this.addItemsFromData( [ this.$input.val() ] );
13703 }
13704 this.clearInput();
13705 };
13706
13707 /**
13708 * Handle focus events
13709 *
13710 * @private
13711 * @param {jQuery.Event} event
13712 */
13713 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13714 if ( !this.isDisabled() ) {
13715 this.popup.setSize( this.$handle.width() );
13716 this.popup.toggle( true );
13717 this.popup.$element.find( '*' )
13718 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13719 .first()
13720 .focus();
13721 }
13722 };
13723
13724 /**
13725 * Handles popup focus out events.
13726 *
13727 * @private
13728 * @param {Event} e Focus out event
13729 */
13730 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13731 var widget = this.popup;
13732
13733 setTimeout( function () {
13734 if (
13735 widget.isVisible() &&
13736 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13737 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13738 ) {
13739 widget.toggle( false );
13740 }
13741 } );
13742 };
13743
13744 /**
13745 * Handle mouse click events.
13746 *
13747 * @private
13748 * @param {jQuery.Event} e Mouse click event
13749 */
13750 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13751 if ( e.which === 1 ) {
13752 this.focus();
13753 return false;
13754 }
13755 };
13756
13757 /**
13758 * Handle key press events.
13759 *
13760 * @private
13761 * @param {jQuery.Event} e Key press event
13762 */
13763 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13764 var item;
13765
13766 if ( !this.isDisabled() ) {
13767 if ( e.which === OO.ui.Keys.ESCAPE ) {
13768 this.clearInput();
13769 return false;
13770 }
13771
13772 if ( !this.popup ) {
13773 this.menu.toggle( true );
13774 if ( e.which === OO.ui.Keys.ENTER ) {
13775 item = this.menu.getItemFromLabel( this.$input.val(), true );
13776 if ( item ) {
13777 this.addItemsFromData( [ item.data ] );
13778 this.clearInput();
13779 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13780 this.addItemsFromData( [ this.$input.val() ] );
13781 this.clearInput();
13782 }
13783 return false;
13784 }
13785
13786 // Make sure the input gets resized.
13787 setTimeout( this.onInputChange.bind( this ), 0 );
13788 }
13789 }
13790 };
13791
13792 /**
13793 * Handle key down events.
13794 *
13795 * @private
13796 * @param {jQuery.Event} e Key down event
13797 */
13798 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13799 if ( !this.isDisabled() ) {
13800 // 'keypress' event is not triggered for Backspace
13801 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13802 if ( this.items.length ) {
13803 this.removeItems( this.items.slice( -1 ) );
13804 }
13805 return false;
13806 }
13807 }
13808 };
13809
13810 /**
13811 * Handle input change events.
13812 *
13813 * @private
13814 * @param {jQuery.Event} e Event of some sort
13815 */
13816 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13817 if ( !this.isDisabled() ) {
13818 this.$input.width( this.$input.val().length + 'em' );
13819 }
13820 };
13821
13822 /**
13823 * Handle menu choose events.
13824 *
13825 * @private
13826 * @param {OO.ui.OptionWidget} item Chosen item
13827 */
13828 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13829 if ( item && item.isVisible() ) {
13830 this.addItemsFromData( [ item.getData() ] );
13831 this.clearInput();
13832 }
13833 };
13834
13835 /**
13836 * Handle menu item change events.
13837 *
13838 * @private
13839 */
13840 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13841 this.setItemsFromData( this.getItemsData() );
13842 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13843 };
13844
13845 /**
13846 * Clear the input field
13847 * @private
13848 */
13849 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13850 if ( this.$input ) {
13851 this.$input.val( '' );
13852 this.$input.width( '1em' );
13853 }
13854 if ( this.popup ) {
13855 this.popup.toggle( false );
13856 }
13857 this.menu.toggle( false );
13858 this.menu.selectItem();
13859 this.menu.highlightItem();
13860 };
13861
13862 /**
13863 * @inheritdoc
13864 */
13865 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13866 var i, len;
13867
13868 // Parent method
13869 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13870
13871 if ( this.$input ) {
13872 this.$input.prop( 'disabled', this.isDisabled() );
13873 }
13874 if ( this.menu ) {
13875 this.menu.setDisabled( this.isDisabled() );
13876 }
13877 if ( this.popup ) {
13878 this.popup.setDisabled( this.isDisabled() );
13879 }
13880
13881 if ( this.items ) {
13882 for ( i = 0, len = this.items.length; i < len; i++ ) {
13883 this.items[ i ].updateDisabled();
13884 }
13885 }
13886
13887 return this;
13888 };
13889
13890 /**
13891 * Focus the widget
13892 * @chainable
13893 * @return {OO.ui.CapsuleMultiSelectWidget}
13894 */
13895 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13896 if ( !this.isDisabled() ) {
13897 if ( this.popup ) {
13898 this.popup.setSize( this.$handle.width() );
13899 this.popup.toggle( true );
13900 this.popup.$element.find( '*' )
13901 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13902 .first()
13903 .focus();
13904 } else {
13905 this.menu.toggle( true );
13906 this.$input.focus();
13907 }
13908 }
13909 return this;
13910 };
13911
13912 /**
13913 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13914 * CapsuleMultiSelectWidget} to display the selected items.
13915 *
13916 * @class
13917 * @extends OO.ui.Widget
13918 * @mixins OO.ui.mixin.ItemWidget
13919 * @mixins OO.ui.mixin.IndicatorElement
13920 * @mixins OO.ui.mixin.LabelElement
13921 * @mixins OO.ui.mixin.FlaggedElement
13922 * @mixins OO.ui.mixin.TabIndexedElement
13923 *
13924 * @constructor
13925 * @param {Object} [config] Configuration options
13926 */
13927 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13928 // Configuration initialization
13929 config = config || {};
13930
13931 // Parent constructor
13932 OO.ui.CapsuleItemWidget.parent.call( this, config );
13933
13934 // Properties (must be set before mixin constructor calls)
13935 this.$indicator = $( '<span>' );
13936
13937 // Mixin constructors
13938 OO.ui.mixin.ItemWidget.call( this );
13939 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13940 OO.ui.mixin.LabelElement.call( this, config );
13941 OO.ui.mixin.FlaggedElement.call( this, config );
13942 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13943
13944 // Events
13945 this.$indicator.on( {
13946 keydown: this.onCloseKeyDown.bind( this ),
13947 click: this.onCloseClick.bind( this )
13948 } );
13949
13950 // Initialization
13951 this.$element
13952 .addClass( 'oo-ui-capsuleItemWidget' )
13953 .append( this.$indicator, this.$label );
13954 };
13955
13956 /* Setup */
13957
13958 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13959 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13960 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13961 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13962 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13963 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13964
13965 /* Methods */
13966
13967 /**
13968 * Handle close icon clicks
13969 * @param {jQuery.Event} event
13970 */
13971 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13972 var element = this.getElementGroup();
13973
13974 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13975 element.removeItems( [ this ] );
13976 element.focus();
13977 }
13978 };
13979
13980 /**
13981 * Handle close keyboard events
13982 * @param {jQuery.Event} event Key down event
13983 */
13984 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13985 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13986 switch ( e.which ) {
13987 case OO.ui.Keys.ENTER:
13988 case OO.ui.Keys.BACKSPACE:
13989 case OO.ui.Keys.SPACE:
13990 this.getElementGroup().removeItems( [ this ] );
13991 return false;
13992 }
13993 }
13994 };
13995
13996 /**
13997 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13998 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13999 * users can interact with it.
14000 *
14001 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
14002 * OO.ui.DropdownInputWidget instead.
14003 *
14004 * @example
14005 * // Example: A DropdownWidget with a menu that contains three options
14006 * var dropDown = new OO.ui.DropdownWidget( {
14007 * label: 'Dropdown menu: Select a menu option',
14008 * menu: {
14009 * items: [
14010 * new OO.ui.MenuOptionWidget( {
14011 * data: 'a',
14012 * label: 'First'
14013 * } ),
14014 * new OO.ui.MenuOptionWidget( {
14015 * data: 'b',
14016 * label: 'Second'
14017 * } ),
14018 * new OO.ui.MenuOptionWidget( {
14019 * data: 'c',
14020 * label: 'Third'
14021 * } )
14022 * ]
14023 * }
14024 * } );
14025 *
14026 * $( 'body' ).append( dropDown.$element );
14027 *
14028 * dropDown.getMenu().selectItemByData( 'b' );
14029 *
14030 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
14031 *
14032 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
14033 *
14034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
14035 *
14036 * @class
14037 * @extends OO.ui.Widget
14038 * @mixins OO.ui.mixin.IconElement
14039 * @mixins OO.ui.mixin.IndicatorElement
14040 * @mixins OO.ui.mixin.LabelElement
14041 * @mixins OO.ui.mixin.TitledElement
14042 * @mixins OO.ui.mixin.TabIndexedElement
14043 *
14044 * @constructor
14045 * @param {Object} [config] Configuration options
14046 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
14047 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
14048 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
14049 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
14050 */
14051 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
14052 // Configuration initialization
14053 config = $.extend( { indicator: 'down' }, config );
14054
14055 // Parent constructor
14056 OO.ui.DropdownWidget.parent.call( this, config );
14057
14058 // Properties (must be set before TabIndexedElement constructor call)
14059 this.$handle = this.$( '<span>' );
14060 this.$overlay = config.$overlay || this.$element;
14061
14062 // Mixin constructors
14063 OO.ui.mixin.IconElement.call( this, config );
14064 OO.ui.mixin.IndicatorElement.call( this, config );
14065 OO.ui.mixin.LabelElement.call( this, config );
14066 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
14067 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
14068
14069 // Properties
14070 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
14071 widget: this,
14072 $container: this.$element
14073 }, config.menu ) );
14074
14075 // Events
14076 this.$handle.on( {
14077 click: this.onClick.bind( this ),
14078 keypress: this.onKeyPress.bind( this )
14079 } );
14080 this.menu.connect( this, { select: 'onMenuSelect' } );
14081
14082 // Initialization
14083 this.$handle
14084 .addClass( 'oo-ui-dropdownWidget-handle' )
14085 .append( this.$icon, this.$label, this.$indicator );
14086 this.$element
14087 .addClass( 'oo-ui-dropdownWidget' )
14088 .append( this.$handle );
14089 this.$overlay.append( this.menu.$element );
14090 };
14091
14092 /* Setup */
14093
14094 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
14095 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
14096 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
14097 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
14098 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
14099 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
14100
14101 /* Methods */
14102
14103 /**
14104 * Get the menu.
14105 *
14106 * @return {OO.ui.MenuSelectWidget} Menu of widget
14107 */
14108 OO.ui.DropdownWidget.prototype.getMenu = function () {
14109 return this.menu;
14110 };
14111
14112 /**
14113 * Handles menu select events.
14114 *
14115 * @private
14116 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14117 */
14118 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
14119 var selectedLabel;
14120
14121 if ( !item ) {
14122 this.setLabel( null );
14123 return;
14124 }
14125
14126 selectedLabel = item.getLabel();
14127
14128 // If the label is a DOM element, clone it, because setLabel will append() it
14129 if ( selectedLabel instanceof jQuery ) {
14130 selectedLabel = selectedLabel.clone();
14131 }
14132
14133 this.setLabel( selectedLabel );
14134 };
14135
14136 /**
14137 * Handle mouse click events.
14138 *
14139 * @private
14140 * @param {jQuery.Event} e Mouse click event
14141 */
14142 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
14143 if ( !this.isDisabled() && e.which === 1 ) {
14144 this.menu.toggle();
14145 }
14146 return false;
14147 };
14148
14149 /**
14150 * Handle key press events.
14151 *
14152 * @private
14153 * @param {jQuery.Event} e Key press event
14154 */
14155 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
14156 if ( !this.isDisabled() &&
14157 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
14158 ) {
14159 this.menu.toggle();
14160 return false;
14161 }
14162 };
14163
14164 /**
14165 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
14166 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
14167 * OO.ui.mixin.IndicatorElement indicators}.
14168 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14169 *
14170 * @example
14171 * // Example of a file select widget
14172 * var selectFile = new OO.ui.SelectFileWidget();
14173 * $( 'body' ).append( selectFile.$element );
14174 *
14175 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
14176 *
14177 * @class
14178 * @extends OO.ui.Widget
14179 * @mixins OO.ui.mixin.IconElement
14180 * @mixins OO.ui.mixin.IndicatorElement
14181 * @mixins OO.ui.mixin.PendingElement
14182 * @mixins OO.ui.mixin.LabelElement
14183 *
14184 * @constructor
14185 * @param {Object} [config] Configuration options
14186 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
14187 * @cfg {string} [placeholder] Text to display when no file is selected.
14188 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
14189 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
14190 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
14191 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
14192 */
14193 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
14194 var dragHandler;
14195
14196 // TODO: Remove in next release
14197 if ( config && config.dragDropUI ) {
14198 config.showDropTarget = true;
14199 }
14200
14201 // Configuration initialization
14202 config = $.extend( {
14203 accept: null,
14204 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
14205 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
14206 droppable: true,
14207 showDropTarget: false
14208 }, config );
14209
14210 // Parent constructor
14211 OO.ui.SelectFileWidget.parent.call( this, config );
14212
14213 // Mixin constructors
14214 OO.ui.mixin.IconElement.call( this, config );
14215 OO.ui.mixin.IndicatorElement.call( this, config );
14216 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
14217 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
14218
14219 // Properties
14220 this.$info = $( '<span>' );
14221
14222 // Properties
14223 this.showDropTarget = config.showDropTarget;
14224 this.isSupported = this.constructor.static.isSupported();
14225 this.currentFile = null;
14226 if ( Array.isArray( config.accept ) ) {
14227 this.accept = config.accept;
14228 } else {
14229 this.accept = null;
14230 }
14231 this.placeholder = config.placeholder;
14232 this.notsupported = config.notsupported;
14233 this.onFileSelectedHandler = this.onFileSelected.bind( this );
14234
14235 this.selectButton = new OO.ui.ButtonWidget( {
14236 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
14237 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
14238 disabled: this.disabled || !this.isSupported
14239 } );
14240
14241 this.clearButton = new OO.ui.ButtonWidget( {
14242 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
14243 framed: false,
14244 icon: 'remove',
14245 disabled: this.disabled
14246 } );
14247
14248 // Events
14249 this.selectButton.$button.on( {
14250 keypress: this.onKeyPress.bind( this )
14251 } );
14252 this.clearButton.connect( this, {
14253 click: 'onClearClick'
14254 } );
14255 if ( config.droppable ) {
14256 dragHandler = this.onDragEnterOrOver.bind( this );
14257 this.$element.on( {
14258 dragenter: dragHandler,
14259 dragover: dragHandler,
14260 dragleave: this.onDragLeave.bind( this ),
14261 drop: this.onDrop.bind( this )
14262 } );
14263 }
14264
14265 // Initialization
14266 this.addInput();
14267 this.updateUI();
14268 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
14269 this.$info
14270 .addClass( 'oo-ui-selectFileWidget-info' )
14271 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
14272 this.$element
14273 .addClass( 'oo-ui-selectFileWidget' )
14274 .append( this.$info, this.selectButton.$element );
14275 if ( config.droppable && config.showDropTarget ) {
14276 this.$dropTarget = $( '<div>' )
14277 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14278 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14279 .on( {
14280 click: this.onDropTargetClick.bind( this )
14281 } );
14282 this.$element.prepend( this.$dropTarget );
14283 }
14284 };
14285
14286 /* Setup */
14287
14288 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
14289 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
14290 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
14291 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
14292 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
14293
14294 /* Static Properties */
14295
14296 /**
14297 * Check if this widget is supported
14298 *
14299 * @static
14300 * @return {boolean}
14301 */
14302 OO.ui.SelectFileWidget.static.isSupported = function () {
14303 var $input;
14304 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
14305 $input = $( '<input type="file">' );
14306 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
14307 }
14308 return OO.ui.SelectFileWidget.static.isSupportedCache;
14309 };
14310
14311 OO.ui.SelectFileWidget.static.isSupportedCache = null;
14312
14313 /* Events */
14314
14315 /**
14316 * @event change
14317 *
14318 * A change event is emitted when the on/off state of the toggle changes.
14319 *
14320 * @param {File|null} value New value
14321 */
14322
14323 /* Methods */
14324
14325 /**
14326 * Get the current value of the field
14327 *
14328 * @return {File|null}
14329 */
14330 OO.ui.SelectFileWidget.prototype.getValue = function () {
14331 return this.currentFile;
14332 };
14333
14334 /**
14335 * Set the current value of the field
14336 *
14337 * @param {File|null} file File to select
14338 */
14339 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
14340 if ( this.currentFile !== file ) {
14341 this.currentFile = file;
14342 this.updateUI();
14343 this.emit( 'change', this.currentFile );
14344 }
14345 };
14346
14347 /**
14348 * Focus the widget.
14349 *
14350 * Focusses the select file button.
14351 *
14352 * @chainable
14353 */
14354 OO.ui.SelectFileWidget.prototype.focus = function () {
14355 this.selectButton.$button[ 0 ].focus();
14356 return this;
14357 };
14358
14359 /**
14360 * Update the user interface when a file is selected or unselected
14361 *
14362 * @protected
14363 */
14364 OO.ui.SelectFileWidget.prototype.updateUI = function () {
14365 var $label;
14366 if ( !this.isSupported ) {
14367 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
14368 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14369 this.setLabel( this.notsupported );
14370 } else {
14371 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
14372 if ( this.currentFile ) {
14373 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
14374 $label = $( [] );
14375 if ( this.currentFile.type !== '' ) {
14376 $label = $label.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile.type ) );
14377 }
14378 $label = $label.add( $( '<span>' ).text( this.currentFile.name ) );
14379 this.setLabel( $label );
14380 } else {
14381 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
14382 this.setLabel( this.placeholder );
14383 }
14384 }
14385 };
14386
14387 /**
14388 * Add the input to the widget
14389 *
14390 * @private
14391 */
14392 OO.ui.SelectFileWidget.prototype.addInput = function () {
14393 if ( this.$input ) {
14394 this.$input.remove();
14395 }
14396
14397 if ( !this.isSupported ) {
14398 this.$input = null;
14399 return;
14400 }
14401
14402 this.$input = $( '<input type="file">' );
14403 this.$input.on( 'change', this.onFileSelectedHandler );
14404 this.$input.attr( {
14405 tabindex: -1
14406 } );
14407 if ( this.accept ) {
14408 this.$input.attr( 'accept', this.accept.join( ', ' ) );
14409 }
14410 this.selectButton.$button.append( this.$input );
14411 };
14412
14413 /**
14414 * Determine if we should accept this file
14415 *
14416 * @private
14417 * @param {string} File MIME type
14418 * @return {boolean}
14419 */
14420 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
14421 var i, mimeTest;
14422
14423 if ( !this.accept || !mimeType ) {
14424 return true;
14425 }
14426
14427 for ( i = 0; i < this.accept.length; i++ ) {
14428 mimeTest = this.accept[ i ];
14429 if ( mimeTest === mimeType ) {
14430 return true;
14431 } else if ( mimeTest.substr( -2 ) === '/*' ) {
14432 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
14433 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
14434 return true;
14435 }
14436 }
14437 }
14438
14439 return false;
14440 };
14441
14442 /**
14443 * Handle file selection from the input
14444 *
14445 * @private
14446 * @param {jQuery.Event} e
14447 */
14448 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
14449 var file = OO.getProp( e.target, 'files', 0 ) || null;
14450
14451 if ( file && !this.isAllowedType( file.type ) ) {
14452 file = null;
14453 }
14454
14455 this.setValue( file );
14456 this.addInput();
14457 };
14458
14459 /**
14460 * Handle clear button click events.
14461 *
14462 * @private
14463 */
14464 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
14465 this.setValue( null );
14466 return false;
14467 };
14468
14469 /**
14470 * Handle key press events.
14471 *
14472 * @private
14473 * @param {jQuery.Event} e Key press event
14474 */
14475 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
14476 if ( this.isSupported && !this.isDisabled() && this.$input &&
14477 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
14478 ) {
14479 this.$input.click();
14480 return false;
14481 }
14482 };
14483
14484 /**
14485 * Handle drop target click events.
14486 *
14487 * @private
14488 * @param {jQuery.Event} e Key press event
14489 */
14490 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14491 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14492 this.$input.click();
14493 return false;
14494 }
14495 };
14496
14497 /**
14498 * Handle drag enter and over events
14499 *
14500 * @private
14501 * @param {jQuery.Event} e Drag event
14502 */
14503 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14504 var itemOrFile,
14505 droppableFile = false,
14506 dt = e.originalEvent.dataTransfer;
14507
14508 e.preventDefault();
14509 e.stopPropagation();
14510
14511 if ( this.isDisabled() || !this.isSupported ) {
14512 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14513 dt.dropEffect = 'none';
14514 return false;
14515 }
14516
14517 // DataTransferItem and File both have a type property, but in Chrome files
14518 // have no information at this point.
14519 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14520 if ( itemOrFile ) {
14521 if ( this.isAllowedType( itemOrFile.type ) ) {
14522 droppableFile = true;
14523 }
14524 // dt.types is Array-like, but not an Array
14525 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14526 // File information is not available at this point for security so just assume
14527 // it is acceptable for now.
14528 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14529 droppableFile = true;
14530 }
14531
14532 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14533 if ( !droppableFile ) {
14534 dt.dropEffect = 'none';
14535 }
14536
14537 return false;
14538 };
14539
14540 /**
14541 * Handle drag leave events
14542 *
14543 * @private
14544 * @param {jQuery.Event} e Drag event
14545 */
14546 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14547 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14548 };
14549
14550 /**
14551 * Handle drop events
14552 *
14553 * @private
14554 * @param {jQuery.Event} e Drop event
14555 */
14556 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14557 var file = null,
14558 dt = e.originalEvent.dataTransfer;
14559
14560 e.preventDefault();
14561 e.stopPropagation();
14562 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14563
14564 if ( this.isDisabled() || !this.isSupported ) {
14565 return false;
14566 }
14567
14568 file = OO.getProp( dt, 'files', 0 );
14569 if ( file && !this.isAllowedType( file.type ) ) {
14570 file = null;
14571 }
14572 if ( file ) {
14573 this.setValue( file );
14574 }
14575
14576 return false;
14577 };
14578
14579 /**
14580 * @inheritdoc
14581 */
14582 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14583 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14584 if ( this.selectButton ) {
14585 this.selectButton.setDisabled( disabled );
14586 }
14587 if ( this.clearButton ) {
14588 this.clearButton.setDisabled( disabled );
14589 }
14590 return this;
14591 };
14592
14593 /**
14594 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14595 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14596 * for a list of icons included in the library.
14597 *
14598 * @example
14599 * // An icon widget with a label
14600 * var myIcon = new OO.ui.IconWidget( {
14601 * icon: 'help',
14602 * iconTitle: 'Help'
14603 * } );
14604 * // Create a label.
14605 * var iconLabel = new OO.ui.LabelWidget( {
14606 * label: 'Help'
14607 * } );
14608 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14609 *
14610 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14611 *
14612 * @class
14613 * @extends OO.ui.Widget
14614 * @mixins OO.ui.mixin.IconElement
14615 * @mixins OO.ui.mixin.TitledElement
14616 * @mixins OO.ui.mixin.FlaggedElement
14617 *
14618 * @constructor
14619 * @param {Object} [config] Configuration options
14620 */
14621 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14622 // Configuration initialization
14623 config = config || {};
14624
14625 // Parent constructor
14626 OO.ui.IconWidget.parent.call( this, config );
14627
14628 // Mixin constructors
14629 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14630 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14631 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14632
14633 // Initialization
14634 this.$element.addClass( 'oo-ui-iconWidget' );
14635 };
14636
14637 /* Setup */
14638
14639 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14640 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14641 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14642 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14643
14644 /* Static Properties */
14645
14646 OO.ui.IconWidget.static.tagName = 'span';
14647
14648 /**
14649 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14650 * attention to the status of an item or to clarify the function of a control. For a list of
14651 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14652 *
14653 * @example
14654 * // Example of an indicator widget
14655 * var indicator1 = new OO.ui.IndicatorWidget( {
14656 * indicator: 'alert'
14657 * } );
14658 *
14659 * // Create a fieldset layout to add a label
14660 * var fieldset = new OO.ui.FieldsetLayout();
14661 * fieldset.addItems( [
14662 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14663 * ] );
14664 * $( 'body' ).append( fieldset.$element );
14665 *
14666 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14667 *
14668 * @class
14669 * @extends OO.ui.Widget
14670 * @mixins OO.ui.mixin.IndicatorElement
14671 * @mixins OO.ui.mixin.TitledElement
14672 *
14673 * @constructor
14674 * @param {Object} [config] Configuration options
14675 */
14676 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14677 // Configuration initialization
14678 config = config || {};
14679
14680 // Parent constructor
14681 OO.ui.IndicatorWidget.parent.call( this, config );
14682
14683 // Mixin constructors
14684 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14685 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14686
14687 // Initialization
14688 this.$element.addClass( 'oo-ui-indicatorWidget' );
14689 };
14690
14691 /* Setup */
14692
14693 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14694 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14695 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14696
14697 /* Static Properties */
14698
14699 OO.ui.IndicatorWidget.static.tagName = 'span';
14700
14701 /**
14702 * InputWidget is the base class for all input widgets, which
14703 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14704 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14705 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14706 *
14707 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14708 *
14709 * @abstract
14710 * @class
14711 * @extends OO.ui.Widget
14712 * @mixins OO.ui.mixin.FlaggedElement
14713 * @mixins OO.ui.mixin.TabIndexedElement
14714 * @mixins OO.ui.mixin.TitledElement
14715 * @mixins OO.ui.mixin.AccessKeyedElement
14716 *
14717 * @constructor
14718 * @param {Object} [config] Configuration options
14719 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14720 * @cfg {string} [value=''] The value of the input.
14721 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
14722 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14723 * before it is accepted.
14724 */
14725 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14726 // Configuration initialization
14727 config = config || {};
14728
14729 // Parent constructor
14730 OO.ui.InputWidget.parent.call( this, config );
14731
14732 // Properties
14733 this.$input = this.getInputElement( config );
14734 this.value = '';
14735 this.inputFilter = config.inputFilter;
14736
14737 // Mixin constructors
14738 OO.ui.mixin.FlaggedElement.call( this, config );
14739 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14740 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14741 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14742
14743 // Events
14744 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14745
14746 // Initialization
14747 this.$input
14748 .addClass( 'oo-ui-inputWidget-input' )
14749 .attr( 'name', config.name )
14750 .prop( 'disabled', this.isDisabled() );
14751 this.$element
14752 .addClass( 'oo-ui-inputWidget' )
14753 .append( this.$input );
14754 this.setValue( config.value );
14755 this.setAccessKey( config.accessKey );
14756 if ( config.dir ) {
14757 this.setDir( config.dir );
14758 }
14759 };
14760
14761 /* Setup */
14762
14763 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14764 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14765 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14766 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14767 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14768
14769 /* Static Properties */
14770
14771 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14772
14773 /* Static Methods */
14774
14775 /**
14776 * @inheritdoc
14777 */
14778 OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) {
14779 config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config );
14780 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
14781 config.$input = $( node ).find( '.oo-ui-inputWidget-input' );
14782 return config;
14783 };
14784
14785 /**
14786 * @inheritdoc
14787 */
14788 OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) {
14789 var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config );
14790 state.value = config.$input.val();
14791 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14792 state.focus = config.$input.is( ':focus' );
14793 return state;
14794 };
14795
14796 /* Events */
14797
14798 /**
14799 * @event change
14800 *
14801 * A change event is emitted when the value of the input changes.
14802 *
14803 * @param {string} value
14804 */
14805
14806 /* Methods */
14807
14808 /**
14809 * Get input element.
14810 *
14811 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14812 * different circumstances. The element must have a `value` property (like form elements).
14813 *
14814 * @protected
14815 * @param {Object} config Configuration options
14816 * @return {jQuery} Input element
14817 */
14818 OO.ui.InputWidget.prototype.getInputElement = function ( config ) {
14819 // See #reusePreInfuseDOM about config.$input
14820 return config.$input || $( '<input>' );
14821 };
14822
14823 /**
14824 * Handle potentially value-changing events.
14825 *
14826 * @private
14827 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14828 */
14829 OO.ui.InputWidget.prototype.onEdit = function () {
14830 var widget = this;
14831 if ( !this.isDisabled() ) {
14832 // Allow the stack to clear so the value will be updated
14833 setTimeout( function () {
14834 widget.setValue( widget.$input.val() );
14835 } );
14836 }
14837 };
14838
14839 /**
14840 * Get the value of the input.
14841 *
14842 * @return {string} Input value
14843 */
14844 OO.ui.InputWidget.prototype.getValue = function () {
14845 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14846 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14847 var value = this.$input.val();
14848 if ( this.value !== value ) {
14849 this.setValue( value );
14850 }
14851 return this.value;
14852 };
14853
14854 /**
14855 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
14856 *
14857 * @deprecated since v0.13.1, use #setDir directly
14858 * @param {boolean} isRTL Directionality is right-to-left
14859 * @chainable
14860 */
14861 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14862 this.setDir( isRTL ? 'rtl' : 'ltr' );
14863 return this;
14864 };
14865
14866 /**
14867 * Set the directionality of the input.
14868 *
14869 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
14870 * @chainable
14871 */
14872 OO.ui.InputWidget.prototype.setDir = function ( dir ) {
14873 this.$input.prop( 'dir', dir );
14874 return this;
14875 };
14876
14877 /**
14878 * Set the value of the input.
14879 *
14880 * @param {string} value New value
14881 * @fires change
14882 * @chainable
14883 */
14884 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14885 value = this.cleanUpValue( value );
14886 // Update the DOM if it has changed. Note that with cleanUpValue, it
14887 // is possible for the DOM value to change without this.value changing.
14888 if ( this.$input.val() !== value ) {
14889 this.$input.val( value );
14890 }
14891 if ( this.value !== value ) {
14892 this.value = value;
14893 this.emit( 'change', this.value );
14894 }
14895 return this;
14896 };
14897
14898 /**
14899 * Set the input's access key.
14900 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14901 *
14902 * @param {string} accessKey Input's access key, use empty string to remove
14903 * @chainable
14904 */
14905 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14906 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14907
14908 if ( this.accessKey !== accessKey ) {
14909 if ( this.$input ) {
14910 if ( accessKey !== null ) {
14911 this.$input.attr( 'accesskey', accessKey );
14912 } else {
14913 this.$input.removeAttr( 'accesskey' );
14914 }
14915 }
14916 this.accessKey = accessKey;
14917 }
14918
14919 return this;
14920 };
14921
14922 /**
14923 * Clean up incoming value.
14924 *
14925 * Ensures value is a string, and converts undefined and null to empty string.
14926 *
14927 * @private
14928 * @param {string} value Original value
14929 * @return {string} Cleaned up value
14930 */
14931 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14932 if ( value === undefined || value === null ) {
14933 return '';
14934 } else if ( this.inputFilter ) {
14935 return this.inputFilter( String( value ) );
14936 } else {
14937 return String( value );
14938 }
14939 };
14940
14941 /**
14942 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14943 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14944 * called directly.
14945 */
14946 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14947 if ( !this.isDisabled() ) {
14948 if ( this.$input.is( ':checkbox, :radio' ) ) {
14949 this.$input.click();
14950 }
14951 if ( this.$input.is( ':input' ) ) {
14952 this.$input[ 0 ].focus();
14953 }
14954 }
14955 };
14956
14957 /**
14958 * @inheritdoc
14959 */
14960 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14961 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14962 if ( this.$input ) {
14963 this.$input.prop( 'disabled', this.isDisabled() );
14964 }
14965 return this;
14966 };
14967
14968 /**
14969 * Focus the input.
14970 *
14971 * @chainable
14972 */
14973 OO.ui.InputWidget.prototype.focus = function () {
14974 this.$input[ 0 ].focus();
14975 return this;
14976 };
14977
14978 /**
14979 * Blur the input.
14980 *
14981 * @chainable
14982 */
14983 OO.ui.InputWidget.prototype.blur = function () {
14984 this.$input[ 0 ].blur();
14985 return this;
14986 };
14987
14988 /**
14989 * @inheritdoc
14990 */
14991 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14992 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14993 if ( state.value !== undefined && state.value !== this.getValue() ) {
14994 this.setValue( state.value );
14995 }
14996 if ( state.focus ) {
14997 this.focus();
14998 }
14999 };
15000
15001 /**
15002 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
15003 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
15004 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
15005 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
15006 * [OOjs UI documentation on MediaWiki] [1] for more information.
15007 *
15008 * @example
15009 * // A ButtonInputWidget rendered as an HTML button, the default.
15010 * var button = new OO.ui.ButtonInputWidget( {
15011 * label: 'Input button',
15012 * icon: 'check',
15013 * value: 'check'
15014 * } );
15015 * $( 'body' ).append( button.$element );
15016 *
15017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
15018 *
15019 * @class
15020 * @extends OO.ui.InputWidget
15021 * @mixins OO.ui.mixin.ButtonElement
15022 * @mixins OO.ui.mixin.IconElement
15023 * @mixins OO.ui.mixin.IndicatorElement
15024 * @mixins OO.ui.mixin.LabelElement
15025 * @mixins OO.ui.mixin.TitledElement
15026 *
15027 * @constructor
15028 * @param {Object} [config] Configuration options
15029 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
15030 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
15031 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
15032 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
15033 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
15034 */
15035 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
15036 // Configuration initialization
15037 config = $.extend( { type: 'button', useInputTag: false }, config );
15038
15039 // Properties (must be set before parent constructor, which calls #setValue)
15040 this.useInputTag = config.useInputTag;
15041
15042 // Parent constructor
15043 OO.ui.ButtonInputWidget.parent.call( this, config );
15044
15045 // Mixin constructors
15046 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
15047 OO.ui.mixin.IconElement.call( this, config );
15048 OO.ui.mixin.IndicatorElement.call( this, config );
15049 OO.ui.mixin.LabelElement.call( this, config );
15050 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
15051
15052 // Initialization
15053 if ( !config.useInputTag ) {
15054 this.$input.append( this.$icon, this.$label, this.$indicator );
15055 }
15056 this.$element.addClass( 'oo-ui-buttonInputWidget' );
15057 };
15058
15059 /* Setup */
15060
15061 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
15062 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
15063 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
15064 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
15065 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
15066 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
15067
15068 /* Static Properties */
15069
15070 /**
15071 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
15072 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
15073 */
15074 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
15075
15076 /* Methods */
15077
15078 /**
15079 * @inheritdoc
15080 * @protected
15081 */
15082 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
15083 var type;
15084 // See InputWidget#reusePreInfuseDOM about config.$input
15085 if ( config.$input ) {
15086 return config.$input.empty();
15087 }
15088 type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button';
15089 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
15090 };
15091
15092 /**
15093 * Set label value.
15094 *
15095 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
15096 *
15097 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
15098 * text, or `null` for no label
15099 * @chainable
15100 */
15101 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
15102 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
15103
15104 if ( this.useInputTag ) {
15105 if ( typeof label === 'function' ) {
15106 label = OO.ui.resolveMsg( label );
15107 }
15108 if ( label instanceof jQuery ) {
15109 label = label.text();
15110 }
15111 if ( !label ) {
15112 label = '';
15113 }
15114 this.$input.val( label );
15115 }
15116
15117 return this;
15118 };
15119
15120 /**
15121 * Set the value of the input.
15122 *
15123 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
15124 * they do not support {@link #value values}.
15125 *
15126 * @param {string} value New value
15127 * @chainable
15128 */
15129 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
15130 if ( !this.useInputTag ) {
15131 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
15132 }
15133 return this;
15134 };
15135
15136 /**
15137 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
15138 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
15139 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
15140 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
15141 *
15142 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15143 *
15144 * @example
15145 * // An example of selected, unselected, and disabled checkbox inputs
15146 * var checkbox1=new OO.ui.CheckboxInputWidget( {
15147 * value: 'a',
15148 * selected: true
15149 * } );
15150 * var checkbox2=new OO.ui.CheckboxInputWidget( {
15151 * value: 'b'
15152 * } );
15153 * var checkbox3=new OO.ui.CheckboxInputWidget( {
15154 * value:'c',
15155 * disabled: true
15156 * } );
15157 * // Create a fieldset layout with fields for each checkbox.
15158 * var fieldset = new OO.ui.FieldsetLayout( {
15159 * label: 'Checkboxes'
15160 * } );
15161 * fieldset.addItems( [
15162 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
15163 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
15164 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
15165 * ] );
15166 * $( 'body' ).append( fieldset.$element );
15167 *
15168 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15169 *
15170 * @class
15171 * @extends OO.ui.InputWidget
15172 *
15173 * @constructor
15174 * @param {Object} [config] Configuration options
15175 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
15176 */
15177 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
15178 // Configuration initialization
15179 config = config || {};
15180
15181 // Parent constructor
15182 OO.ui.CheckboxInputWidget.parent.call( this, config );
15183
15184 // Initialization
15185 this.$element
15186 .addClass( 'oo-ui-checkboxInputWidget' )
15187 // Required for pretty styling in MediaWiki theme
15188 .append( $( '<span>' ) );
15189 this.setSelected( config.selected !== undefined ? config.selected : false );
15190 };
15191
15192 /* Setup */
15193
15194 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
15195
15196 /* Static Methods */
15197
15198 /**
15199 * @inheritdoc
15200 */
15201 OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15202 var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config );
15203 state.checked = config.$input.prop( 'checked' );
15204 return state;
15205 };
15206
15207 /* Methods */
15208
15209 /**
15210 * @inheritdoc
15211 * @protected
15212 */
15213 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
15214 return $( '<input type="checkbox" />' );
15215 };
15216
15217 /**
15218 * @inheritdoc
15219 */
15220 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
15221 var widget = this;
15222 if ( !this.isDisabled() ) {
15223 // Allow the stack to clear so the value will be updated
15224 setTimeout( function () {
15225 widget.setSelected( widget.$input.prop( 'checked' ) );
15226 } );
15227 }
15228 };
15229
15230 /**
15231 * Set selection state of this checkbox.
15232 *
15233 * @param {boolean} state `true` for selected
15234 * @chainable
15235 */
15236 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
15237 state = !!state;
15238 if ( this.selected !== state ) {
15239 this.selected = state;
15240 this.$input.prop( 'checked', this.selected );
15241 this.emit( 'change', this.selected );
15242 }
15243 return this;
15244 };
15245
15246 /**
15247 * Check if this checkbox is selected.
15248 *
15249 * @return {boolean} Checkbox is selected
15250 */
15251 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
15252 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
15253 // it, and we won't know unless they're kind enough to trigger a 'change' event.
15254 var selected = this.$input.prop( 'checked' );
15255 if ( this.selected !== selected ) {
15256 this.setSelected( selected );
15257 }
15258 return this.selected;
15259 };
15260
15261 /**
15262 * @inheritdoc
15263 */
15264 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
15265 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15266 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15267 this.setSelected( state.checked );
15268 }
15269 };
15270
15271 /**
15272 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
15273 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15274 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15275 * more information about input widgets.
15276 *
15277 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
15278 * are no options. If no `value` configuration option is provided, the first option is selected.
15279 * If you need a state representing no value (no option being selected), use a DropdownWidget.
15280 *
15281 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
15282 *
15283 * @example
15284 * // Example: A DropdownInputWidget with three options
15285 * var dropdownInput = new OO.ui.DropdownInputWidget( {
15286 * options: [
15287 * { data: 'a', label: 'First' },
15288 * { data: 'b', label: 'Second'},
15289 * { data: 'c', label: 'Third' }
15290 * ]
15291 * } );
15292 * $( 'body' ).append( dropdownInput.$element );
15293 *
15294 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15295 *
15296 * @class
15297 * @extends OO.ui.InputWidget
15298 * @mixins OO.ui.mixin.TitledElement
15299 *
15300 * @constructor
15301 * @param {Object} [config] Configuration options
15302 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15303 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15304 */
15305 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
15306 // Configuration initialization
15307 config = config || {};
15308
15309 // Properties (must be done before parent constructor which calls #setDisabled)
15310 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
15311
15312 // Parent constructor
15313 OO.ui.DropdownInputWidget.parent.call( this, config );
15314
15315 // Mixin constructors
15316 OO.ui.mixin.TitledElement.call( this, config );
15317
15318 // Events
15319 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
15320
15321 // Initialization
15322 this.setOptions( config.options || [] );
15323 this.$element
15324 .addClass( 'oo-ui-dropdownInputWidget' )
15325 .append( this.dropdownWidget.$element );
15326 };
15327
15328 /* Setup */
15329
15330 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
15331 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
15332
15333 /* Methods */
15334
15335 /**
15336 * @inheritdoc
15337 * @protected
15338 */
15339 OO.ui.DropdownInputWidget.prototype.getInputElement = function ( config ) {
15340 // See InputWidget#reusePreInfuseDOM about config.$input
15341 if ( config.$input ) {
15342 return config.$input.addClass( 'oo-ui-element-hidden' );
15343 }
15344 return $( '<input type="hidden">' );
15345 };
15346
15347 /**
15348 * Handles menu select events.
15349 *
15350 * @private
15351 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15352 */
15353 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
15354 this.setValue( item.getData() );
15355 };
15356
15357 /**
15358 * @inheritdoc
15359 */
15360 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
15361 value = this.cleanUpValue( value );
15362 this.dropdownWidget.getMenu().selectItemByData( value );
15363 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
15364 return this;
15365 };
15366
15367 /**
15368 * @inheritdoc
15369 */
15370 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
15371 this.dropdownWidget.setDisabled( state );
15372 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
15373 return this;
15374 };
15375
15376 /**
15377 * Set the options available for this input.
15378 *
15379 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15380 * @chainable
15381 */
15382 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
15383 var
15384 value = this.getValue(),
15385 widget = this;
15386
15387 // Rebuild the dropdown menu
15388 this.dropdownWidget.getMenu()
15389 .clearItems()
15390 .addItems( options.map( function ( opt ) {
15391 var optValue = widget.cleanUpValue( opt.data );
15392 return new OO.ui.MenuOptionWidget( {
15393 data: optValue,
15394 label: opt.label !== undefined ? opt.label : optValue
15395 } );
15396 } ) );
15397
15398 // Restore the previous value, or reset to something sensible
15399 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
15400 // Previous value is still available, ensure consistency with the dropdown
15401 this.setValue( value );
15402 } else {
15403 // No longer valid, reset
15404 if ( options.length ) {
15405 this.setValue( options[ 0 ].data );
15406 }
15407 }
15408
15409 return this;
15410 };
15411
15412 /**
15413 * @inheritdoc
15414 */
15415 OO.ui.DropdownInputWidget.prototype.focus = function () {
15416 this.dropdownWidget.getMenu().toggle( true );
15417 return this;
15418 };
15419
15420 /**
15421 * @inheritdoc
15422 */
15423 OO.ui.DropdownInputWidget.prototype.blur = function () {
15424 this.dropdownWidget.getMenu().toggle( false );
15425 return this;
15426 };
15427
15428 /**
15429 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15430 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15431 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15432 * please see the [OOjs UI documentation on MediaWiki][1].
15433 *
15434 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15435 *
15436 * @example
15437 * // An example of selected, unselected, and disabled radio inputs
15438 * var radio1 = new OO.ui.RadioInputWidget( {
15439 * value: 'a',
15440 * selected: true
15441 * } );
15442 * var radio2 = new OO.ui.RadioInputWidget( {
15443 * value: 'b'
15444 * } );
15445 * var radio3 = new OO.ui.RadioInputWidget( {
15446 * value: 'c',
15447 * disabled: true
15448 * } );
15449 * // Create a fieldset layout with fields for each radio button.
15450 * var fieldset = new OO.ui.FieldsetLayout( {
15451 * label: 'Radio inputs'
15452 * } );
15453 * fieldset.addItems( [
15454 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15455 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15456 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15457 * ] );
15458 * $( 'body' ).append( fieldset.$element );
15459 *
15460 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15461 *
15462 * @class
15463 * @extends OO.ui.InputWidget
15464 *
15465 * @constructor
15466 * @param {Object} [config] Configuration options
15467 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15468 */
15469 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
15470 // Configuration initialization
15471 config = config || {};
15472
15473 // Parent constructor
15474 OO.ui.RadioInputWidget.parent.call( this, config );
15475
15476 // Initialization
15477 this.$element
15478 .addClass( 'oo-ui-radioInputWidget' )
15479 // Required for pretty styling in MediaWiki theme
15480 .append( $( '<span>' ) );
15481 this.setSelected( config.selected !== undefined ? config.selected : false );
15482 };
15483
15484 /* Setup */
15485
15486 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
15487
15488 /* Static Methods */
15489
15490 /**
15491 * @inheritdoc
15492 */
15493 OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15494 var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config );
15495 state.checked = config.$input.prop( 'checked' );
15496 return state;
15497 };
15498
15499 /* Methods */
15500
15501 /**
15502 * @inheritdoc
15503 * @protected
15504 */
15505 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
15506 return $( '<input type="radio" />' );
15507 };
15508
15509 /**
15510 * @inheritdoc
15511 */
15512 OO.ui.RadioInputWidget.prototype.onEdit = function () {
15513 // RadioInputWidget doesn't track its state.
15514 };
15515
15516 /**
15517 * Set selection state of this radio button.
15518 *
15519 * @param {boolean} state `true` for selected
15520 * @chainable
15521 */
15522 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15523 // RadioInputWidget doesn't track its state.
15524 this.$input.prop( 'checked', state );
15525 return this;
15526 };
15527
15528 /**
15529 * Check if this radio button is selected.
15530 *
15531 * @return {boolean} Radio is selected
15532 */
15533 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15534 return this.$input.prop( 'checked' );
15535 };
15536
15537 /**
15538 * @inheritdoc
15539 */
15540 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15541 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15542 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15543 this.setSelected( state.checked );
15544 }
15545 };
15546
15547 /**
15548 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15549 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15550 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15551 * more information about input widgets.
15552 *
15553 * This and OO.ui.DropdownInputWidget support the same configuration options.
15554 *
15555 * @example
15556 * // Example: A RadioSelectInputWidget with three options
15557 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15558 * options: [
15559 * { data: 'a', label: 'First' },
15560 * { data: 'b', label: 'Second'},
15561 * { data: 'c', label: 'Third' }
15562 * ]
15563 * } );
15564 * $( 'body' ).append( radioSelectInput.$element );
15565 *
15566 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15567 *
15568 * @class
15569 * @extends OO.ui.InputWidget
15570 *
15571 * @constructor
15572 * @param {Object} [config] Configuration options
15573 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15574 */
15575 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15576 // Configuration initialization
15577 config = config || {};
15578
15579 // Properties (must be done before parent constructor which calls #setDisabled)
15580 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15581
15582 // Parent constructor
15583 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15584
15585 // Events
15586 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15587
15588 // Initialization
15589 this.setOptions( config.options || [] );
15590 this.$element
15591 .addClass( 'oo-ui-radioSelectInputWidget' )
15592 .append( this.radioSelectWidget.$element );
15593 };
15594
15595 /* Setup */
15596
15597 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15598
15599 /* Static Properties */
15600
15601 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15602
15603 /* Static Methods */
15604
15605 /**
15606 * @inheritdoc
15607 */
15608 OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15609 var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config );
15610 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15611 return state;
15612 };
15613
15614 /* Methods */
15615
15616 /**
15617 * @inheritdoc
15618 * @protected
15619 */
15620 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15621 return $( '<input type="hidden">' );
15622 };
15623
15624 /**
15625 * Handles menu select events.
15626 *
15627 * @private
15628 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15629 */
15630 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15631 this.setValue( item.getData() );
15632 };
15633
15634 /**
15635 * @inheritdoc
15636 */
15637 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15638 value = this.cleanUpValue( value );
15639 this.radioSelectWidget.selectItemByData( value );
15640 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15641 return this;
15642 };
15643
15644 /**
15645 * @inheritdoc
15646 */
15647 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15648 this.radioSelectWidget.setDisabled( state );
15649 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15650 return this;
15651 };
15652
15653 /**
15654 * Set the options available for this input.
15655 *
15656 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15657 * @chainable
15658 */
15659 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15660 var
15661 value = this.getValue(),
15662 widget = this;
15663
15664 // Rebuild the radioSelect menu
15665 this.radioSelectWidget
15666 .clearItems()
15667 .addItems( options.map( function ( opt ) {
15668 var optValue = widget.cleanUpValue( opt.data );
15669 return new OO.ui.RadioOptionWidget( {
15670 data: optValue,
15671 label: opt.label !== undefined ? opt.label : optValue
15672 } );
15673 } ) );
15674
15675 // Restore the previous value, or reset to something sensible
15676 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15677 // Previous value is still available, ensure consistency with the radioSelect
15678 this.setValue( value );
15679 } else {
15680 // No longer valid, reset
15681 if ( options.length ) {
15682 this.setValue( options[ 0 ].data );
15683 }
15684 }
15685
15686 return this;
15687 };
15688
15689 /**
15690 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15691 * size of the field as well as its presentation. In addition, these widgets can be configured
15692 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15693 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15694 * which modifies incoming values rather than validating them.
15695 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15696 *
15697 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15698 *
15699 * @example
15700 * // Example of a text input widget
15701 * var textInput = new OO.ui.TextInputWidget( {
15702 * value: 'Text input'
15703 * } )
15704 * $( 'body' ).append( textInput.$element );
15705 *
15706 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15707 *
15708 * @class
15709 * @extends OO.ui.InputWidget
15710 * @mixins OO.ui.mixin.IconElement
15711 * @mixins OO.ui.mixin.IndicatorElement
15712 * @mixins OO.ui.mixin.PendingElement
15713 * @mixins OO.ui.mixin.LabelElement
15714 *
15715 * @constructor
15716 * @param {Object} [config] Configuration options
15717 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15718 * 'email' or 'url'. Ignored if `multiline` is true.
15719 *
15720 * Some values of `type` result in additional behaviors:
15721 *
15722 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15723 * empties the text field
15724 * @cfg {string} [placeholder] Placeholder text
15725 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15726 * instruct the browser to focus this widget.
15727 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15728 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15729 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15730 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15731 * specifies minimum number of rows to display.
15732 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15733 * Use the #maxRows config to specify a maximum number of displayed rows.
15734 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15735 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15736 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15737 * the value or placeholder text: `'before'` or `'after'`
15738 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15739 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15740 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15741 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15742 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15743 * value for it to be considered valid; when Function, a function receiving the value as parameter
15744 * that must return true, or promise resolving to true, for it to be considered valid.
15745 */
15746 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15747 // Configuration initialization
15748 config = $.extend( {
15749 type: 'text',
15750 labelPosition: 'after'
15751 }, config );
15752 if ( config.type === 'search' ) {
15753 if ( config.icon === undefined ) {
15754 config.icon = 'search';
15755 }
15756 // indicator: 'clear' is set dynamically later, depending on value
15757 }
15758 if ( config.required ) {
15759 if ( config.indicator === undefined ) {
15760 config.indicator = 'required';
15761 }
15762 }
15763
15764 // Parent constructor
15765 OO.ui.TextInputWidget.parent.call( this, config );
15766
15767 // Mixin constructors
15768 OO.ui.mixin.IconElement.call( this, config );
15769 OO.ui.mixin.IndicatorElement.call( this, config );
15770 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15771 OO.ui.mixin.LabelElement.call( this, config );
15772
15773 // Properties
15774 this.type = this.getSaneType( config );
15775 this.readOnly = false;
15776 this.multiline = !!config.multiline;
15777 this.autosize = !!config.autosize;
15778 this.minRows = config.rows !== undefined ? config.rows : '';
15779 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15780 this.validate = null;
15781 this.styleHeight = null;
15782 this.scrollWidth = null;
15783
15784 // Clone for resizing
15785 if ( this.autosize ) {
15786 this.$clone = this.$input
15787 .clone()
15788 .insertAfter( this.$input )
15789 .attr( 'aria-hidden', 'true' )
15790 .addClass( 'oo-ui-element-hidden' );
15791 }
15792
15793 this.setValidation( config.validate );
15794 this.setLabelPosition( config.labelPosition );
15795
15796 // Events
15797 this.$input.on( {
15798 keypress: this.onKeyPress.bind( this ),
15799 blur: this.onBlur.bind( this )
15800 } );
15801 this.$input.one( {
15802 focus: this.onElementAttach.bind( this )
15803 } );
15804 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15805 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15806 this.on( 'labelChange', this.updatePosition.bind( this ) );
15807 this.connect( this, {
15808 change: 'onChange',
15809 disable: 'onDisable'
15810 } );
15811
15812 // Initialization
15813 this.$element
15814 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15815 .append( this.$icon, this.$indicator );
15816 this.setReadOnly( !!config.readOnly );
15817 this.updateSearchIndicator();
15818 if ( config.placeholder ) {
15819 this.$input.attr( 'placeholder', config.placeholder );
15820 }
15821 if ( config.maxLength !== undefined ) {
15822 this.$input.attr( 'maxlength', config.maxLength );
15823 }
15824 if ( config.autofocus ) {
15825 this.$input.attr( 'autofocus', 'autofocus' );
15826 }
15827 if ( config.required ) {
15828 this.$input.attr( 'required', 'required' );
15829 this.$input.attr( 'aria-required', 'true' );
15830 }
15831 if ( config.autocomplete === false ) {
15832 this.$input.attr( 'autocomplete', 'off' );
15833 // Turning off autocompletion also disables "form caching" when the user navigates to a
15834 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
15835 $( window ).on( {
15836 beforeunload: function () {
15837 this.$input.removeAttr( 'autocomplete' );
15838 }.bind( this ),
15839 pageshow: function () {
15840 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
15841 // whole page... it shouldn't hurt, though.
15842 this.$input.attr( 'autocomplete', 'off' );
15843 }.bind( this )
15844 } );
15845 }
15846 if ( this.multiline && config.rows ) {
15847 this.$input.attr( 'rows', config.rows );
15848 }
15849 if ( this.label || config.autosize ) {
15850 this.installParentChangeDetector();
15851 }
15852 };
15853
15854 /* Setup */
15855
15856 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15857 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15858 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15859 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15860 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15861
15862 /* Static Properties */
15863
15864 OO.ui.TextInputWidget.static.validationPatterns = {
15865 'non-empty': /.+/,
15866 integer: /^\d+$/
15867 };
15868
15869 /* Static Methods */
15870
15871 /**
15872 * @inheritdoc
15873 */
15874 OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) {
15875 var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config );
15876 if ( config.multiline ) {
15877 state.scrollTop = config.$input.scrollTop();
15878 }
15879 return state;
15880 };
15881
15882 /* Events */
15883
15884 /**
15885 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15886 *
15887 * Not emitted if the input is multiline.
15888 *
15889 * @event enter
15890 */
15891
15892 /**
15893 * A `resize` event is emitted when autosize is set and the widget resizes
15894 *
15895 * @event resize
15896 */
15897
15898 /* Methods */
15899
15900 /**
15901 * Handle icon mouse down events.
15902 *
15903 * @private
15904 * @param {jQuery.Event} e Mouse down event
15905 * @fires icon
15906 */
15907 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15908 if ( e.which === 1 ) {
15909 this.$input[ 0 ].focus();
15910 return false;
15911 }
15912 };
15913
15914 /**
15915 * Handle indicator mouse down events.
15916 *
15917 * @private
15918 * @param {jQuery.Event} e Mouse down event
15919 * @fires indicator
15920 */
15921 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15922 if ( e.which === 1 ) {
15923 if ( this.type === 'search' ) {
15924 // Clear the text field
15925 this.setValue( '' );
15926 }
15927 this.$input[ 0 ].focus();
15928 return false;
15929 }
15930 };
15931
15932 /**
15933 * Handle key press events.
15934 *
15935 * @private
15936 * @param {jQuery.Event} e Key press event
15937 * @fires enter If enter key is pressed and input is not multiline
15938 */
15939 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15940 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15941 this.emit( 'enter', e );
15942 }
15943 };
15944
15945 /**
15946 * Handle blur events.
15947 *
15948 * @private
15949 * @param {jQuery.Event} e Blur event
15950 */
15951 OO.ui.TextInputWidget.prototype.onBlur = function () {
15952 this.setValidityFlag();
15953 };
15954
15955 /**
15956 * Handle element attach events.
15957 *
15958 * @private
15959 * @param {jQuery.Event} e Element attach event
15960 */
15961 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15962 // Any previously calculated size is now probably invalid if we reattached elsewhere
15963 this.valCache = null;
15964 this.adjustSize();
15965 this.positionLabel();
15966 };
15967
15968 /**
15969 * Handle change events.
15970 *
15971 * @param {string} value
15972 * @private
15973 */
15974 OO.ui.TextInputWidget.prototype.onChange = function () {
15975 this.updateSearchIndicator();
15976 this.setValidityFlag();
15977 this.adjustSize();
15978 };
15979
15980 /**
15981 * Handle disable events.
15982 *
15983 * @param {boolean} disabled Element is disabled
15984 * @private
15985 */
15986 OO.ui.TextInputWidget.prototype.onDisable = function () {
15987 this.updateSearchIndicator();
15988 };
15989
15990 /**
15991 * Check if the input is {@link #readOnly read-only}.
15992 *
15993 * @return {boolean}
15994 */
15995 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15996 return this.readOnly;
15997 };
15998
15999 /**
16000 * Set the {@link #readOnly read-only} state of the input.
16001 *
16002 * @param {boolean} state Make input read-only
16003 * @chainable
16004 */
16005 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
16006 this.readOnly = !!state;
16007 this.$input.prop( 'readOnly', this.readOnly );
16008 this.updateSearchIndicator();
16009 return this;
16010 };
16011
16012 /**
16013 * Support function for making #onElementAttach work across browsers.
16014 *
16015 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
16016 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
16017 *
16018 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
16019 * first time that the element gets attached to the documented.
16020 */
16021 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
16022 var mutationObserver, onRemove, topmostNode, fakeParentNode,
16023 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
16024 widget = this;
16025
16026 if ( MutationObserver ) {
16027 // The new way. If only it wasn't so ugly.
16028
16029 if ( this.$element.closest( 'html' ).length ) {
16030 // Widget is attached already, do nothing. This breaks the functionality of this function when
16031 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
16032 // would require observation of the whole document, which would hurt performance of other,
16033 // more important code.
16034 return;
16035 }
16036
16037 // Find topmost node in the tree
16038 topmostNode = this.$element[ 0 ];
16039 while ( topmostNode.parentNode ) {
16040 topmostNode = topmostNode.parentNode;
16041 }
16042
16043 // We have no way to detect the $element being attached somewhere without observing the entire
16044 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
16045 // parent node of $element, and instead detect when $element is removed from it (and thus
16046 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
16047 // doesn't get attached, we end up back here and create the parent.
16048
16049 mutationObserver = new MutationObserver( function ( mutations ) {
16050 var i, j, removedNodes;
16051 for ( i = 0; i < mutations.length; i++ ) {
16052 removedNodes = mutations[ i ].removedNodes;
16053 for ( j = 0; j < removedNodes.length; j++ ) {
16054 if ( removedNodes[ j ] === topmostNode ) {
16055 setTimeout( onRemove, 0 );
16056 return;
16057 }
16058 }
16059 }
16060 } );
16061
16062 onRemove = function () {
16063 // If the node was attached somewhere else, report it
16064 if ( widget.$element.closest( 'html' ).length ) {
16065 widget.onElementAttach();
16066 }
16067 mutationObserver.disconnect();
16068 widget.installParentChangeDetector();
16069 };
16070
16071 // Create a fake parent and observe it
16072 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
16073 mutationObserver.observe( fakeParentNode, { childList: true } );
16074 } else {
16075 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
16076 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
16077 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
16078 }
16079 };
16080
16081 /**
16082 * Automatically adjust the size of the text input.
16083 *
16084 * This only affects #multiline inputs that are {@link #autosize autosized}.
16085 *
16086 * @chainable
16087 * @fires resize
16088 */
16089 OO.ui.TextInputWidget.prototype.adjustSize = function () {
16090 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError,
16091 idealHeight, newHeight, scrollWidth, property;
16092
16093 if ( this.multiline && this.$input.val() !== this.valCache ) {
16094 if ( this.autosize ) {
16095 this.$clone
16096 .val( this.$input.val() )
16097 .attr( 'rows', this.minRows )
16098 // Set inline height property to 0 to measure scroll height
16099 .css( 'height', 0 );
16100
16101 this.$clone.removeClass( 'oo-ui-element-hidden' );
16102
16103 this.valCache = this.$input.val();
16104
16105 scrollHeight = this.$clone[ 0 ].scrollHeight;
16106
16107 // Remove inline height property to measure natural heights
16108 this.$clone.css( 'height', '' );
16109 innerHeight = this.$clone.innerHeight();
16110 outerHeight = this.$clone.outerHeight();
16111
16112 // Measure max rows height
16113 this.$clone
16114 .attr( 'rows', this.maxRows )
16115 .css( 'height', 'auto' )
16116 .val( '' );
16117 maxInnerHeight = this.$clone.innerHeight();
16118
16119 // Difference between reported innerHeight and scrollHeight with no scrollbars present
16120 // Equals 1 on Blink-based browsers and 0 everywhere else
16121 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
16122 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
16123
16124 this.$clone.addClass( 'oo-ui-element-hidden' );
16125
16126 // Only apply inline height when expansion beyond natural height is needed
16127 // Use the difference between the inner and outer height as a buffer
16128 newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : '';
16129 if ( newHeight !== this.styleHeight ) {
16130 this.$input.css( 'height', newHeight );
16131 this.styleHeight = newHeight;
16132 this.emit( 'resize' );
16133 }
16134 }
16135 scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth;
16136 if ( scrollWidth !== this.scrollWidth ) {
16137 property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right';
16138 // Reset
16139 this.$label.css( { right: '', left: '' } );
16140 this.$indicator.css( { right: '', left: '' } );
16141
16142 if ( scrollWidth ) {
16143 this.$indicator.css( property, scrollWidth );
16144 if ( this.labelPosition === 'after' ) {
16145 this.$label.css( property, scrollWidth );
16146 }
16147 }
16148
16149 this.scrollWidth = scrollWidth;
16150 this.positionLabel();
16151 }
16152 }
16153 return this;
16154 };
16155
16156 /**
16157 * @inheritdoc
16158 * @protected
16159 */
16160 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
16161 return config.multiline ?
16162 $( '<textarea>' ) :
16163 $( '<input type="' + this.getSaneType( config ) + '" />' );
16164 };
16165
16166 /**
16167 * Get sanitized value for 'type' for given config.
16168 *
16169 * @param {Object} config Configuration options
16170 * @return {string|null}
16171 * @private
16172 */
16173 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
16174 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
16175 config.type :
16176 'text';
16177 return config.multiline ? 'multiline' : type;
16178 };
16179
16180 /**
16181 * Check if the input supports multiple lines.
16182 *
16183 * @return {boolean}
16184 */
16185 OO.ui.TextInputWidget.prototype.isMultiline = function () {
16186 return !!this.multiline;
16187 };
16188
16189 /**
16190 * Check if the input automatically adjusts its size.
16191 *
16192 * @return {boolean}
16193 */
16194 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
16195 return !!this.autosize;
16196 };
16197
16198 /**
16199 * Focus the input and select a specified range within the text.
16200 *
16201 * @param {number} from Select from offset
16202 * @param {number} [to] Select to offset, defaults to from
16203 * @chainable
16204 */
16205 OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) {
16206 var textRange, isBackwards, start, end,
16207 input = this.$input[ 0 ];
16208
16209 to = to || from;
16210
16211 isBackwards = to < from;
16212 start = isBackwards ? to : from;
16213 end = isBackwards ? from : to;
16214
16215 this.focus();
16216
16217 if ( input.setSelectionRange ) {
16218 input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' );
16219 } else if ( input.createTextRange ) {
16220 // IE 8 and below
16221 textRange = input.createTextRange();
16222 textRange.collapse( true );
16223 textRange.moveStart( 'character', start );
16224 textRange.moveEnd( 'character', end - start );
16225 textRange.select();
16226 }
16227 return this;
16228 };
16229
16230 /**
16231 * Get an object describing the current selection range in a directional manner
16232 *
16233 * @return {Object} Object containing 'from' and 'to' offsets
16234 */
16235 OO.ui.TextInputWidget.prototype.getRange = function () {
16236 var input = this.$input[ 0 ],
16237 start = input.selectionStart,
16238 end = input.selectionEnd,
16239 isBackwards = input.selectionDirection === 'backward';
16240
16241 return {
16242 from: isBackwards ? end : start,
16243 to: isBackwards ? start : end
16244 };
16245 };
16246
16247 /**
16248 * Get the length of the text input value.
16249 *
16250 * This could differ from the length of #getValue if the
16251 * value gets filtered
16252 *
16253 * @return {number} Input length
16254 */
16255 OO.ui.TextInputWidget.prototype.getInputLength = function () {
16256 return this.$input[ 0 ].value.length;
16257 };
16258
16259 /**
16260 * Focus the input and select the entire text.
16261 *
16262 * @chainable
16263 */
16264 OO.ui.TextInputWidget.prototype.select = function () {
16265 return this.selectRange( 0, this.getInputLength() );
16266 };
16267
16268 /**
16269 * Focus the input and move the cursor to the start.
16270 *
16271 * @chainable
16272 */
16273 OO.ui.TextInputWidget.prototype.moveCursorToStart = function () {
16274 return this.selectRange( 0 );
16275 };
16276
16277 /**
16278 * Focus the input and move the cursor to the end.
16279 *
16280 * @chainable
16281 */
16282 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
16283 return this.selectRange( this.getInputLength() );
16284 };
16285
16286 /**
16287 * Insert new content into the input.
16288 *
16289 * @param {string} content Content to be inserted
16290 * @chainable
16291 */
16292 OO.ui.TextInputWidget.prototype.insertContent = function ( content ) {
16293 var start, end,
16294 range = this.getRange(),
16295 value = this.getValue();
16296
16297 start = Math.min( range.from, range.to );
16298 end = Math.max( range.from, range.to );
16299
16300 this.setValue( value.slice( 0, start ) + content + value.slice( end ) );
16301 this.selectRange( start + content.length );
16302 return this;
16303 };
16304
16305 /**
16306 * Insert new content either side of a selection.
16307 *
16308 * @param {string} pre Content to be inserted before the selection
16309 * @param {string} post Content to be inserted after the selection
16310 * @chainable
16311 */
16312 OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) {
16313 var start, end,
16314 range = this.getRange(),
16315 offset = pre.length;
16316
16317 start = Math.min( range.from, range.to );
16318 end = Math.max( range.from, range.to );
16319
16320 this.selectRange( start ).insertContent( pre );
16321 this.selectRange( offset + end ).insertContent( post );
16322
16323 this.selectRange( offset + start, offset + end );
16324 return this;
16325 };
16326
16327 /**
16328 * Set the validation pattern.
16329 *
16330 * The validation pattern is either a regular expression, a function, or the symbolic name of a
16331 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
16332 * value must contain only numbers).
16333 *
16334 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
16335 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
16336 */
16337 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
16338 if ( validate instanceof RegExp || validate instanceof Function ) {
16339 this.validate = validate;
16340 } else {
16341 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
16342 }
16343 };
16344
16345 /**
16346 * Sets the 'invalid' flag appropriately.
16347 *
16348 * @param {boolean} [isValid] Optionally override validation result
16349 */
16350 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
16351 var widget = this,
16352 setFlag = function ( valid ) {
16353 if ( !valid ) {
16354 widget.$input.attr( 'aria-invalid', 'true' );
16355 } else {
16356 widget.$input.removeAttr( 'aria-invalid' );
16357 }
16358 widget.setFlags( { invalid: !valid } );
16359 };
16360
16361 if ( isValid !== undefined ) {
16362 setFlag( isValid );
16363 } else {
16364 this.getValidity().then( function () {
16365 setFlag( true );
16366 }, function () {
16367 setFlag( false );
16368 } );
16369 }
16370 };
16371
16372 /**
16373 * Check if a value is valid.
16374 *
16375 * This method returns a promise that resolves with a boolean `true` if the current value is
16376 * considered valid according to the supplied {@link #validate validation pattern}.
16377 *
16378 * @deprecated
16379 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
16380 */
16381 OO.ui.TextInputWidget.prototype.isValid = function () {
16382 var result;
16383
16384 if ( this.validate instanceof Function ) {
16385 result = this.validate( this.getValue() );
16386 if ( $.isFunction( result.promise ) ) {
16387 return result.promise();
16388 } else {
16389 return $.Deferred().resolve( !!result ).promise();
16390 }
16391 } else {
16392 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
16393 }
16394 };
16395
16396 /**
16397 * Get the validity of current value.
16398 *
16399 * This method returns a promise that resolves if the value is valid and rejects if
16400 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
16401 *
16402 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
16403 */
16404 OO.ui.TextInputWidget.prototype.getValidity = function () {
16405 var result, promise;
16406
16407 function rejectOrResolve( valid ) {
16408 if ( valid ) {
16409 return $.Deferred().resolve().promise();
16410 } else {
16411 return $.Deferred().reject().promise();
16412 }
16413 }
16414
16415 if ( this.validate instanceof Function ) {
16416 result = this.validate( this.getValue() );
16417
16418 if ( $.isFunction( result.promise ) ) {
16419 promise = $.Deferred();
16420
16421 result.then( function ( valid ) {
16422 if ( valid ) {
16423 promise.resolve();
16424 } else {
16425 promise.reject();
16426 }
16427 }, function () {
16428 promise.reject();
16429 } );
16430
16431 return promise.promise();
16432 } else {
16433 return rejectOrResolve( result );
16434 }
16435 } else {
16436 return rejectOrResolve( this.getValue().match( this.validate ) );
16437 }
16438 };
16439
16440 /**
16441 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
16442 *
16443 * @param {string} labelPosition Label position, 'before' or 'after'
16444 * @chainable
16445 */
16446 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
16447 this.labelPosition = labelPosition;
16448 this.updatePosition();
16449 return this;
16450 };
16451
16452 /**
16453 * Update the position of the inline label.
16454 *
16455 * This method is called by #setLabelPosition, and can also be called on its own if
16456 * something causes the label to be mispositioned.
16457 *
16458 * @chainable
16459 */
16460 OO.ui.TextInputWidget.prototype.updatePosition = function () {
16461 var after = this.labelPosition === 'after';
16462
16463 this.$element
16464 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
16465 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
16466
16467 this.valCache = null;
16468 this.scrollWidth = null;
16469 this.adjustSize();
16470 this.positionLabel();
16471
16472 return this;
16473 };
16474
16475 /**
16476 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16477 * already empty or when it's not editable.
16478 */
16479 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
16480 if ( this.type === 'search' ) {
16481 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16482 this.setIndicator( null );
16483 } else {
16484 this.setIndicator( 'clear' );
16485 }
16486 }
16487 };
16488
16489 /**
16490 * Position the label by setting the correct padding on the input.
16491 *
16492 * @private
16493 * @chainable
16494 */
16495 OO.ui.TextInputWidget.prototype.positionLabel = function () {
16496 var after, rtl, property;
16497 // Clear old values
16498 this.$input
16499 // Clear old values if present
16500 .css( {
16501 'padding-right': '',
16502 'padding-left': ''
16503 } );
16504
16505 if ( this.label ) {
16506 this.$element.append( this.$label );
16507 } else {
16508 this.$label.detach();
16509 return;
16510 }
16511
16512 after = this.labelPosition === 'after';
16513 rtl = this.$element.css( 'direction' ) === 'rtl';
16514 property = after === rtl ? 'padding-left' : 'padding-right';
16515
16516 this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) );
16517
16518 return this;
16519 };
16520
16521 /**
16522 * @inheritdoc
16523 */
16524 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
16525 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
16526 if ( state.scrollTop !== undefined ) {
16527 this.$input.scrollTop( state.scrollTop );
16528 }
16529 };
16530
16531 /**
16532 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16533 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16534 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16535 *
16536 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16537 * option, that option will appear to be selected.
16538 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16539 * input field.
16540 *
16541 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
16542 *
16543 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16544 *
16545 * @example
16546 * // Example: A ComboBoxInputWidget.
16547 * var comboBox = new OO.ui.ComboBoxInputWidget( {
16548 * label: 'ComboBoxInputWidget',
16549 * value: 'Option 1',
16550 * menu: {
16551 * items: [
16552 * new OO.ui.MenuOptionWidget( {
16553 * data: 'Option 1',
16554 * label: 'Option One'
16555 * } ),
16556 * new OO.ui.MenuOptionWidget( {
16557 * data: 'Option 2',
16558 * label: 'Option Two'
16559 * } ),
16560 * new OO.ui.MenuOptionWidget( {
16561 * data: 'Option 3',
16562 * label: 'Option Three'
16563 * } ),
16564 * new OO.ui.MenuOptionWidget( {
16565 * data: 'Option 4',
16566 * label: 'Option Four'
16567 * } ),
16568 * new OO.ui.MenuOptionWidget( {
16569 * data: 'Option 5',
16570 * label: 'Option Five'
16571 * } )
16572 * ]
16573 * }
16574 * } );
16575 * $( 'body' ).append( comboBox.$element );
16576 *
16577 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16578 *
16579 * @class
16580 * @extends OO.ui.TextInputWidget
16581 *
16582 * @constructor
16583 * @param {Object} [config] Configuration options
16584 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
16585 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16586 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16587 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16588 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16589 */
16590 OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) {
16591 // Configuration initialization
16592 config = $.extend( {
16593 indicator: 'down'
16594 }, config );
16595 // For backwards-compatibility with ComboBoxWidget config
16596 $.extend( config, config.input );
16597
16598 // Parent constructor
16599 OO.ui.ComboBoxInputWidget.parent.call( this, config );
16600
16601 // Properties
16602 this.$overlay = config.$overlay || this.$element;
16603 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
16604 {
16605 widget: this,
16606 input: this,
16607 $container: this.$element,
16608 disabled: this.isDisabled()
16609 },
16610 config.menu
16611 ) );
16612 // For backwards-compatibility with ComboBoxWidget
16613 this.input = this;
16614
16615 // Events
16616 this.$indicator.on( {
16617 click: this.onIndicatorClick.bind( this ),
16618 keypress: this.onIndicatorKeyPress.bind( this )
16619 } );
16620 this.connect( this, {
16621 change: 'onInputChange',
16622 enter: 'onInputEnter'
16623 } );
16624 this.menu.connect( this, {
16625 choose: 'onMenuChoose',
16626 add: 'onMenuItemsChange',
16627 remove: 'onMenuItemsChange'
16628 } );
16629
16630 // Initialization
16631 this.$input.attr( {
16632 role: 'combobox',
16633 'aria-autocomplete': 'list'
16634 } );
16635 // Do not override options set via config.menu.items
16636 if ( config.options !== undefined ) {
16637 this.setOptions( config.options );
16638 }
16639 // Extra class for backwards-compatibility with ComboBoxWidget
16640 this.$element.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
16641 this.$overlay.append( this.menu.$element );
16642 this.onMenuItemsChange();
16643 };
16644
16645 /* Setup */
16646
16647 OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget );
16648
16649 /* Methods */
16650
16651 /**
16652 * Get the combobox's menu.
16653 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16654 */
16655 OO.ui.ComboBoxInputWidget.prototype.getMenu = function () {
16656 return this.menu;
16657 };
16658
16659 /**
16660 * Get the combobox's text input widget.
16661 * @return {OO.ui.TextInputWidget} Text input widget
16662 */
16663 OO.ui.ComboBoxInputWidget.prototype.getInput = function () {
16664 return this;
16665 };
16666
16667 /**
16668 * Handle input change events.
16669 *
16670 * @private
16671 * @param {string} value New value
16672 */
16673 OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) {
16674 var match = this.menu.getItemFromData( value );
16675
16676 this.menu.selectItem( match );
16677 if ( this.menu.getHighlightedItem() ) {
16678 this.menu.highlightItem( match );
16679 }
16680
16681 if ( !this.isDisabled() ) {
16682 this.menu.toggle( true );
16683 }
16684 };
16685
16686 /**
16687 * Handle mouse click events.
16688 *
16689 * @private
16690 * @param {jQuery.Event} e Mouse click event
16691 */
16692 OO.ui.ComboBoxInputWidget.prototype.onIndicatorClick = function ( e ) {
16693 if ( !this.isDisabled() && e.which === 1 ) {
16694 this.menu.toggle();
16695 this.$input[ 0 ].focus();
16696 }
16697 return false;
16698 };
16699
16700 /**
16701 * Handle key press events.
16702 *
16703 * @private
16704 * @param {jQuery.Event} e Key press event
16705 */
16706 OO.ui.ComboBoxInputWidget.prototype.onIndicatorKeyPress = function ( e ) {
16707 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16708 this.menu.toggle();
16709 this.$input[ 0 ].focus();
16710 return false;
16711 }
16712 };
16713
16714 /**
16715 * Handle input enter events.
16716 *
16717 * @private
16718 */
16719 OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () {
16720 if ( !this.isDisabled() ) {
16721 this.menu.toggle( false );
16722 }
16723 };
16724
16725 /**
16726 * Handle menu choose events.
16727 *
16728 * @private
16729 * @param {OO.ui.OptionWidget} item Chosen item
16730 */
16731 OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) {
16732 this.setValue( item.getData() );
16733 };
16734
16735 /**
16736 * Handle menu item change events.
16737 *
16738 * @private
16739 */
16740 OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () {
16741 var match = this.menu.getItemFromData( this.getValue() );
16742 this.menu.selectItem( match );
16743 if ( this.menu.getHighlightedItem() ) {
16744 this.menu.highlightItem( match );
16745 }
16746 this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() );
16747 };
16748
16749 /**
16750 * @inheritdoc
16751 */
16752 OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) {
16753 // Parent method
16754 OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled );
16755
16756 if ( this.menu ) {
16757 this.menu.setDisabled( this.isDisabled() );
16758 }
16759
16760 return this;
16761 };
16762
16763 /**
16764 * Set the options available for this input.
16765 *
16766 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
16767 * @chainable
16768 */
16769 OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) {
16770 this.getMenu()
16771 .clearItems()
16772 .addItems( options.map( function ( opt ) {
16773 return new OO.ui.MenuOptionWidget( {
16774 data: opt.data,
16775 label: opt.label !== undefined ? opt.label : opt.data
16776 } );
16777 } ) );
16778
16779 return this;
16780 };
16781
16782 /**
16783 * @class
16784 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
16785 */
16786 OO.ui.ComboBoxWidget = OO.ui.ComboBoxInputWidget;
16787
16788 /**
16789 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16790 * be configured with a `label` option that is set to a string, a label node, or a function:
16791 *
16792 * - String: a plaintext string
16793 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16794 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16795 * - Function: a function that will produce a string in the future. Functions are used
16796 * in cases where the value of the label is not currently defined.
16797 *
16798 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16799 * will come into focus when the label is clicked.
16800 *
16801 * @example
16802 * // Examples of LabelWidgets
16803 * var label1 = new OO.ui.LabelWidget( {
16804 * label: 'plaintext label'
16805 * } );
16806 * var label2 = new OO.ui.LabelWidget( {
16807 * label: $( '<a href="default.html">jQuery label</a>' )
16808 * } );
16809 * // Create a fieldset layout with fields for each example
16810 * var fieldset = new OO.ui.FieldsetLayout();
16811 * fieldset.addItems( [
16812 * new OO.ui.FieldLayout( label1 ),
16813 * new OO.ui.FieldLayout( label2 )
16814 * ] );
16815 * $( 'body' ).append( fieldset.$element );
16816 *
16817 * @class
16818 * @extends OO.ui.Widget
16819 * @mixins OO.ui.mixin.LabelElement
16820 *
16821 * @constructor
16822 * @param {Object} [config] Configuration options
16823 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16824 * Clicking the label will focus the specified input field.
16825 */
16826 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16827 // Configuration initialization
16828 config = config || {};
16829
16830 // Parent constructor
16831 OO.ui.LabelWidget.parent.call( this, config );
16832
16833 // Mixin constructors
16834 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16835 OO.ui.mixin.TitledElement.call( this, config );
16836
16837 // Properties
16838 this.input = config.input;
16839
16840 // Events
16841 if ( this.input instanceof OO.ui.InputWidget ) {
16842 this.$element.on( 'click', this.onClick.bind( this ) );
16843 }
16844
16845 // Initialization
16846 this.$element.addClass( 'oo-ui-labelWidget' );
16847 };
16848
16849 /* Setup */
16850
16851 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16852 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16853 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16854
16855 /* Static Properties */
16856
16857 OO.ui.LabelWidget.static.tagName = 'span';
16858
16859 /* Methods */
16860
16861 /**
16862 * Handles label mouse click events.
16863 *
16864 * @private
16865 * @param {jQuery.Event} e Mouse click event
16866 */
16867 OO.ui.LabelWidget.prototype.onClick = function () {
16868 this.input.simulateLabelClick();
16869 return false;
16870 };
16871
16872 /**
16873 * OptionWidgets are special elements that can be selected and configured with data. The
16874 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16875 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16876 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16877 *
16878 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16879 *
16880 * @class
16881 * @extends OO.ui.Widget
16882 * @mixins OO.ui.mixin.LabelElement
16883 * @mixins OO.ui.mixin.FlaggedElement
16884 *
16885 * @constructor
16886 * @param {Object} [config] Configuration options
16887 */
16888 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16889 // Configuration initialization
16890 config = config || {};
16891
16892 // Parent constructor
16893 OO.ui.OptionWidget.parent.call( this, config );
16894
16895 // Mixin constructors
16896 OO.ui.mixin.ItemWidget.call( this );
16897 OO.ui.mixin.LabelElement.call( this, config );
16898 OO.ui.mixin.FlaggedElement.call( this, config );
16899
16900 // Properties
16901 this.selected = false;
16902 this.highlighted = false;
16903 this.pressed = false;
16904
16905 // Initialization
16906 this.$element
16907 .data( 'oo-ui-optionWidget', this )
16908 .attr( 'role', 'option' )
16909 .attr( 'aria-selected', 'false' )
16910 .addClass( 'oo-ui-optionWidget' )
16911 .append( this.$label );
16912 };
16913
16914 /* Setup */
16915
16916 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16917 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16918 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16919 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16920
16921 /* Static Properties */
16922
16923 OO.ui.OptionWidget.static.selectable = true;
16924
16925 OO.ui.OptionWidget.static.highlightable = true;
16926
16927 OO.ui.OptionWidget.static.pressable = true;
16928
16929 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16930
16931 /* Methods */
16932
16933 /**
16934 * Check if the option can be selected.
16935 *
16936 * @return {boolean} Item is selectable
16937 */
16938 OO.ui.OptionWidget.prototype.isSelectable = function () {
16939 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16940 };
16941
16942 /**
16943 * Check if the option can be highlighted. A highlight indicates that the option
16944 * may be selected when a user presses enter or clicks. Disabled items cannot
16945 * be highlighted.
16946 *
16947 * @return {boolean} Item is highlightable
16948 */
16949 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16950 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16951 };
16952
16953 /**
16954 * Check if the option can be pressed. The pressed state occurs when a user mouses
16955 * down on an item, but has not yet let go of the mouse.
16956 *
16957 * @return {boolean} Item is pressable
16958 */
16959 OO.ui.OptionWidget.prototype.isPressable = function () {
16960 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16961 };
16962
16963 /**
16964 * Check if the option is selected.
16965 *
16966 * @return {boolean} Item is selected
16967 */
16968 OO.ui.OptionWidget.prototype.isSelected = function () {
16969 return this.selected;
16970 };
16971
16972 /**
16973 * Check if the option is highlighted. A highlight indicates that the
16974 * item may be selected when a user presses enter or clicks.
16975 *
16976 * @return {boolean} Item is highlighted
16977 */
16978 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16979 return this.highlighted;
16980 };
16981
16982 /**
16983 * Check if the option is pressed. The pressed state occurs when a user mouses
16984 * down on an item, but has not yet let go of the mouse. The item may appear
16985 * selected, but it will not be selected until the user releases the mouse.
16986 *
16987 * @return {boolean} Item is pressed
16988 */
16989 OO.ui.OptionWidget.prototype.isPressed = function () {
16990 return this.pressed;
16991 };
16992
16993 /**
16994 * Set the option’s selected state. In general, all modifications to the selection
16995 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16996 * method instead of this method.
16997 *
16998 * @param {boolean} [state=false] Select option
16999 * @chainable
17000 */
17001 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
17002 if ( this.constructor.static.selectable ) {
17003 this.selected = !!state;
17004 this.$element
17005 .toggleClass( 'oo-ui-optionWidget-selected', state )
17006 .attr( 'aria-selected', state.toString() );
17007 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
17008 this.scrollElementIntoView();
17009 }
17010 this.updateThemeClasses();
17011 }
17012 return this;
17013 };
17014
17015 /**
17016 * Set the option’s highlighted state. In general, all programmatic
17017 * modifications to the highlight should be handled by the
17018 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
17019 * method instead of this method.
17020 *
17021 * @param {boolean} [state=false] Highlight option
17022 * @chainable
17023 */
17024 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
17025 if ( this.constructor.static.highlightable ) {
17026 this.highlighted = !!state;
17027 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
17028 this.updateThemeClasses();
17029 }
17030 return this;
17031 };
17032
17033 /**
17034 * Set the option’s pressed state. In general, all
17035 * programmatic modifications to the pressed state should be handled by the
17036 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
17037 * method instead of this method.
17038 *
17039 * @param {boolean} [state=false] Press option
17040 * @chainable
17041 */
17042 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
17043 if ( this.constructor.static.pressable ) {
17044 this.pressed = !!state;
17045 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
17046 this.updateThemeClasses();
17047 }
17048 return this;
17049 };
17050
17051 /**
17052 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
17053 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
17054 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
17055 * options. For more information about options and selects, please see the
17056 * [OOjs UI documentation on MediaWiki][1].
17057 *
17058 * @example
17059 * // Decorated options in a select widget
17060 * var select = new OO.ui.SelectWidget( {
17061 * items: [
17062 * new OO.ui.DecoratedOptionWidget( {
17063 * data: 'a',
17064 * label: 'Option with icon',
17065 * icon: 'help'
17066 * } ),
17067 * new OO.ui.DecoratedOptionWidget( {
17068 * data: 'b',
17069 * label: 'Option with indicator',
17070 * indicator: 'next'
17071 * } )
17072 * ]
17073 * } );
17074 * $( 'body' ).append( select.$element );
17075 *
17076 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17077 *
17078 * @class
17079 * @extends OO.ui.OptionWidget
17080 * @mixins OO.ui.mixin.IconElement
17081 * @mixins OO.ui.mixin.IndicatorElement
17082 *
17083 * @constructor
17084 * @param {Object} [config] Configuration options
17085 */
17086 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
17087 // Parent constructor
17088 OO.ui.DecoratedOptionWidget.parent.call( this, config );
17089
17090 // Mixin constructors
17091 OO.ui.mixin.IconElement.call( this, config );
17092 OO.ui.mixin.IndicatorElement.call( this, config );
17093
17094 // Initialization
17095 this.$element
17096 .addClass( 'oo-ui-decoratedOptionWidget' )
17097 .prepend( this.$icon )
17098 .append( this.$indicator );
17099 };
17100
17101 /* Setup */
17102
17103 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
17104 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
17105 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
17106
17107 /**
17108 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
17109 * can be selected and configured with data. The class is
17110 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
17111 * [OOjs UI documentation on MediaWiki] [1] for more information.
17112 *
17113 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
17114 *
17115 * @class
17116 * @extends OO.ui.DecoratedOptionWidget
17117 * @mixins OO.ui.mixin.ButtonElement
17118 * @mixins OO.ui.mixin.TabIndexedElement
17119 * @mixins OO.ui.mixin.TitledElement
17120 *
17121 * @constructor
17122 * @param {Object} [config] Configuration options
17123 */
17124 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
17125 // Configuration initialization
17126 config = config || {};
17127
17128 // Parent constructor
17129 OO.ui.ButtonOptionWidget.parent.call( this, config );
17130
17131 // Mixin constructors
17132 OO.ui.mixin.ButtonElement.call( this, config );
17133 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
17134 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
17135 $tabIndexed: this.$button,
17136 tabIndex: -1
17137 } ) );
17138
17139 // Initialization
17140 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
17141 this.$button.append( this.$element.contents() );
17142 this.$element.append( this.$button );
17143 };
17144
17145 /* Setup */
17146
17147 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
17148 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
17149 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
17150 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
17151
17152 /* Static Properties */
17153
17154 // Allow button mouse down events to pass through so they can be handled by the parent select widget
17155 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
17156
17157 OO.ui.ButtonOptionWidget.static.highlightable = false;
17158
17159 /* Methods */
17160
17161 /**
17162 * @inheritdoc
17163 */
17164 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
17165 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
17166
17167 if ( this.constructor.static.selectable ) {
17168 this.setActive( state );
17169 }
17170
17171 return this;
17172 };
17173
17174 /**
17175 * RadioOptionWidget is an option widget that looks like a radio button.
17176 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
17177 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
17178 *
17179 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
17180 *
17181 * @class
17182 * @extends OO.ui.OptionWidget
17183 *
17184 * @constructor
17185 * @param {Object} [config] Configuration options
17186 */
17187 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
17188 // Configuration initialization
17189 config = config || {};
17190
17191 // Properties (must be done before parent constructor which calls #setDisabled)
17192 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
17193
17194 // Parent constructor
17195 OO.ui.RadioOptionWidget.parent.call( this, config );
17196
17197 // Events
17198 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
17199
17200 // Initialization
17201 // Remove implicit role, we're handling it ourselves
17202 this.radio.$input.attr( 'role', 'presentation' );
17203 this.$element
17204 .addClass( 'oo-ui-radioOptionWidget' )
17205 .attr( 'role', 'radio' )
17206 .attr( 'aria-checked', 'false' )
17207 .removeAttr( 'aria-selected' )
17208 .prepend( this.radio.$element );
17209 };
17210
17211 /* Setup */
17212
17213 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
17214
17215 /* Static Properties */
17216
17217 OO.ui.RadioOptionWidget.static.highlightable = false;
17218
17219 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
17220
17221 OO.ui.RadioOptionWidget.static.pressable = false;
17222
17223 OO.ui.RadioOptionWidget.static.tagName = 'label';
17224
17225 /* Methods */
17226
17227 /**
17228 * @param {jQuery.Event} e Focus event
17229 * @private
17230 */
17231 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
17232 this.radio.$input.blur();
17233 this.$element.parent().focus();
17234 };
17235
17236 /**
17237 * @inheritdoc
17238 */
17239 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
17240 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
17241
17242 this.radio.setSelected( state );
17243 this.$element
17244 .attr( 'aria-checked', state.toString() )
17245 .removeAttr( 'aria-selected' );
17246
17247 return this;
17248 };
17249
17250 /**
17251 * @inheritdoc
17252 */
17253 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
17254 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
17255
17256 this.radio.setDisabled( this.isDisabled() );
17257
17258 return this;
17259 };
17260
17261 /**
17262 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
17263 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
17264 * the [OOjs UI documentation on MediaWiki] [1] for more information.
17265 *
17266 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
17267 *
17268 * @class
17269 * @extends OO.ui.DecoratedOptionWidget
17270 *
17271 * @constructor
17272 * @param {Object} [config] Configuration options
17273 */
17274 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
17275 // Configuration initialization
17276 config = $.extend( { icon: 'check' }, config );
17277
17278 // Parent constructor
17279 OO.ui.MenuOptionWidget.parent.call( this, config );
17280
17281 // Initialization
17282 this.$element
17283 .attr( 'role', 'menuitem' )
17284 .addClass( 'oo-ui-menuOptionWidget' );
17285 };
17286
17287 /* Setup */
17288
17289 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
17290
17291 /* Static Properties */
17292
17293 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
17294
17295 /**
17296 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
17297 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
17298 *
17299 * @example
17300 * var myDropdown = new OO.ui.DropdownWidget( {
17301 * menu: {
17302 * items: [
17303 * new OO.ui.MenuSectionOptionWidget( {
17304 * label: 'Dogs'
17305 * } ),
17306 * new OO.ui.MenuOptionWidget( {
17307 * data: 'corgi',
17308 * label: 'Welsh Corgi'
17309 * } ),
17310 * new OO.ui.MenuOptionWidget( {
17311 * data: 'poodle',
17312 * label: 'Standard Poodle'
17313 * } ),
17314 * new OO.ui.MenuSectionOptionWidget( {
17315 * label: 'Cats'
17316 * } ),
17317 * new OO.ui.MenuOptionWidget( {
17318 * data: 'lion',
17319 * label: 'Lion'
17320 * } )
17321 * ]
17322 * }
17323 * } );
17324 * $( 'body' ).append( myDropdown.$element );
17325 *
17326 * @class
17327 * @extends OO.ui.DecoratedOptionWidget
17328 *
17329 * @constructor
17330 * @param {Object} [config] Configuration options
17331 */
17332 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
17333 // Parent constructor
17334 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
17335
17336 // Initialization
17337 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
17338 };
17339
17340 /* Setup */
17341
17342 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
17343
17344 /* Static Properties */
17345
17346 OO.ui.MenuSectionOptionWidget.static.selectable = false;
17347
17348 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
17349
17350 /**
17351 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
17352 *
17353 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
17354 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
17355 * for an example.
17356 *
17357 * @class
17358 * @extends OO.ui.DecoratedOptionWidget
17359 *
17360 * @constructor
17361 * @param {Object} [config] Configuration options
17362 * @cfg {number} [level] Indentation level
17363 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
17364 */
17365 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
17366 // Configuration initialization
17367 config = config || {};
17368
17369 // Parent constructor
17370 OO.ui.OutlineOptionWidget.parent.call( this, config );
17371
17372 // Properties
17373 this.level = 0;
17374 this.movable = !!config.movable;
17375 this.removable = !!config.removable;
17376
17377 // Initialization
17378 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
17379 this.setLevel( config.level );
17380 };
17381
17382 /* Setup */
17383
17384 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
17385
17386 /* Static Properties */
17387
17388 OO.ui.OutlineOptionWidget.static.highlightable = false;
17389
17390 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
17391
17392 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
17393
17394 OO.ui.OutlineOptionWidget.static.levels = 3;
17395
17396 /* Methods */
17397
17398 /**
17399 * Check if item is movable.
17400 *
17401 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17402 *
17403 * @return {boolean} Item is movable
17404 */
17405 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
17406 return this.movable;
17407 };
17408
17409 /**
17410 * Check if item is removable.
17411 *
17412 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17413 *
17414 * @return {boolean} Item is removable
17415 */
17416 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
17417 return this.removable;
17418 };
17419
17420 /**
17421 * Get indentation level.
17422 *
17423 * @return {number} Indentation level
17424 */
17425 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
17426 return this.level;
17427 };
17428
17429 /**
17430 * Set movability.
17431 *
17432 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17433 *
17434 * @param {boolean} movable Item is movable
17435 * @chainable
17436 */
17437 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
17438 this.movable = !!movable;
17439 this.updateThemeClasses();
17440 return this;
17441 };
17442
17443 /**
17444 * Set removability.
17445 *
17446 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
17447 *
17448 * @param {boolean} movable Item is removable
17449 * @chainable
17450 */
17451 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
17452 this.removable = !!removable;
17453 this.updateThemeClasses();
17454 return this;
17455 };
17456
17457 /**
17458 * Set indentation level.
17459 *
17460 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17461 * @chainable
17462 */
17463 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
17464 var levels = this.constructor.static.levels,
17465 levelClass = this.constructor.static.levelClass,
17466 i = levels;
17467
17468 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
17469 while ( i-- ) {
17470 if ( this.level === i ) {
17471 this.$element.addClass( levelClass + i );
17472 } else {
17473 this.$element.removeClass( levelClass + i );
17474 }
17475 }
17476 this.updateThemeClasses();
17477
17478 return this;
17479 };
17480
17481 /**
17482 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17483 *
17484 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17485 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17486 * for an example.
17487 *
17488 * @class
17489 * @extends OO.ui.OptionWidget
17490 *
17491 * @constructor
17492 * @param {Object} [config] Configuration options
17493 */
17494 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
17495 // Configuration initialization
17496 config = config || {};
17497
17498 // Parent constructor
17499 OO.ui.TabOptionWidget.parent.call( this, config );
17500
17501 // Initialization
17502 this.$element.addClass( 'oo-ui-tabOptionWidget' );
17503 };
17504
17505 /* Setup */
17506
17507 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
17508
17509 /* Static Properties */
17510
17511 OO.ui.TabOptionWidget.static.highlightable = false;
17512
17513 /**
17514 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17515 * By default, each popup has an anchor that points toward its origin.
17516 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17517 *
17518 * @example
17519 * // A popup widget.
17520 * var popup = new OO.ui.PopupWidget( {
17521 * $content: $( '<p>Hi there!</p>' ),
17522 * padded: true,
17523 * width: 300
17524 * } );
17525 *
17526 * $( 'body' ).append( popup.$element );
17527 * // To display the popup, toggle the visibility to 'true'.
17528 * popup.toggle( true );
17529 *
17530 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17531 *
17532 * @class
17533 * @extends OO.ui.Widget
17534 * @mixins OO.ui.mixin.LabelElement
17535 * @mixins OO.ui.mixin.ClippableElement
17536 *
17537 * @constructor
17538 * @param {Object} [config] Configuration options
17539 * @cfg {number} [width=320] Width of popup in pixels
17540 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17541 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17542 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17543 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17544 * popup is leaning towards the right of the screen.
17545 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17546 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17547 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17548 * sentence in the given language.
17549 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17550 * See the [OOjs UI docs on MediaWiki][3] for an example.
17551 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17552 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17553 * @cfg {jQuery} [$content] Content to append to the popup's body
17554 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17555 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17556 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17557 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17558 * for an example.
17559 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17560 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17561 * button.
17562 * @cfg {boolean} [padded] Add padding to the popup's body
17563 */
17564 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
17565 // Configuration initialization
17566 config = config || {};
17567
17568 // Parent constructor
17569 OO.ui.PopupWidget.parent.call( this, config );
17570
17571 // Properties (must be set before ClippableElement constructor call)
17572 this.$body = $( '<div>' );
17573 this.$popup = $( '<div>' );
17574
17575 // Mixin constructors
17576 OO.ui.mixin.LabelElement.call( this, config );
17577 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
17578 $clippable: this.$body,
17579 $clippableContainer: this.$popup
17580 } ) );
17581
17582 // Properties
17583 this.$head = $( '<div>' );
17584 this.$footer = $( '<div>' );
17585 this.$anchor = $( '<div>' );
17586 // If undefined, will be computed lazily in updateDimensions()
17587 this.$container = config.$container;
17588 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
17589 this.autoClose = !!config.autoClose;
17590 this.$autoCloseIgnore = config.$autoCloseIgnore;
17591 this.transitionTimeout = null;
17592 this.anchor = null;
17593 this.width = config.width !== undefined ? config.width : 320;
17594 this.height = config.height !== undefined ? config.height : null;
17595 this.setAlignment( config.align );
17596 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
17597 this.onMouseDownHandler = this.onMouseDown.bind( this );
17598 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
17599
17600 // Events
17601 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
17602
17603 // Initialization
17604 this.toggleAnchor( config.anchor === undefined || config.anchor );
17605 this.$body.addClass( 'oo-ui-popupWidget-body' );
17606 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
17607 this.$head
17608 .addClass( 'oo-ui-popupWidget-head' )
17609 .append( this.$label, this.closeButton.$element );
17610 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
17611 if ( !config.head ) {
17612 this.$head.addClass( 'oo-ui-element-hidden' );
17613 }
17614 if ( !config.$footer ) {
17615 this.$footer.addClass( 'oo-ui-element-hidden' );
17616 }
17617 this.$popup
17618 .addClass( 'oo-ui-popupWidget-popup' )
17619 .append( this.$head, this.$body, this.$footer );
17620 this.$element
17621 .addClass( 'oo-ui-popupWidget' )
17622 .append( this.$popup, this.$anchor );
17623 // Move content, which was added to #$element by OO.ui.Widget, to the body
17624 if ( config.$content instanceof jQuery ) {
17625 this.$body.append( config.$content );
17626 }
17627 if ( config.$footer instanceof jQuery ) {
17628 this.$footer.append( config.$footer );
17629 }
17630 if ( config.padded ) {
17631 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
17632 }
17633
17634 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17635 // that reference properties not initialized at that time of parent class construction
17636 // TODO: Find a better way to handle post-constructor setup
17637 this.visible = false;
17638 this.$element.addClass( 'oo-ui-element-hidden' );
17639 };
17640
17641 /* Setup */
17642
17643 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
17644 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
17645 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
17646
17647 /* Methods */
17648
17649 /**
17650 * Handles mouse down events.
17651 *
17652 * @private
17653 * @param {MouseEvent} e Mouse down event
17654 */
17655 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
17656 if (
17657 this.isVisible() &&
17658 !$.contains( this.$element[ 0 ], e.target ) &&
17659 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
17660 ) {
17661 this.toggle( false );
17662 }
17663 };
17664
17665 /**
17666 * Bind mouse down listener.
17667 *
17668 * @private
17669 */
17670 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17671 // Capture clicks outside popup
17672 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17673 };
17674
17675 /**
17676 * Handles close button click events.
17677 *
17678 * @private
17679 */
17680 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17681 if ( this.isVisible() ) {
17682 this.toggle( false );
17683 }
17684 };
17685
17686 /**
17687 * Unbind mouse down listener.
17688 *
17689 * @private
17690 */
17691 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17692 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17693 };
17694
17695 /**
17696 * Handles key down events.
17697 *
17698 * @private
17699 * @param {KeyboardEvent} e Key down event
17700 */
17701 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17702 if (
17703 e.which === OO.ui.Keys.ESCAPE &&
17704 this.isVisible()
17705 ) {
17706 this.toggle( false );
17707 e.preventDefault();
17708 e.stopPropagation();
17709 }
17710 };
17711
17712 /**
17713 * Bind key down listener.
17714 *
17715 * @private
17716 */
17717 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17718 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17719 };
17720
17721 /**
17722 * Unbind key down listener.
17723 *
17724 * @private
17725 */
17726 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17727 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17728 };
17729
17730 /**
17731 * Show, hide, or toggle the visibility of the anchor.
17732 *
17733 * @param {boolean} [show] Show anchor, omit to toggle
17734 */
17735 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17736 show = show === undefined ? !this.anchored : !!show;
17737
17738 if ( this.anchored !== show ) {
17739 if ( show ) {
17740 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17741 } else {
17742 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17743 }
17744 this.anchored = show;
17745 }
17746 };
17747
17748 /**
17749 * Check if the anchor is visible.
17750 *
17751 * @return {boolean} Anchor is visible
17752 */
17753 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17754 return this.anchor;
17755 };
17756
17757 /**
17758 * @inheritdoc
17759 */
17760 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17761 var change;
17762 show = show === undefined ? !this.isVisible() : !!show;
17763
17764 change = show !== this.isVisible();
17765
17766 // Parent method
17767 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17768
17769 if ( change ) {
17770 if ( show ) {
17771 if ( this.autoClose ) {
17772 this.bindMouseDownListener();
17773 this.bindKeyDownListener();
17774 }
17775 this.updateDimensions();
17776 this.toggleClipping( true );
17777 } else {
17778 this.toggleClipping( false );
17779 if ( this.autoClose ) {
17780 this.unbindMouseDownListener();
17781 this.unbindKeyDownListener();
17782 }
17783 }
17784 }
17785
17786 return this;
17787 };
17788
17789 /**
17790 * Set the size of the popup.
17791 *
17792 * Changing the size may also change the popup's position depending on the alignment.
17793 *
17794 * @param {number} width Width in pixels
17795 * @param {number} height Height in pixels
17796 * @param {boolean} [transition=false] Use a smooth transition
17797 * @chainable
17798 */
17799 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17800 this.width = width;
17801 this.height = height !== undefined ? height : null;
17802 if ( this.isVisible() ) {
17803 this.updateDimensions( transition );
17804 }
17805 };
17806
17807 /**
17808 * Update the size and position.
17809 *
17810 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17811 * be called automatically.
17812 *
17813 * @param {boolean} [transition=false] Use a smooth transition
17814 * @chainable
17815 */
17816 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17817 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17818 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17819 align = this.align,
17820 widget = this;
17821
17822 if ( !this.$container ) {
17823 // Lazy-initialize $container if not specified in constructor
17824 this.$container = $( this.getClosestScrollableElementContainer() );
17825 }
17826
17827 // Set height and width before measuring things, since it might cause our measurements
17828 // to change (e.g. due to scrollbars appearing or disappearing)
17829 this.$popup.css( {
17830 width: this.width,
17831 height: this.height !== null ? this.height : 'auto'
17832 } );
17833
17834 // If we are in RTL, we need to flip the alignment, unless it is center
17835 if ( align === 'forwards' || align === 'backwards' ) {
17836 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17837 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17838 } else {
17839 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17840 }
17841
17842 }
17843
17844 // Compute initial popupOffset based on alignment
17845 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17846
17847 // Figure out if this will cause the popup to go beyond the edge of the container
17848 originOffset = this.$element.offset().left;
17849 containerLeft = this.$container.offset().left;
17850 containerWidth = this.$container.innerWidth();
17851 containerRight = containerLeft + containerWidth;
17852 popupLeft = popupOffset - this.containerPadding;
17853 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17854 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17855 overlapRight = containerRight - ( originOffset + popupRight );
17856
17857 // Adjust offset to make the popup not go beyond the edge, if needed
17858 if ( overlapRight < 0 ) {
17859 popupOffset += overlapRight;
17860 } else if ( overlapLeft < 0 ) {
17861 popupOffset -= overlapLeft;
17862 }
17863
17864 // Adjust offset to avoid anchor being rendered too close to the edge
17865 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17866 // TODO: Find a measurement that works for CSS anchors and image anchors
17867 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17868 if ( popupOffset + this.width < anchorWidth ) {
17869 popupOffset = anchorWidth - this.width;
17870 } else if ( -popupOffset < anchorWidth ) {
17871 popupOffset = -anchorWidth;
17872 }
17873
17874 // Prevent transition from being interrupted
17875 clearTimeout( this.transitionTimeout );
17876 if ( transition ) {
17877 // Enable transition
17878 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17879 }
17880
17881 // Position body relative to anchor
17882 this.$popup.css( 'margin-left', popupOffset );
17883
17884 if ( transition ) {
17885 // Prevent transitioning after transition is complete
17886 this.transitionTimeout = setTimeout( function () {
17887 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17888 }, 200 );
17889 } else {
17890 // Prevent transitioning immediately
17891 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17892 }
17893
17894 // Reevaluate clipping state since we've relocated and resized the popup
17895 this.clip();
17896
17897 return this;
17898 };
17899
17900 /**
17901 * Set popup alignment
17902 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17903 * `backwards` or `forwards`.
17904 */
17905 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17906 // Validate alignment and transform deprecated values
17907 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17908 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17909 } else {
17910 this.align = 'center';
17911 }
17912 };
17913
17914 /**
17915 * Get popup alignment
17916 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17917 * `backwards` or `forwards`.
17918 */
17919 OO.ui.PopupWidget.prototype.getAlignment = function () {
17920 return this.align;
17921 };
17922
17923 /**
17924 * Progress bars visually display the status of an operation, such as a download,
17925 * and can be either determinate or indeterminate:
17926 *
17927 * - **determinate** process bars show the percent of an operation that is complete.
17928 *
17929 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17930 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17931 * not use percentages.
17932 *
17933 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17934 *
17935 * @example
17936 * // Examples of determinate and indeterminate progress bars.
17937 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17938 * progress: 33
17939 * } );
17940 * var progressBar2 = new OO.ui.ProgressBarWidget();
17941 *
17942 * // Create a FieldsetLayout to layout progress bars
17943 * var fieldset = new OO.ui.FieldsetLayout;
17944 * fieldset.addItems( [
17945 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17946 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17947 * ] );
17948 * $( 'body' ).append( fieldset.$element );
17949 *
17950 * @class
17951 * @extends OO.ui.Widget
17952 *
17953 * @constructor
17954 * @param {Object} [config] Configuration options
17955 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17956 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17957 * By default, the progress bar is indeterminate.
17958 */
17959 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17960 // Configuration initialization
17961 config = config || {};
17962
17963 // Parent constructor
17964 OO.ui.ProgressBarWidget.parent.call( this, config );
17965
17966 // Properties
17967 this.$bar = $( '<div>' );
17968 this.progress = null;
17969
17970 // Initialization
17971 this.setProgress( config.progress !== undefined ? config.progress : false );
17972 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17973 this.$element
17974 .attr( {
17975 role: 'progressbar',
17976 'aria-valuemin': 0,
17977 'aria-valuemax': 100
17978 } )
17979 .addClass( 'oo-ui-progressBarWidget' )
17980 .append( this.$bar );
17981 };
17982
17983 /* Setup */
17984
17985 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17986
17987 /* Static Properties */
17988
17989 OO.ui.ProgressBarWidget.static.tagName = 'div';
17990
17991 /* Methods */
17992
17993 /**
17994 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17995 *
17996 * @return {number|boolean} Progress percent
17997 */
17998 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17999 return this.progress;
18000 };
18001
18002 /**
18003 * Set the percent of the process completed or `false` for an indeterminate process.
18004 *
18005 * @param {number|boolean} progress Progress percent or `false` for indeterminate
18006 */
18007 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
18008 this.progress = progress;
18009
18010 if ( progress !== false ) {
18011 this.$bar.css( 'width', this.progress + '%' );
18012 this.$element.attr( 'aria-valuenow', this.progress );
18013 } else {
18014 this.$bar.css( 'width', '' );
18015 this.$element.removeAttr( 'aria-valuenow' );
18016 }
18017 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
18018 };
18019
18020 /**
18021 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
18022 * and a menu of search results, which is displayed beneath the query
18023 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
18024 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
18025 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
18026 *
18027 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
18028 * the [OOjs UI demos][1] for an example.
18029 *
18030 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
18031 *
18032 * @class
18033 * @extends OO.ui.Widget
18034 *
18035 * @constructor
18036 * @param {Object} [config] Configuration options
18037 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
18038 * @cfg {string} [value] Initial query value
18039 */
18040 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
18041 // Configuration initialization
18042 config = config || {};
18043
18044 // Parent constructor
18045 OO.ui.SearchWidget.parent.call( this, config );
18046
18047 // Properties
18048 this.query = new OO.ui.TextInputWidget( {
18049 icon: 'search',
18050 placeholder: config.placeholder,
18051 value: config.value
18052 } );
18053 this.results = new OO.ui.SelectWidget();
18054 this.$query = $( '<div>' );
18055 this.$results = $( '<div>' );
18056
18057 // Events
18058 this.query.connect( this, {
18059 change: 'onQueryChange',
18060 enter: 'onQueryEnter'
18061 } );
18062 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
18063
18064 // Initialization
18065 this.$query
18066 .addClass( 'oo-ui-searchWidget-query' )
18067 .append( this.query.$element );
18068 this.$results
18069 .addClass( 'oo-ui-searchWidget-results' )
18070 .append( this.results.$element );
18071 this.$element
18072 .addClass( 'oo-ui-searchWidget' )
18073 .append( this.$results, this.$query );
18074 };
18075
18076 /* Setup */
18077
18078 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
18079
18080 /* Methods */
18081
18082 /**
18083 * Handle query key down events.
18084 *
18085 * @private
18086 * @param {jQuery.Event} e Key down event
18087 */
18088 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
18089 var highlightedItem, nextItem,
18090 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
18091
18092 if ( dir ) {
18093 highlightedItem = this.results.getHighlightedItem();
18094 if ( !highlightedItem ) {
18095 highlightedItem = this.results.getSelectedItem();
18096 }
18097 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
18098 this.results.highlightItem( nextItem );
18099 nextItem.scrollElementIntoView();
18100 }
18101 };
18102
18103 /**
18104 * Handle select widget select events.
18105 *
18106 * Clears existing results. Subclasses should repopulate items according to new query.
18107 *
18108 * @private
18109 * @param {string} value New value
18110 */
18111 OO.ui.SearchWidget.prototype.onQueryChange = function () {
18112 // Reset
18113 this.results.clearItems();
18114 };
18115
18116 /**
18117 * Handle select widget enter key events.
18118 *
18119 * Chooses highlighted item.
18120 *
18121 * @private
18122 * @param {string} value New value
18123 */
18124 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
18125 var highlightedItem = this.results.getHighlightedItem();
18126 if ( highlightedItem ) {
18127 this.results.chooseItem( highlightedItem );
18128 }
18129 };
18130
18131 /**
18132 * Get the query input.
18133 *
18134 * @return {OO.ui.TextInputWidget} Query input
18135 */
18136 OO.ui.SearchWidget.prototype.getQuery = function () {
18137 return this.query;
18138 };
18139
18140 /**
18141 * Get the search results menu.
18142 *
18143 * @return {OO.ui.SelectWidget} Menu of search results
18144 */
18145 OO.ui.SearchWidget.prototype.getResults = function () {
18146 return this.results;
18147 };
18148
18149 /**
18150 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
18151 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
18152 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
18153 * menu selects}.
18154 *
18155 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
18156 * information, please see the [OOjs UI documentation on MediaWiki][1].
18157 *
18158 * @example
18159 * // Example of a select widget with three options
18160 * var select = new OO.ui.SelectWidget( {
18161 * items: [
18162 * new OO.ui.OptionWidget( {
18163 * data: 'a',
18164 * label: 'Option One',
18165 * } ),
18166 * new OO.ui.OptionWidget( {
18167 * data: 'b',
18168 * label: 'Option Two',
18169 * } ),
18170 * new OO.ui.OptionWidget( {
18171 * data: 'c',
18172 * label: 'Option Three',
18173 * } )
18174 * ]
18175 * } );
18176 * $( 'body' ).append( select.$element );
18177 *
18178 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18179 *
18180 * @abstract
18181 * @class
18182 * @extends OO.ui.Widget
18183 * @mixins OO.ui.mixin.GroupWidget
18184 *
18185 * @constructor
18186 * @param {Object} [config] Configuration options
18187 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
18188 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
18189 * the [OOjs UI documentation on MediaWiki] [2] for examples.
18190 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18191 */
18192 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
18193 // Configuration initialization
18194 config = config || {};
18195
18196 // Parent constructor
18197 OO.ui.SelectWidget.parent.call( this, config );
18198
18199 // Mixin constructors
18200 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
18201
18202 // Properties
18203 this.pressed = false;
18204 this.selecting = null;
18205 this.onMouseUpHandler = this.onMouseUp.bind( this );
18206 this.onMouseMoveHandler = this.onMouseMove.bind( this );
18207 this.onKeyDownHandler = this.onKeyDown.bind( this );
18208 this.onKeyPressHandler = this.onKeyPress.bind( this );
18209 this.keyPressBuffer = '';
18210 this.keyPressBufferTimer = null;
18211
18212 // Events
18213 this.connect( this, {
18214 toggle: 'onToggle'
18215 } );
18216 this.$element.on( {
18217 mousedown: this.onMouseDown.bind( this ),
18218 mouseover: this.onMouseOver.bind( this ),
18219 mouseleave: this.onMouseLeave.bind( this )
18220 } );
18221
18222 // Initialization
18223 this.$element
18224 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
18225 .attr( 'role', 'listbox' );
18226 if ( Array.isArray( config.items ) ) {
18227 this.addItems( config.items );
18228 }
18229 };
18230
18231 /* Setup */
18232
18233 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
18234
18235 // Need to mixin base class as well
18236 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
18237 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
18238
18239 /* Static */
18240 OO.ui.SelectWidget.static.passAllFilter = function () {
18241 return true;
18242 };
18243
18244 /* Events */
18245
18246 /**
18247 * @event highlight
18248 *
18249 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
18250 *
18251 * @param {OO.ui.OptionWidget|null} item Highlighted item
18252 */
18253
18254 /**
18255 * @event press
18256 *
18257 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
18258 * pressed state of an option.
18259 *
18260 * @param {OO.ui.OptionWidget|null} item Pressed item
18261 */
18262
18263 /**
18264 * @event select
18265 *
18266 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
18267 *
18268 * @param {OO.ui.OptionWidget|null} item Selected item
18269 */
18270
18271 /**
18272 * @event choose
18273 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
18274 * @param {OO.ui.OptionWidget} item Chosen item
18275 */
18276
18277 /**
18278 * @event add
18279 *
18280 * An `add` event is emitted when options are added to the select with the #addItems method.
18281 *
18282 * @param {OO.ui.OptionWidget[]} items Added items
18283 * @param {number} index Index of insertion point
18284 */
18285
18286 /**
18287 * @event remove
18288 *
18289 * A `remove` event is emitted when options are removed from the select with the #clearItems
18290 * or #removeItems methods.
18291 *
18292 * @param {OO.ui.OptionWidget[]} items Removed items
18293 */
18294
18295 /* Methods */
18296
18297 /**
18298 * Handle mouse down events.
18299 *
18300 * @private
18301 * @param {jQuery.Event} e Mouse down event
18302 */
18303 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
18304 var item;
18305
18306 if ( !this.isDisabled() && e.which === 1 ) {
18307 this.togglePressed( true );
18308 item = this.getTargetItem( e );
18309 if ( item && item.isSelectable() ) {
18310 this.pressItem( item );
18311 this.selecting = item;
18312 OO.ui.addCaptureEventListener(
18313 this.getElementDocument(),
18314 'mouseup',
18315 this.onMouseUpHandler
18316 );
18317 OO.ui.addCaptureEventListener(
18318 this.getElementDocument(),
18319 'mousemove',
18320 this.onMouseMoveHandler
18321 );
18322 }
18323 }
18324 return false;
18325 };
18326
18327 /**
18328 * Handle mouse up events.
18329 *
18330 * @private
18331 * @param {jQuery.Event} e Mouse up event
18332 */
18333 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
18334 var item;
18335
18336 this.togglePressed( false );
18337 if ( !this.selecting ) {
18338 item = this.getTargetItem( e );
18339 if ( item && item.isSelectable() ) {
18340 this.selecting = item;
18341 }
18342 }
18343 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
18344 this.pressItem( null );
18345 this.chooseItem( this.selecting );
18346 this.selecting = null;
18347 }
18348
18349 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
18350 this.onMouseUpHandler );
18351 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
18352 this.onMouseMoveHandler );
18353
18354 return false;
18355 };
18356
18357 /**
18358 * Handle mouse move events.
18359 *
18360 * @private
18361 * @param {jQuery.Event} e Mouse move event
18362 */
18363 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
18364 var item;
18365
18366 if ( !this.isDisabled() && this.pressed ) {
18367 item = this.getTargetItem( e );
18368 if ( item && item !== this.selecting && item.isSelectable() ) {
18369 this.pressItem( item );
18370 this.selecting = item;
18371 }
18372 }
18373 return false;
18374 };
18375
18376 /**
18377 * Handle mouse over events.
18378 *
18379 * @private
18380 * @param {jQuery.Event} e Mouse over event
18381 */
18382 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
18383 var item;
18384
18385 if ( !this.isDisabled() ) {
18386 item = this.getTargetItem( e );
18387 this.highlightItem( item && item.isHighlightable() ? item : null );
18388 }
18389 return false;
18390 };
18391
18392 /**
18393 * Handle mouse leave events.
18394 *
18395 * @private
18396 * @param {jQuery.Event} e Mouse over event
18397 */
18398 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
18399 if ( !this.isDisabled() ) {
18400 this.highlightItem( null );
18401 }
18402 return false;
18403 };
18404
18405 /**
18406 * Handle key down events.
18407 *
18408 * @protected
18409 * @param {jQuery.Event} e Key down event
18410 */
18411 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
18412 var nextItem,
18413 handled = false,
18414 currentItem = this.getHighlightedItem() || this.getSelectedItem();
18415
18416 if ( !this.isDisabled() && this.isVisible() ) {
18417 switch ( e.keyCode ) {
18418 case OO.ui.Keys.ENTER:
18419 if ( currentItem && currentItem.constructor.static.highlightable ) {
18420 // Was only highlighted, now let's select it. No-op if already selected.
18421 this.chooseItem( currentItem );
18422 handled = true;
18423 }
18424 break;
18425 case OO.ui.Keys.UP:
18426 case OO.ui.Keys.LEFT:
18427 this.clearKeyPressBuffer();
18428 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
18429 handled = true;
18430 break;
18431 case OO.ui.Keys.DOWN:
18432 case OO.ui.Keys.RIGHT:
18433 this.clearKeyPressBuffer();
18434 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
18435 handled = true;
18436 break;
18437 case OO.ui.Keys.ESCAPE:
18438 case OO.ui.Keys.TAB:
18439 if ( currentItem && currentItem.constructor.static.highlightable ) {
18440 currentItem.setHighlighted( false );
18441 }
18442 this.unbindKeyDownListener();
18443 this.unbindKeyPressListener();
18444 // Don't prevent tabbing away / defocusing
18445 handled = false;
18446 break;
18447 }
18448
18449 if ( nextItem ) {
18450 if ( nextItem.constructor.static.highlightable ) {
18451 this.highlightItem( nextItem );
18452 } else {
18453 this.chooseItem( nextItem );
18454 }
18455 nextItem.scrollElementIntoView();
18456 }
18457
18458 if ( handled ) {
18459 // Can't just return false, because e is not always a jQuery event
18460 e.preventDefault();
18461 e.stopPropagation();
18462 }
18463 }
18464 };
18465
18466 /**
18467 * Bind key down listener.
18468 *
18469 * @protected
18470 */
18471 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
18472 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18473 };
18474
18475 /**
18476 * Unbind key down listener.
18477 *
18478 * @protected
18479 */
18480 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
18481 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
18482 };
18483
18484 /**
18485 * Clear the key-press buffer
18486 *
18487 * @protected
18488 */
18489 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
18490 if ( this.keyPressBufferTimer ) {
18491 clearTimeout( this.keyPressBufferTimer );
18492 this.keyPressBufferTimer = null;
18493 }
18494 this.keyPressBuffer = '';
18495 };
18496
18497 /**
18498 * Handle key press events.
18499 *
18500 * @protected
18501 * @param {jQuery.Event} e Key press event
18502 */
18503 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
18504 var c, filter, item;
18505
18506 if ( !e.charCode ) {
18507 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
18508 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
18509 return false;
18510 }
18511 return;
18512 }
18513 if ( String.fromCodePoint ) {
18514 c = String.fromCodePoint( e.charCode );
18515 } else {
18516 c = String.fromCharCode( e.charCode );
18517 }
18518
18519 if ( this.keyPressBufferTimer ) {
18520 clearTimeout( this.keyPressBufferTimer );
18521 }
18522 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
18523
18524 item = this.getHighlightedItem() || this.getSelectedItem();
18525
18526 if ( this.keyPressBuffer === c ) {
18527 // Common (if weird) special case: typing "xxxx" will cycle through all
18528 // the items beginning with "x".
18529 if ( item ) {
18530 item = this.getRelativeSelectableItem( item, 1 );
18531 }
18532 } else {
18533 this.keyPressBuffer += c;
18534 }
18535
18536 filter = this.getItemMatcher( this.keyPressBuffer, false );
18537 if ( !item || !filter( item ) ) {
18538 item = this.getRelativeSelectableItem( item, 1, filter );
18539 }
18540 if ( item ) {
18541 if ( item.constructor.static.highlightable ) {
18542 this.highlightItem( item );
18543 } else {
18544 this.chooseItem( item );
18545 }
18546 item.scrollElementIntoView();
18547 }
18548
18549 return false;
18550 };
18551
18552 /**
18553 * Get a matcher for the specific string
18554 *
18555 * @protected
18556 * @param {string} s String to match against items
18557 * @param {boolean} [exact=false] Only accept exact matches
18558 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18559 */
18560 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
18561 var re;
18562
18563 if ( s.normalize ) {
18564 s = s.normalize();
18565 }
18566 s = exact ? s.trim() : s.replace( /^\s+/, '' );
18567 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18568 if ( exact ) {
18569 re += '\\s*$';
18570 }
18571 re = new RegExp( re, 'i' );
18572 return function ( item ) {
18573 var l = item.getLabel();
18574 if ( typeof l !== 'string' ) {
18575 l = item.$label.text();
18576 }
18577 if ( l.normalize ) {
18578 l = l.normalize();
18579 }
18580 return re.test( l );
18581 };
18582 };
18583
18584 /**
18585 * Bind key press listener.
18586 *
18587 * @protected
18588 */
18589 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
18590 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18591 };
18592
18593 /**
18594 * Unbind key down listener.
18595 *
18596 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18597 * implementation.
18598 *
18599 * @protected
18600 */
18601 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
18602 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
18603 this.clearKeyPressBuffer();
18604 };
18605
18606 /**
18607 * Visibility change handler
18608 *
18609 * @protected
18610 * @param {boolean} visible
18611 */
18612 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
18613 if ( !visible ) {
18614 this.clearKeyPressBuffer();
18615 }
18616 };
18617
18618 /**
18619 * Get the closest item to a jQuery.Event.
18620 *
18621 * @private
18622 * @param {jQuery.Event} e
18623 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18624 */
18625 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
18626 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18627 };
18628
18629 /**
18630 * Get selected item.
18631 *
18632 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18633 */
18634 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
18635 var i, len;
18636
18637 for ( i = 0, len = this.items.length; i < len; i++ ) {
18638 if ( this.items[ i ].isSelected() ) {
18639 return this.items[ i ];
18640 }
18641 }
18642 return null;
18643 };
18644
18645 /**
18646 * Get highlighted item.
18647 *
18648 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18649 */
18650 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
18651 var i, len;
18652
18653 for ( i = 0, len = this.items.length; i < len; i++ ) {
18654 if ( this.items[ i ].isHighlighted() ) {
18655 return this.items[ i ];
18656 }
18657 }
18658 return null;
18659 };
18660
18661 /**
18662 * Toggle pressed state.
18663 *
18664 * Press is a state that occurs when a user mouses down on an item, but
18665 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18666 * until the user releases the mouse.
18667 *
18668 * @param {boolean} pressed An option is being pressed
18669 */
18670 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18671 if ( pressed === undefined ) {
18672 pressed = !this.pressed;
18673 }
18674 if ( pressed !== this.pressed ) {
18675 this.$element
18676 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18677 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18678 this.pressed = pressed;
18679 }
18680 };
18681
18682 /**
18683 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18684 * and any existing highlight will be removed. The highlight is mutually exclusive.
18685 *
18686 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18687 * @fires highlight
18688 * @chainable
18689 */
18690 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18691 var i, len, highlighted,
18692 changed = false;
18693
18694 for ( i = 0, len = this.items.length; i < len; i++ ) {
18695 highlighted = this.items[ i ] === item;
18696 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18697 this.items[ i ].setHighlighted( highlighted );
18698 changed = true;
18699 }
18700 }
18701 if ( changed ) {
18702 this.emit( 'highlight', item );
18703 }
18704
18705 return this;
18706 };
18707
18708 /**
18709 * Fetch an item by its label.
18710 *
18711 * @param {string} label Label of the item to select.
18712 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18713 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18714 */
18715 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18716 var i, item, found,
18717 len = this.items.length,
18718 filter = this.getItemMatcher( label, true );
18719
18720 for ( i = 0; i < len; i++ ) {
18721 item = this.items[ i ];
18722 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18723 return item;
18724 }
18725 }
18726
18727 if ( prefix ) {
18728 found = null;
18729 filter = this.getItemMatcher( label, false );
18730 for ( i = 0; i < len; i++ ) {
18731 item = this.items[ i ];
18732 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18733 if ( found ) {
18734 return null;
18735 }
18736 found = item;
18737 }
18738 }
18739 if ( found ) {
18740 return found;
18741 }
18742 }
18743
18744 return null;
18745 };
18746
18747 /**
18748 * Programmatically select an option by its label. If the item does not exist,
18749 * all options will be deselected.
18750 *
18751 * @param {string} [label] Label of the item to select.
18752 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18753 * @fires select
18754 * @chainable
18755 */
18756 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18757 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18758 if ( label === undefined || !itemFromLabel ) {
18759 return this.selectItem();
18760 }
18761 return this.selectItem( itemFromLabel );
18762 };
18763
18764 /**
18765 * Programmatically select an option by its data. If the `data` parameter is omitted,
18766 * or if the item does not exist, all options will be deselected.
18767 *
18768 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18769 * @fires select
18770 * @chainable
18771 */
18772 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18773 var itemFromData = this.getItemFromData( data );
18774 if ( data === undefined || !itemFromData ) {
18775 return this.selectItem();
18776 }
18777 return this.selectItem( itemFromData );
18778 };
18779
18780 /**
18781 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18782 * all options will be deselected.
18783 *
18784 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18785 * @fires select
18786 * @chainable
18787 */
18788 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18789 var i, len, selected,
18790 changed = false;
18791
18792 for ( i = 0, len = this.items.length; i < len; i++ ) {
18793 selected = this.items[ i ] === item;
18794 if ( this.items[ i ].isSelected() !== selected ) {
18795 this.items[ i ].setSelected( selected );
18796 changed = true;
18797 }
18798 }
18799 if ( changed ) {
18800 this.emit( 'select', item );
18801 }
18802
18803 return this;
18804 };
18805
18806 /**
18807 * Press an item.
18808 *
18809 * Press is a state that occurs when a user mouses down on an item, but has not
18810 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18811 * releases the mouse.
18812 *
18813 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18814 * @fires press
18815 * @chainable
18816 */
18817 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18818 var i, len, pressed,
18819 changed = false;
18820
18821 for ( i = 0, len = this.items.length; i < len; i++ ) {
18822 pressed = this.items[ i ] === item;
18823 if ( this.items[ i ].isPressed() !== pressed ) {
18824 this.items[ i ].setPressed( pressed );
18825 changed = true;
18826 }
18827 }
18828 if ( changed ) {
18829 this.emit( 'press', item );
18830 }
18831
18832 return this;
18833 };
18834
18835 /**
18836 * Choose an item.
18837 *
18838 * Note that ‘choose’ should never be modified programmatically. A user can choose
18839 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18840 * use the #selectItem method.
18841 *
18842 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18843 * when users choose an item with the keyboard or mouse.
18844 *
18845 * @param {OO.ui.OptionWidget} item Item to choose
18846 * @fires choose
18847 * @chainable
18848 */
18849 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18850 if ( item ) {
18851 this.selectItem( item );
18852 this.emit( 'choose', item );
18853 }
18854
18855 return this;
18856 };
18857
18858 /**
18859 * Get an option by its position relative to the specified item (or to the start of the option array,
18860 * if item is `null`). The direction in which to search through the option array is specified with a
18861 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18862 * `null` if there are no options in the array.
18863 *
18864 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18865 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18866 * @param {Function} filter Only consider items for which this function returns
18867 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18868 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18869 */
18870 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18871 var currentIndex, nextIndex, i,
18872 increase = direction > 0 ? 1 : -1,
18873 len = this.items.length;
18874
18875 if ( !$.isFunction( filter ) ) {
18876 filter = OO.ui.SelectWidget.static.passAllFilter;
18877 }
18878
18879 if ( item instanceof OO.ui.OptionWidget ) {
18880 currentIndex = this.items.indexOf( item );
18881 nextIndex = ( currentIndex + increase + len ) % len;
18882 } else {
18883 // If no item is selected and moving forward, start at the beginning.
18884 // If moving backward, start at the end.
18885 nextIndex = direction > 0 ? 0 : len - 1;
18886 }
18887
18888 for ( i = 0; i < len; i++ ) {
18889 item = this.items[ nextIndex ];
18890 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18891 return item;
18892 }
18893 nextIndex = ( nextIndex + increase + len ) % len;
18894 }
18895 return null;
18896 };
18897
18898 /**
18899 * Get the next selectable item or `null` if there are no selectable items.
18900 * Disabled options and menu-section markers and breaks are not selectable.
18901 *
18902 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18903 */
18904 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18905 var i, len, item;
18906
18907 for ( i = 0, len = this.items.length; i < len; i++ ) {
18908 item = this.items[ i ];
18909 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18910 return item;
18911 }
18912 }
18913
18914 return null;
18915 };
18916
18917 /**
18918 * Add an array of options to the select. Optionally, an index number can be used to
18919 * specify an insertion point.
18920 *
18921 * @param {OO.ui.OptionWidget[]} items Items to add
18922 * @param {number} [index] Index to insert items after
18923 * @fires add
18924 * @chainable
18925 */
18926 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18927 // Mixin method
18928 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18929
18930 // Always provide an index, even if it was omitted
18931 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18932
18933 return this;
18934 };
18935
18936 /**
18937 * Remove the specified array of options from the select. Options will be detached
18938 * from the DOM, not removed, so they can be reused later. To remove all options from
18939 * the select, you may wish to use the #clearItems method instead.
18940 *
18941 * @param {OO.ui.OptionWidget[]} items Items to remove
18942 * @fires remove
18943 * @chainable
18944 */
18945 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18946 var i, len, item;
18947
18948 // Deselect items being removed
18949 for ( i = 0, len = items.length; i < len; i++ ) {
18950 item = items[ i ];
18951 if ( item.isSelected() ) {
18952 this.selectItem( null );
18953 }
18954 }
18955
18956 // Mixin method
18957 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18958
18959 this.emit( 'remove', items );
18960
18961 return this;
18962 };
18963
18964 /**
18965 * Clear all options from the select. Options will be detached from the DOM, not removed,
18966 * so that they can be reused later. To remove a subset of options from the select, use
18967 * the #removeItems method.
18968 *
18969 * @fires remove
18970 * @chainable
18971 */
18972 OO.ui.SelectWidget.prototype.clearItems = function () {
18973 var items = this.items.slice();
18974
18975 // Mixin method
18976 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18977
18978 // Clear selection
18979 this.selectItem( null );
18980
18981 this.emit( 'remove', items );
18982
18983 return this;
18984 };
18985
18986 /**
18987 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18988 * button options and is used together with
18989 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18990 * highlighting, choosing, and selecting mutually exclusive options. Please see
18991 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18992 *
18993 * @example
18994 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18995 * var option1 = new OO.ui.ButtonOptionWidget( {
18996 * data: 1,
18997 * label: 'Option 1',
18998 * title: 'Button option 1'
18999 * } );
19000 *
19001 * var option2 = new OO.ui.ButtonOptionWidget( {
19002 * data: 2,
19003 * label: 'Option 2',
19004 * title: 'Button option 2'
19005 * } );
19006 *
19007 * var option3 = new OO.ui.ButtonOptionWidget( {
19008 * data: 3,
19009 * label: 'Option 3',
19010 * title: 'Button option 3'
19011 * } );
19012 *
19013 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
19014 * items: [ option1, option2, option3 ]
19015 * } );
19016 * $( 'body' ).append( buttonSelect.$element );
19017 *
19018 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19019 *
19020 * @class
19021 * @extends OO.ui.SelectWidget
19022 * @mixins OO.ui.mixin.TabIndexedElement
19023 *
19024 * @constructor
19025 * @param {Object} [config] Configuration options
19026 */
19027 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
19028 // Parent constructor
19029 OO.ui.ButtonSelectWidget.parent.call( this, config );
19030
19031 // Mixin constructors
19032 OO.ui.mixin.TabIndexedElement.call( this, config );
19033
19034 // Events
19035 this.$element.on( {
19036 focus: this.bindKeyDownListener.bind( this ),
19037 blur: this.unbindKeyDownListener.bind( this )
19038 } );
19039
19040 // Initialization
19041 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
19042 };
19043
19044 /* Setup */
19045
19046 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
19047 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
19048
19049 /**
19050 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
19051 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
19052 * an interface for adding, removing and selecting options.
19053 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19054 *
19055 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
19056 * OO.ui.RadioSelectInputWidget instead.
19057 *
19058 * @example
19059 * // A RadioSelectWidget with RadioOptions.
19060 * var option1 = new OO.ui.RadioOptionWidget( {
19061 * data: 'a',
19062 * label: 'Selected radio option'
19063 * } );
19064 *
19065 * var option2 = new OO.ui.RadioOptionWidget( {
19066 * data: 'b',
19067 * label: 'Unselected radio option'
19068 * } );
19069 *
19070 * var radioSelect=new OO.ui.RadioSelectWidget( {
19071 * items: [ option1, option2 ]
19072 * } );
19073 *
19074 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
19075 * radioSelect.selectItem( option1 );
19076 *
19077 * $( 'body' ).append( radioSelect.$element );
19078 *
19079 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19080
19081 *
19082 * @class
19083 * @extends OO.ui.SelectWidget
19084 * @mixins OO.ui.mixin.TabIndexedElement
19085 *
19086 * @constructor
19087 * @param {Object} [config] Configuration options
19088 */
19089 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
19090 // Parent constructor
19091 OO.ui.RadioSelectWidget.parent.call( this, config );
19092
19093 // Mixin constructors
19094 OO.ui.mixin.TabIndexedElement.call( this, config );
19095
19096 // Events
19097 this.$element.on( {
19098 focus: this.bindKeyDownListener.bind( this ),
19099 blur: this.unbindKeyDownListener.bind( this )
19100 } );
19101
19102 // Initialization
19103 this.$element
19104 .addClass( 'oo-ui-radioSelectWidget' )
19105 .attr( 'role', 'radiogroup' );
19106 };
19107
19108 /* Setup */
19109
19110 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
19111 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
19112
19113 /**
19114 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
19115 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
19116 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
19117 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
19118 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
19119 * and customized to be opened, closed, and displayed as needed.
19120 *
19121 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
19122 * mouse outside the menu.
19123 *
19124 * Menus also have support for keyboard interaction:
19125 *
19126 * - Enter/Return key: choose and select a menu option
19127 * - Up-arrow key: highlight the previous menu option
19128 * - Down-arrow key: highlight the next menu option
19129 * - Esc key: hide the menu
19130 *
19131 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
19132 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
19133 *
19134 * @class
19135 * @extends OO.ui.SelectWidget
19136 * @mixins OO.ui.mixin.ClippableElement
19137 *
19138 * @constructor
19139 * @param {Object} [config] Configuration options
19140 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
19141 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
19142 * and {@link OO.ui.mixin.LookupElement LookupElement}
19143 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
19144 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
19145 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
19146 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
19147 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
19148 * that button, unless the button (or its parent widget) is passed in here.
19149 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
19150 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
19151 */
19152 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
19153 // Configuration initialization
19154 config = config || {};
19155
19156 // Parent constructor
19157 OO.ui.MenuSelectWidget.parent.call( this, config );
19158
19159 // Mixin constructors
19160 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
19161
19162 // Properties
19163 this.newItems = null;
19164 this.autoHide = config.autoHide === undefined || !!config.autoHide;
19165 this.filterFromInput = !!config.filterFromInput;
19166 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
19167 this.$widget = config.widget ? config.widget.$element : null;
19168 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
19169 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
19170
19171 // Initialization
19172 this.$element
19173 .addClass( 'oo-ui-menuSelectWidget' )
19174 .attr( 'role', 'menu' );
19175
19176 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
19177 // that reference properties not initialized at that time of parent class construction
19178 // TODO: Find a better way to handle post-constructor setup
19179 this.visible = false;
19180 this.$element.addClass( 'oo-ui-element-hidden' );
19181 };
19182
19183 /* Setup */
19184
19185 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
19186 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
19187
19188 /* Methods */
19189
19190 /**
19191 * Handles document mouse down events.
19192 *
19193 * @protected
19194 * @param {jQuery.Event} e Key down event
19195 */
19196 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
19197 if (
19198 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
19199 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
19200 ) {
19201 this.toggle( false );
19202 }
19203 };
19204
19205 /**
19206 * @inheritdoc
19207 */
19208 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
19209 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
19210
19211 if ( !this.isDisabled() && this.isVisible() ) {
19212 switch ( e.keyCode ) {
19213 case OO.ui.Keys.LEFT:
19214 case OO.ui.Keys.RIGHT:
19215 // Do nothing if a text field is associated, arrow keys will be handled natively
19216 if ( !this.$input ) {
19217 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19218 }
19219 break;
19220 case OO.ui.Keys.ESCAPE:
19221 case OO.ui.Keys.TAB:
19222 if ( currentItem ) {
19223 currentItem.setHighlighted( false );
19224 }
19225 this.toggle( false );
19226 // Don't prevent tabbing away, prevent defocusing
19227 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
19228 e.preventDefault();
19229 e.stopPropagation();
19230 }
19231 break;
19232 default:
19233 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
19234 return;
19235 }
19236 }
19237 };
19238
19239 /**
19240 * Update menu item visibility after input changes.
19241 * @protected
19242 */
19243 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
19244 var i, item,
19245 len = this.items.length,
19246 showAll = !this.isVisible(),
19247 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
19248
19249 for ( i = 0; i < len; i++ ) {
19250 item = this.items[ i ];
19251 if ( item instanceof OO.ui.OptionWidget ) {
19252 item.toggle( showAll || filter( item ) );
19253 }
19254 }
19255
19256 // Reevaluate clipping
19257 this.clip();
19258 };
19259
19260 /**
19261 * @inheritdoc
19262 */
19263 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
19264 if ( this.$input ) {
19265 this.$input.on( 'keydown', this.onKeyDownHandler );
19266 } else {
19267 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
19268 }
19269 };
19270
19271 /**
19272 * @inheritdoc
19273 */
19274 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
19275 if ( this.$input ) {
19276 this.$input.off( 'keydown', this.onKeyDownHandler );
19277 } else {
19278 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
19279 }
19280 };
19281
19282 /**
19283 * @inheritdoc
19284 */
19285 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
19286 if ( this.$input ) {
19287 if ( this.filterFromInput ) {
19288 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19289 }
19290 } else {
19291 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
19292 }
19293 };
19294
19295 /**
19296 * @inheritdoc
19297 */
19298 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
19299 if ( this.$input ) {
19300 if ( this.filterFromInput ) {
19301 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
19302 this.updateItemVisibility();
19303 }
19304 } else {
19305 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
19306 }
19307 };
19308
19309 /**
19310 * Choose an item.
19311 *
19312 * When a user chooses an item, the menu is closed.
19313 *
19314 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
19315 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
19316 * @param {OO.ui.OptionWidget} item Item to choose
19317 * @chainable
19318 */
19319 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
19320 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
19321 this.toggle( false );
19322 return this;
19323 };
19324
19325 /**
19326 * @inheritdoc
19327 */
19328 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
19329 var i, len, item;
19330
19331 // Parent method
19332 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
19333
19334 // Auto-initialize
19335 if ( !this.newItems ) {
19336 this.newItems = [];
19337 }
19338
19339 for ( i = 0, len = items.length; i < len; i++ ) {
19340 item = items[ i ];
19341 if ( this.isVisible() ) {
19342 // Defer fitting label until item has been attached
19343 item.fitLabel();
19344 } else {
19345 this.newItems.push( item );
19346 }
19347 }
19348
19349 // Reevaluate clipping
19350 this.clip();
19351
19352 return this;
19353 };
19354
19355 /**
19356 * @inheritdoc
19357 */
19358 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
19359 // Parent method
19360 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
19361
19362 // Reevaluate clipping
19363 this.clip();
19364
19365 return this;
19366 };
19367
19368 /**
19369 * @inheritdoc
19370 */
19371 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
19372 // Parent method
19373 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
19374
19375 // Reevaluate clipping
19376 this.clip();
19377
19378 return this;
19379 };
19380
19381 /**
19382 * @inheritdoc
19383 */
19384 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
19385 var i, len, change;
19386
19387 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
19388 change = visible !== this.isVisible();
19389
19390 // Parent method
19391 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
19392
19393 if ( change ) {
19394 if ( visible ) {
19395 this.bindKeyDownListener();
19396 this.bindKeyPressListener();
19397
19398 if ( this.newItems && this.newItems.length ) {
19399 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
19400 this.newItems[ i ].fitLabel();
19401 }
19402 this.newItems = null;
19403 }
19404 this.toggleClipping( true );
19405
19406 // Auto-hide
19407 if ( this.autoHide ) {
19408 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19409 }
19410 } else {
19411 this.unbindKeyDownListener();
19412 this.unbindKeyPressListener();
19413 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
19414 this.toggleClipping( false );
19415 }
19416 }
19417
19418 return this;
19419 };
19420
19421 /**
19422 * FloatingMenuSelectWidget is a menu that will stick under a specified
19423 * container, even when it is inserted elsewhere in the document (for example,
19424 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
19425 * menu from being clipped too aggresively.
19426 *
19427 * The menu's position is automatically calculated and maintained when the menu
19428 * is toggled or the window is resized.
19429 *
19430 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
19431 *
19432 * @class
19433 * @extends OO.ui.MenuSelectWidget
19434 * @mixins OO.ui.mixin.FloatableElement
19435 *
19436 * @constructor
19437 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
19438 * Deprecated, omit this parameter and specify `$container` instead.
19439 * @param {Object} [config] Configuration options
19440 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
19441 */
19442 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
19443 // Allow 'inputWidget' parameter and config for backwards compatibility
19444 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
19445 config = inputWidget;
19446 inputWidget = config.inputWidget;
19447 }
19448
19449 // Configuration initialization
19450 config = config || {};
19451
19452 // Parent constructor
19453 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
19454
19455 // Properties (must be set before mixin constructors)
19456 this.inputWidget = inputWidget; // For backwards compatibility
19457 this.$container = config.$container || this.inputWidget.$element;
19458
19459 // Mixins constructors
19460 OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) );
19461
19462 // Initialization
19463 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
19464 // For backwards compatibility
19465 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
19466 };
19467
19468 /* Setup */
19469
19470 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
19471 OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement );
19472
19473 // For backwards compatibility
19474 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
19475
19476 /* Methods */
19477
19478 /**
19479 * @inheritdoc
19480 */
19481 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
19482 var change;
19483 visible = visible === undefined ? !this.isVisible() : !!visible;
19484 change = visible !== this.isVisible();
19485
19486 if ( change && visible ) {
19487 // Make sure the width is set before the parent method runs.
19488 this.setIdealSize( this.$container.width() );
19489 }
19490
19491 // Parent method
19492 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19493 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
19494
19495 if ( change ) {
19496 this.togglePositioning( this.isVisible() );
19497 }
19498
19499 return this;
19500 };
19501
19502 /**
19503 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19504 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19505 *
19506 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19507 *
19508 * @class
19509 * @extends OO.ui.SelectWidget
19510 * @mixins OO.ui.mixin.TabIndexedElement
19511 *
19512 * @constructor
19513 * @param {Object} [config] Configuration options
19514 */
19515 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
19516 // Parent constructor
19517 OO.ui.OutlineSelectWidget.parent.call( this, config );
19518
19519 // Mixin constructors
19520 OO.ui.mixin.TabIndexedElement.call( this, config );
19521
19522 // Events
19523 this.$element.on( {
19524 focus: this.bindKeyDownListener.bind( this ),
19525 blur: this.unbindKeyDownListener.bind( this )
19526 } );
19527
19528 // Initialization
19529 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
19530 };
19531
19532 /* Setup */
19533
19534 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
19535 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
19536
19537 /**
19538 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19539 *
19540 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19541 *
19542 * @class
19543 * @extends OO.ui.SelectWidget
19544 * @mixins OO.ui.mixin.TabIndexedElement
19545 *
19546 * @constructor
19547 * @param {Object} [config] Configuration options
19548 */
19549 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
19550 // Parent constructor
19551 OO.ui.TabSelectWidget.parent.call( this, config );
19552
19553 // Mixin constructors
19554 OO.ui.mixin.TabIndexedElement.call( this, config );
19555
19556 // Events
19557 this.$element.on( {
19558 focus: this.bindKeyDownListener.bind( this ),
19559 blur: this.unbindKeyDownListener.bind( this )
19560 } );
19561
19562 // Initialization
19563 this.$element.addClass( 'oo-ui-tabSelectWidget' );
19564 };
19565
19566 /* Setup */
19567
19568 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
19569 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
19570
19571 /**
19572 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19573 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19574 * (to adjust the value in increments) to allow the user to enter a number.
19575 *
19576 * @example
19577 * // Example: A NumberInputWidget.
19578 * var numberInput = new OO.ui.NumberInputWidget( {
19579 * label: 'NumberInputWidget',
19580 * input: { value: 5, min: 1, max: 10 }
19581 * } );
19582 * $( 'body' ).append( numberInput.$element );
19583 *
19584 * @class
19585 * @extends OO.ui.Widget
19586 *
19587 * @constructor
19588 * @param {Object} [config] Configuration options
19589 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19590 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19591 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19592 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19593 * @cfg {number} [min=-Infinity] Minimum allowed value
19594 * @cfg {number} [max=Infinity] Maximum allowed value
19595 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19596 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19597 */
19598 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
19599 // Configuration initialization
19600 config = $.extend( {
19601 isInteger: false,
19602 min: -Infinity,
19603 max: Infinity,
19604 step: 1,
19605 pageStep: null
19606 }, config );
19607
19608 // Parent constructor
19609 OO.ui.NumberInputWidget.parent.call( this, config );
19610
19611 // Properties
19612 this.input = new OO.ui.TextInputWidget( $.extend(
19613 {
19614 disabled: this.isDisabled()
19615 },
19616 config.input
19617 ) );
19618 this.minusButton = new OO.ui.ButtonWidget( $.extend(
19619 {
19620 disabled: this.isDisabled(),
19621 tabIndex: -1
19622 },
19623 config.minusButton,
19624 {
19625 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
19626 label: '−'
19627 }
19628 ) );
19629 this.plusButton = new OO.ui.ButtonWidget( $.extend(
19630 {
19631 disabled: this.isDisabled(),
19632 tabIndex: -1
19633 },
19634 config.plusButton,
19635 {
19636 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19637 label: '+'
19638 }
19639 ) );
19640
19641 // Events
19642 this.input.connect( this, {
19643 change: this.emit.bind( this, 'change' ),
19644 enter: this.emit.bind( this, 'enter' )
19645 } );
19646 this.input.$input.on( {
19647 keydown: this.onKeyDown.bind( this ),
19648 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19649 } );
19650 this.plusButton.connect( this, {
19651 click: [ 'onButtonClick', +1 ]
19652 } );
19653 this.minusButton.connect( this, {
19654 click: [ 'onButtonClick', -1 ]
19655 } );
19656
19657 // Initialization
19658 this.setIsInteger( !!config.isInteger );
19659 this.setRange( config.min, config.max );
19660 this.setStep( config.step, config.pageStep );
19661
19662 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19663 .append(
19664 this.minusButton.$element,
19665 this.input.$element,
19666 this.plusButton.$element
19667 );
19668 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19669 this.input.setValidation( this.validateNumber.bind( this ) );
19670 };
19671
19672 /* Setup */
19673
19674 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19675
19676 /* Events */
19677
19678 /**
19679 * A `change` event is emitted when the value of the input changes.
19680 *
19681 * @event change
19682 */
19683
19684 /**
19685 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19686 *
19687 * @event enter
19688 */
19689
19690 /* Methods */
19691
19692 /**
19693 * Set whether only integers are allowed
19694 * @param {boolean} flag
19695 */
19696 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19697 this.isInteger = !!flag;
19698 this.input.setValidityFlag();
19699 };
19700
19701 /**
19702 * Get whether only integers are allowed
19703 * @return {boolean} Flag value
19704 */
19705 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19706 return this.isInteger;
19707 };
19708
19709 /**
19710 * Set the range of allowed values
19711 * @param {number} min Minimum allowed value
19712 * @param {number} max Maximum allowed value
19713 */
19714 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19715 if ( min > max ) {
19716 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19717 }
19718 this.min = min;
19719 this.max = max;
19720 this.input.setValidityFlag();
19721 };
19722
19723 /**
19724 * Get the current range
19725 * @return {number[]} Minimum and maximum values
19726 */
19727 OO.ui.NumberInputWidget.prototype.getRange = function () {
19728 return [ this.min, this.max ];
19729 };
19730
19731 /**
19732 * Set the stepping deltas
19733 * @param {number} step Normal step
19734 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19735 */
19736 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19737 if ( step <= 0 ) {
19738 throw new Error( 'Step value must be positive' );
19739 }
19740 if ( pageStep === null ) {
19741 pageStep = step * 10;
19742 } else if ( pageStep <= 0 ) {
19743 throw new Error( 'Page step value must be positive' );
19744 }
19745 this.step = step;
19746 this.pageStep = pageStep;
19747 };
19748
19749 /**
19750 * Get the current stepping values
19751 * @return {number[]} Step and page step
19752 */
19753 OO.ui.NumberInputWidget.prototype.getStep = function () {
19754 return [ this.step, this.pageStep ];
19755 };
19756
19757 /**
19758 * Get the current value of the widget
19759 * @return {string}
19760 */
19761 OO.ui.NumberInputWidget.prototype.getValue = function () {
19762 return this.input.getValue();
19763 };
19764
19765 /**
19766 * Get the current value of the widget as a number
19767 * @return {number} May be NaN, or an invalid number
19768 */
19769 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19770 return +this.input.getValue();
19771 };
19772
19773 /**
19774 * Set the value of the widget
19775 * @param {string} value Invalid values are allowed
19776 */
19777 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19778 this.input.setValue( value );
19779 };
19780
19781 /**
19782 * Adjust the value of the widget
19783 * @param {number} delta Adjustment amount
19784 */
19785 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19786 var n, v = this.getNumericValue();
19787
19788 delta = +delta;
19789 if ( isNaN( delta ) || !isFinite( delta ) ) {
19790 throw new Error( 'Delta must be a finite number' );
19791 }
19792
19793 if ( isNaN( v ) ) {
19794 n = 0;
19795 } else {
19796 n = v + delta;
19797 n = Math.max( Math.min( n, this.max ), this.min );
19798 if ( this.isInteger ) {
19799 n = Math.round( n );
19800 }
19801 }
19802
19803 if ( n !== v ) {
19804 this.setValue( n );
19805 }
19806 };
19807
19808 /**
19809 * Validate input
19810 * @private
19811 * @param {string} value Field value
19812 * @return {boolean}
19813 */
19814 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19815 var n = +value;
19816 if ( isNaN( n ) || !isFinite( n ) ) {
19817 return false;
19818 }
19819
19820 /*jshint bitwise: false */
19821 if ( this.isInteger && ( n | 0 ) !== n ) {
19822 return false;
19823 }
19824 /*jshint bitwise: true */
19825
19826 if ( n < this.min || n > this.max ) {
19827 return false;
19828 }
19829
19830 return true;
19831 };
19832
19833 /**
19834 * Handle mouse click events.
19835 *
19836 * @private
19837 * @param {number} dir +1 or -1
19838 */
19839 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19840 this.adjustValue( dir * this.step );
19841 };
19842
19843 /**
19844 * Handle mouse wheel events.
19845 *
19846 * @private
19847 * @param {jQuery.Event} event
19848 */
19849 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19850 var delta = 0;
19851
19852 // Standard 'wheel' event
19853 if ( event.originalEvent.deltaMode !== undefined ) {
19854 this.sawWheelEvent = true;
19855 }
19856 if ( event.originalEvent.deltaY ) {
19857 delta = -event.originalEvent.deltaY;
19858 } else if ( event.originalEvent.deltaX ) {
19859 delta = event.originalEvent.deltaX;
19860 }
19861
19862 // Non-standard events
19863 if ( !this.sawWheelEvent ) {
19864 if ( event.originalEvent.wheelDeltaX ) {
19865 delta = -event.originalEvent.wheelDeltaX;
19866 } else if ( event.originalEvent.wheelDeltaY ) {
19867 delta = event.originalEvent.wheelDeltaY;
19868 } else if ( event.originalEvent.wheelDelta ) {
19869 delta = event.originalEvent.wheelDelta;
19870 } else if ( event.originalEvent.detail ) {
19871 delta = -event.originalEvent.detail;
19872 }
19873 }
19874
19875 if ( delta ) {
19876 delta = delta < 0 ? -1 : 1;
19877 this.adjustValue( delta * this.step );
19878 }
19879
19880 return false;
19881 };
19882
19883 /**
19884 * Handle key down events.
19885 *
19886 * @private
19887 * @param {jQuery.Event} e Key down event
19888 */
19889 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19890 if ( !this.isDisabled() ) {
19891 switch ( e.which ) {
19892 case OO.ui.Keys.UP:
19893 this.adjustValue( this.step );
19894 return false;
19895 case OO.ui.Keys.DOWN:
19896 this.adjustValue( -this.step );
19897 return false;
19898 case OO.ui.Keys.PAGEUP:
19899 this.adjustValue( this.pageStep );
19900 return false;
19901 case OO.ui.Keys.PAGEDOWN:
19902 this.adjustValue( -this.pageStep );
19903 return false;
19904 }
19905 }
19906 };
19907
19908 /**
19909 * @inheritdoc
19910 */
19911 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19912 // Parent method
19913 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19914
19915 if ( this.input ) {
19916 this.input.setDisabled( this.isDisabled() );
19917 }
19918 if ( this.minusButton ) {
19919 this.minusButton.setDisabled( this.isDisabled() );
19920 }
19921 if ( this.plusButton ) {
19922 this.plusButton.setDisabled( this.isDisabled() );
19923 }
19924
19925 return this;
19926 };
19927
19928 /**
19929 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19930 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19931 * visually by a slider in the leftmost position.
19932 *
19933 * @example
19934 * // Toggle switches in the 'off' and 'on' position.
19935 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19936 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19937 * value: true
19938 * } );
19939 *
19940 * // Create a FieldsetLayout to layout and label switches
19941 * var fieldset = new OO.ui.FieldsetLayout( {
19942 * label: 'Toggle switches'
19943 * } );
19944 * fieldset.addItems( [
19945 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19946 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19947 * ] );
19948 * $( 'body' ).append( fieldset.$element );
19949 *
19950 * @class
19951 * @extends OO.ui.ToggleWidget
19952 * @mixins OO.ui.mixin.TabIndexedElement
19953 *
19954 * @constructor
19955 * @param {Object} [config] Configuration options
19956 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19957 * By default, the toggle switch is in the 'off' position.
19958 */
19959 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19960 // Parent constructor
19961 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19962
19963 // Mixin constructors
19964 OO.ui.mixin.TabIndexedElement.call( this, config );
19965
19966 // Properties
19967 this.dragging = false;
19968 this.dragStart = null;
19969 this.sliding = false;
19970 this.$glow = $( '<span>' );
19971 this.$grip = $( '<span>' );
19972
19973 // Events
19974 this.$element.on( {
19975 click: this.onClick.bind( this ),
19976 keypress: this.onKeyPress.bind( this )
19977 } );
19978
19979 // Initialization
19980 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19981 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19982 this.$element
19983 .addClass( 'oo-ui-toggleSwitchWidget' )
19984 .attr( 'role', 'checkbox' )
19985 .append( this.$glow, this.$grip );
19986 };
19987
19988 /* Setup */
19989
19990 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19991 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19992
19993 /* Methods */
19994
19995 /**
19996 * Handle mouse click events.
19997 *
19998 * @private
19999 * @param {jQuery.Event} e Mouse click event
20000 */
20001 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
20002 if ( !this.isDisabled() && e.which === 1 ) {
20003 this.setValue( !this.value );
20004 }
20005 return false;
20006 };
20007
20008 /**
20009 * Handle key press events.
20010 *
20011 * @private
20012 * @param {jQuery.Event} e Key press event
20013 */
20014 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
20015 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
20016 this.setValue( !this.value );
20017 return false;
20018 }
20019 };
20020
20021 }( OO ) );