Update OOjs UI to v0.12.6
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.6
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-08-26T00:14:36Z
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 node = $element[ 0 ],
71 nodeName = node.nodeName.toLowerCase(),
72 // Check if the element have tabindex set
73 isInElementGroup = /^(input|select|textarea|button|object)$/.test( nodeName ),
74 // Check if the element is a link with href or if it has tabindex
75 isOtherElement = (
76 ( nodeName === 'a' && node.href ) ||
77 !isNaN( $element.attr( 'tabindex' ) )
78 ),
79 // Check if the element is visible
80 isVisible = (
81 // This is quicker than calling $element.is( ':visible' )
82 $.expr.filters.visible( node ) &&
83 // Check that all parents are visible
84 !$element.parents().addBack().filter( function () {
85 return $.css( this, 'visibility' ) === 'hidden';
86 } ).length
87 ),
88 isTabOk = isNaN( $element.attr( 'tabindex' ) ) || +$element.attr( 'tabindex' ) >= 0;
89
90 return (
91 ( isInElementGroup ? !node.disabled : isOtherElement ) &&
92 isVisible && isTabOk
93 );
94 };
95
96 /**
97 * Get the user's language and any fallback languages.
98 *
99 * These language codes are used to localize user interface elements in the user's language.
100 *
101 * In environments that provide a localization system, this function should be overridden to
102 * return the user's language(s). The default implementation returns English (en) only.
103 *
104 * @return {string[]} Language codes, in descending order of priority
105 */
106 OO.ui.getUserLanguages = function () {
107 return [ 'en' ];
108 };
109
110 /**
111 * Get a value in an object keyed by language code.
112 *
113 * @param {Object.<string,Mixed>} obj Object keyed by language code
114 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
115 * @param {string} [fallback] Fallback code, used if no matching language can be found
116 * @return {Mixed} Local value
117 */
118 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
119 var i, len, langs;
120
121 // Requested language
122 if ( obj[ lang ] ) {
123 return obj[ lang ];
124 }
125 // Known user language
126 langs = OO.ui.getUserLanguages();
127 for ( i = 0, len = langs.length; i < len; i++ ) {
128 lang = langs[ i ];
129 if ( obj[ lang ] ) {
130 return obj[ lang ];
131 }
132 }
133 // Fallback language
134 if ( obj[ fallback ] ) {
135 return obj[ fallback ];
136 }
137 // First existing language
138 for ( lang in obj ) {
139 return obj[ lang ];
140 }
141
142 return undefined;
143 };
144
145 /**
146 * Check if a node is contained within another node
147 *
148 * Similar to jQuery#contains except a list of containers can be supplied
149 * and a boolean argument allows you to include the container in the match list
150 *
151 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
152 * @param {HTMLElement} contained Node to find
153 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
154 * @return {boolean} The node is in the list of target nodes
155 */
156 OO.ui.contains = function ( containers, contained, matchContainers ) {
157 var i;
158 if ( !Array.isArray( containers ) ) {
159 containers = [ containers ];
160 }
161 for ( i = containers.length - 1; i >= 0; i-- ) {
162 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
163 return true;
164 }
165 }
166 return false;
167 };
168
169 /**
170 * Return a function, that, as long as it continues to be invoked, will not
171 * be triggered. The function will be called after it stops being called for
172 * N milliseconds. If `immediate` is passed, trigger the function on the
173 * leading edge, instead of the trailing.
174 *
175 * Ported from: http://underscorejs.org/underscore.js
176 *
177 * @param {Function} func
178 * @param {number} wait
179 * @param {boolean} immediate
180 * @return {Function}
181 */
182 OO.ui.debounce = function ( func, wait, immediate ) {
183 var timeout;
184 return function () {
185 var context = this,
186 args = arguments,
187 later = function () {
188 timeout = null;
189 if ( !immediate ) {
190 func.apply( context, args );
191 }
192 };
193 if ( immediate && !timeout ) {
194 func.apply( context, args );
195 }
196 clearTimeout( timeout );
197 timeout = setTimeout( later, wait );
198 };
199 };
200
201 /**
202 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
203 * Otherwise falls back to non-capturing event listeners.
204 *
205 * @param {HTMLElement} node
206 * @param {string} eventName
207 * @param {Function} handler
208 */
209 OO.ui.addCaptureEventListener = function ( node, eventName, handler ) {
210 if ( node.addEventListener ) {
211 node.addEventListener( eventName, handler, true );
212 } else {
213 node.attachEvent( 'on' + eventName, handler );
214 }
215 };
216
217 /**
218 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
219 * Otherwise falls back to non-capturing event listeners.
220 *
221 * @param {HTMLElement} node
222 * @param {string} eventName
223 * @param {Function} handler
224 */
225 OO.ui.removeCaptureEventListener = function ( node, eventName, handler ) {
226 if ( node.addEventListener ) {
227 node.removeEventListener( eventName, handler, true );
228 } else {
229 node.detachEvent( 'on' + eventName, handler );
230 }
231 };
232
233 /**
234 * Reconstitute a JavaScript object corresponding to a widget created by
235 * the PHP implementation.
236 *
237 * This is an alias for `OO.ui.Element.static.infuse()`.
238 *
239 * @param {string|HTMLElement|jQuery} idOrNode
240 * A DOM id (if a string) or node for the widget to infuse.
241 * @return {OO.ui.Element}
242 * The `OO.ui.Element` corresponding to this (infusable) document node.
243 */
244 OO.ui.infuse = function ( idOrNode ) {
245 return OO.ui.Element.static.infuse( idOrNode );
246 };
247
248 ( function () {
249 /**
250 * Message store for the default implementation of OO.ui.msg
251 *
252 * Environments that provide a localization system should not use this, but should override
253 * OO.ui.msg altogether.
254 *
255 * @private
256 */
257 var messages = {
258 // Tool tip for a button that moves items in a list down one place
259 'ooui-outline-control-move-down': 'Move item down',
260 // Tool tip for a button that moves items in a list up one place
261 'ooui-outline-control-move-up': 'Move item up',
262 // Tool tip for a button that removes items from a list
263 'ooui-outline-control-remove': 'Remove item',
264 // Label for the toolbar group that contains a list of all other available tools
265 'ooui-toolbar-more': 'More',
266 // Label for the fake tool that expands the full list of tools in a toolbar group
267 'ooui-toolgroup-expand': 'More',
268 // Label for the fake tool that collapses the full list of tools in a toolbar group
269 'ooui-toolgroup-collapse': 'Fewer',
270 // Default label for the accept button of a confirmation dialog
271 'ooui-dialog-message-accept': 'OK',
272 // Default label for the reject button of a confirmation dialog
273 'ooui-dialog-message-reject': 'Cancel',
274 // Title for process dialog error description
275 'ooui-dialog-process-error': 'Something went wrong',
276 // Label for process dialog dismiss error button, visible when describing errors
277 'ooui-dialog-process-dismiss': 'Dismiss',
278 // Label for process dialog retry action button, visible when describing only recoverable errors
279 'ooui-dialog-process-retry': 'Try again',
280 // Label for process dialog retry action button, visible when describing only warnings
281 'ooui-dialog-process-continue': 'Continue',
282 // Default placeholder for file selection widgets
283 'ooui-selectfile-not-supported': 'File selection is not supported',
284 // Default placeholder for file selection widgets
285 'ooui-selectfile-placeholder': 'No file is selected',
286 // Default placeholder for file selection widgets when using drag drop UI
287 'ooui-selectfile-dragdrop-placeholder': 'Drop file here (or click to browse)',
288 // Semicolon separator
289 'ooui-semicolon-separator': '; '
290 };
291
292 /**
293 * Get a localized message.
294 *
295 * In environments that provide a localization system, this function should be overridden to
296 * return the message translated in the user's language. The default implementation always returns
297 * English messages.
298 *
299 * After the message key, message parameters may optionally be passed. In the default implementation,
300 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
301 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
302 * they support unnamed, ordered message parameters.
303 *
304 * @abstract
305 * @param {string} key Message key
306 * @param {Mixed...} [params] Message parameters
307 * @return {string} Translated message with parameters substituted
308 */
309 OO.ui.msg = function ( key ) {
310 var message = messages[ key ],
311 params = Array.prototype.slice.call( arguments, 1 );
312 if ( typeof message === 'string' ) {
313 // Perform $1 substitution
314 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
315 var i = parseInt( n, 10 );
316 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
317 } );
318 } else {
319 // Return placeholder if message not found
320 message = '[' + key + ']';
321 }
322 return message;
323 };
324
325 /**
326 * Package a message and arguments for deferred resolution.
327 *
328 * Use this when you are statically specifying a message and the message may not yet be present.
329 *
330 * @param {string} key Message key
331 * @param {Mixed...} [params] Message parameters
332 * @return {Function} Function that returns the resolved message when executed
333 */
334 OO.ui.deferMsg = function () {
335 var args = arguments;
336 return function () {
337 return OO.ui.msg.apply( OO.ui, args );
338 };
339 };
340
341 /**
342 * Resolve a message.
343 *
344 * If the message is a function it will be executed, otherwise it will pass through directly.
345 *
346 * @param {Function|string} msg Deferred message, or message text
347 * @return {string} Resolved message
348 */
349 OO.ui.resolveMsg = function ( msg ) {
350 if ( $.isFunction( msg ) ) {
351 return msg();
352 }
353 return msg;
354 };
355
356 /**
357 * @param {string} url
358 * @return {boolean}
359 */
360 OO.ui.isSafeUrl = function ( url ) {
361 var protocol,
362 // Keep in sync with php/Tag.php
363 whitelist = [
364 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
365 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
366 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
367 ];
368
369 if ( url.indexOf( ':' ) === -1 ) {
370 // No protocol, safe
371 return true;
372 }
373
374 protocol = url.split( ':', 1 )[ 0 ] + ':';
375 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
376 // Not a valid protocol, safe
377 return true;
378 }
379
380 // Safe if in the whitelist
381 return whitelist.indexOf( protocol ) !== -1;
382 };
383
384 } )();
385
386 /*!
387 * Mixin namespace.
388 */
389
390 /**
391 * Namespace for OOjs UI mixins.
392 *
393 * Mixins are named according to the type of object they are intended to
394 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
395 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
396 * is intended to be mixed in to an instance of OO.ui.Widget.
397 *
398 * @class
399 * @singleton
400 */
401 OO.ui.mixin = {};
402
403 /**
404 * PendingElement is a mixin that is used to create elements that notify users that something is happening
405 * and that they should wait before proceeding. The pending state is visually represented with a pending
406 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
407 * field of a {@link OO.ui.TextInputWidget text input widget}.
408 *
409 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
410 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
411 * in process dialogs.
412 *
413 * @example
414 * function MessageDialog( config ) {
415 * MessageDialog.parent.call( this, config );
416 * }
417 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
418 *
419 * MessageDialog.static.actions = [
420 * { action: 'save', label: 'Done', flags: 'primary' },
421 * { label: 'Cancel', flags: 'safe' }
422 * ];
423 *
424 * MessageDialog.prototype.initialize = function () {
425 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
426 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
427 * 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>' );
428 * this.$body.append( this.content.$element );
429 * };
430 * MessageDialog.prototype.getBodyHeight = function () {
431 * return 100;
432 * }
433 * MessageDialog.prototype.getActionProcess = function ( action ) {
434 * var dialog = this;
435 * if ( action === 'save' ) {
436 * dialog.getActions().get({actions: 'save'})[0].pushPending();
437 * return new OO.ui.Process()
438 * .next( 1000 )
439 * .next( function () {
440 * dialog.getActions().get({actions: 'save'})[0].popPending();
441 * } );
442 * }
443 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
444 * };
445 *
446 * var windowManager = new OO.ui.WindowManager();
447 * $( 'body' ).append( windowManager.$element );
448 *
449 * var dialog = new MessageDialog();
450 * windowManager.addWindows( [ dialog ] );
451 * windowManager.openWindow( dialog );
452 *
453 * @abstract
454 * @class
455 *
456 * @constructor
457 * @param {Object} [config] Configuration options
458 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
459 */
460 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
461 // Configuration initialization
462 config = config || {};
463
464 // Properties
465 this.pending = 0;
466 this.$pending = null;
467
468 // Initialisation
469 this.setPendingElement( config.$pending || this.$element );
470 };
471
472 /* Setup */
473
474 OO.initClass( OO.ui.mixin.PendingElement );
475
476 /* Methods */
477
478 /**
479 * Set the pending element (and clean up any existing one).
480 *
481 * @param {jQuery} $pending The element to set to pending.
482 */
483 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
484 if ( this.$pending ) {
485 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
486 }
487
488 this.$pending = $pending;
489 if ( this.pending > 0 ) {
490 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
491 }
492 };
493
494 /**
495 * Check if an element is pending.
496 *
497 * @return {boolean} Element is pending
498 */
499 OO.ui.mixin.PendingElement.prototype.isPending = function () {
500 return !!this.pending;
501 };
502
503 /**
504 * Increase the pending counter. The pending state will remain active until the counter is zero
505 * (i.e., the number of calls to #pushPending and #popPending is the same).
506 *
507 * @chainable
508 */
509 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
510 if ( this.pending === 0 ) {
511 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
512 this.updateThemeClasses();
513 }
514 this.pending++;
515
516 return this;
517 };
518
519 /**
520 * Decrease the pending counter. The pending state will remain active until the counter is zero
521 * (i.e., the number of calls to #pushPending and #popPending is the same).
522 *
523 * @chainable
524 */
525 OO.ui.mixin.PendingElement.prototype.popPending = function () {
526 if ( this.pending === 1 ) {
527 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
528 this.updateThemeClasses();
529 }
530 this.pending = Math.max( 0, this.pending - 1 );
531
532 return this;
533 };
534
535 /**
536 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
537 * Actions can be made available for specific contexts (modes) and circumstances
538 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
539 *
540 * ActionSets contain two types of actions:
541 *
542 * - 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.
543 * - Other: Other actions include all non-special visible actions.
544 *
545 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
546 *
547 * @example
548 * // Example: An action set used in a process dialog
549 * function MyProcessDialog( config ) {
550 * MyProcessDialog.parent.call( this, config );
551 * }
552 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
553 * MyProcessDialog.static.title = 'An action set in a process dialog';
554 * // An action set that uses modes ('edit' and 'help' mode, in this example).
555 * MyProcessDialog.static.actions = [
556 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
557 * { action: 'help', modes: 'edit', label: 'Help' },
558 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
559 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
560 * ];
561 *
562 * MyProcessDialog.prototype.initialize = function () {
563 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
564 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
565 * 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>' );
566 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
567 * 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>' );
568 * this.stackLayout = new OO.ui.StackLayout( {
569 * items: [ this.panel1, this.panel2 ]
570 * } );
571 * this.$body.append( this.stackLayout.$element );
572 * };
573 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
574 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
575 * .next( function () {
576 * this.actions.setMode( 'edit' );
577 * }, this );
578 * };
579 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
580 * if ( action === 'help' ) {
581 * this.actions.setMode( 'help' );
582 * this.stackLayout.setItem( this.panel2 );
583 * } else if ( action === 'back' ) {
584 * this.actions.setMode( 'edit' );
585 * this.stackLayout.setItem( this.panel1 );
586 * } else if ( action === 'continue' ) {
587 * var dialog = this;
588 * return new OO.ui.Process( function () {
589 * dialog.close();
590 * } );
591 * }
592 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
593 * };
594 * MyProcessDialog.prototype.getBodyHeight = function () {
595 * return this.panel1.$element.outerHeight( true );
596 * };
597 * var windowManager = new OO.ui.WindowManager();
598 * $( 'body' ).append( windowManager.$element );
599 * var dialog = new MyProcessDialog( {
600 * size: 'medium'
601 * } );
602 * windowManager.addWindows( [ dialog ] );
603 * windowManager.openWindow( dialog );
604 *
605 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
606 *
607 * @abstract
608 * @class
609 * @mixins OO.EventEmitter
610 *
611 * @constructor
612 * @param {Object} [config] Configuration options
613 */
614 OO.ui.ActionSet = function OoUiActionSet( config ) {
615 // Configuration initialization
616 config = config || {};
617
618 // Mixin constructors
619 OO.EventEmitter.call( this );
620
621 // Properties
622 this.list = [];
623 this.categories = {
624 actions: 'getAction',
625 flags: 'getFlags',
626 modes: 'getModes'
627 };
628 this.categorized = {};
629 this.special = {};
630 this.others = [];
631 this.organized = false;
632 this.changing = false;
633 this.changed = false;
634 };
635
636 /* Setup */
637
638 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
639
640 /* Static Properties */
641
642 /**
643 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
644 * header of a {@link OO.ui.ProcessDialog process dialog}.
645 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
646 *
647 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
648 *
649 * @abstract
650 * @static
651 * @inheritable
652 * @property {string}
653 */
654 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
655
656 /* Events */
657
658 /**
659 * @event click
660 *
661 * A 'click' event is emitted when an action is clicked.
662 *
663 * @param {OO.ui.ActionWidget} action Action that was clicked
664 */
665
666 /**
667 * @event resize
668 *
669 * A 'resize' event is emitted when an action widget is resized.
670 *
671 * @param {OO.ui.ActionWidget} action Action that was resized
672 */
673
674 /**
675 * @event add
676 *
677 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
678 *
679 * @param {OO.ui.ActionWidget[]} added Actions added
680 */
681
682 /**
683 * @event remove
684 *
685 * A 'remove' event is emitted when actions are {@link #method-remove removed}
686 * or {@link #clear cleared}.
687 *
688 * @param {OO.ui.ActionWidget[]} added Actions removed
689 */
690
691 /**
692 * @event change
693 *
694 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
695 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
696 *
697 */
698
699 /* Methods */
700
701 /**
702 * Handle action change events.
703 *
704 * @private
705 * @fires change
706 */
707 OO.ui.ActionSet.prototype.onActionChange = function () {
708 this.organized = false;
709 if ( this.changing ) {
710 this.changed = true;
711 } else {
712 this.emit( 'change' );
713 }
714 };
715
716 /**
717 * Check if an action is one of the special actions.
718 *
719 * @param {OO.ui.ActionWidget} action Action to check
720 * @return {boolean} Action is special
721 */
722 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
723 var flag;
724
725 for ( flag in this.special ) {
726 if ( action === this.special[ flag ] ) {
727 return true;
728 }
729 }
730
731 return false;
732 };
733
734 /**
735 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
736 * or ‘disabled’.
737 *
738 * @param {Object} [filters] Filters to use, omit to get all actions
739 * @param {string|string[]} [filters.actions] Actions that action widgets must have
740 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
741 * @param {string|string[]} [filters.modes] Modes that action widgets must have
742 * @param {boolean} [filters.visible] Action widgets must be visible
743 * @param {boolean} [filters.disabled] Action widgets must be disabled
744 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
745 */
746 OO.ui.ActionSet.prototype.get = function ( filters ) {
747 var i, len, list, category, actions, index, match, matches;
748
749 if ( filters ) {
750 this.organize();
751
752 // Collect category candidates
753 matches = [];
754 for ( category in this.categorized ) {
755 list = filters[ category ];
756 if ( list ) {
757 if ( !Array.isArray( list ) ) {
758 list = [ list ];
759 }
760 for ( i = 0, len = list.length; i < len; i++ ) {
761 actions = this.categorized[ category ][ list[ i ] ];
762 if ( Array.isArray( actions ) ) {
763 matches.push.apply( matches, actions );
764 }
765 }
766 }
767 }
768 // Remove by boolean filters
769 for ( i = 0, len = matches.length; i < len; i++ ) {
770 match = matches[ i ];
771 if (
772 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
773 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
774 ) {
775 matches.splice( i, 1 );
776 len--;
777 i--;
778 }
779 }
780 // Remove duplicates
781 for ( i = 0, len = matches.length; i < len; i++ ) {
782 match = matches[ i ];
783 index = matches.lastIndexOf( match );
784 while ( index !== i ) {
785 matches.splice( index, 1 );
786 len--;
787 index = matches.lastIndexOf( match );
788 }
789 }
790 return matches;
791 }
792 return this.list.slice();
793 };
794
795 /**
796 * Get 'special' actions.
797 *
798 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
799 * Special flags can be configured in subclasses by changing the static #specialFlags property.
800 *
801 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
802 */
803 OO.ui.ActionSet.prototype.getSpecial = function () {
804 this.organize();
805 return $.extend( {}, this.special );
806 };
807
808 /**
809 * Get 'other' actions.
810 *
811 * Other actions include all non-special visible action widgets.
812 *
813 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
814 */
815 OO.ui.ActionSet.prototype.getOthers = function () {
816 this.organize();
817 return this.others.slice();
818 };
819
820 /**
821 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
822 * to be available in the specified mode will be made visible. All other actions will be hidden.
823 *
824 * @param {string} mode The mode. Only actions configured to be available in the specified
825 * mode will be made visible.
826 * @chainable
827 * @fires toggle
828 * @fires change
829 */
830 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
831 var i, len, action;
832
833 this.changing = true;
834 for ( i = 0, len = this.list.length; i < len; i++ ) {
835 action = this.list[ i ];
836 action.toggle( action.hasMode( mode ) );
837 }
838
839 this.organized = false;
840 this.changing = false;
841 this.emit( 'change' );
842
843 return this;
844 };
845
846 /**
847 * Set the abilities of the specified actions.
848 *
849 * Action widgets that are configured with the specified actions will be enabled
850 * or disabled based on the boolean values specified in the `actions`
851 * parameter.
852 *
853 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
854 * values that indicate whether or not the action should be enabled.
855 * @chainable
856 */
857 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
858 var i, len, action, item;
859
860 for ( i = 0, len = this.list.length; i < len; i++ ) {
861 item = this.list[ i ];
862 action = item.getAction();
863 if ( actions[ action ] !== undefined ) {
864 item.setDisabled( !actions[ action ] );
865 }
866 }
867
868 return this;
869 };
870
871 /**
872 * Executes a function once per action.
873 *
874 * When making changes to multiple actions, use this method instead of iterating over the actions
875 * manually to defer emitting a #change event until after all actions have been changed.
876 *
877 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
878 * @param {Function} callback Callback to run for each action; callback is invoked with three
879 * arguments: the action, the action's index, the list of actions being iterated over
880 * @chainable
881 */
882 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
883 this.changed = false;
884 this.changing = true;
885 this.get( filter ).forEach( callback );
886 this.changing = false;
887 if ( this.changed ) {
888 this.emit( 'change' );
889 }
890
891 return this;
892 };
893
894 /**
895 * Add action widgets to the action set.
896 *
897 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
898 * @chainable
899 * @fires add
900 * @fires change
901 */
902 OO.ui.ActionSet.prototype.add = function ( actions ) {
903 var i, len, action;
904
905 this.changing = true;
906 for ( i = 0, len = actions.length; i < len; i++ ) {
907 action = actions[ i ];
908 action.connect( this, {
909 click: [ 'emit', 'click', action ],
910 resize: [ 'emit', 'resize', action ],
911 toggle: [ 'onActionChange' ]
912 } );
913 this.list.push( action );
914 }
915 this.organized = false;
916 this.emit( 'add', actions );
917 this.changing = false;
918 this.emit( 'change' );
919
920 return this;
921 };
922
923 /**
924 * Remove action widgets from the set.
925 *
926 * To remove all actions, you may wish to use the #clear method instead.
927 *
928 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
929 * @chainable
930 * @fires remove
931 * @fires change
932 */
933 OO.ui.ActionSet.prototype.remove = function ( actions ) {
934 var i, len, index, action;
935
936 this.changing = true;
937 for ( i = 0, len = actions.length; i < len; i++ ) {
938 action = actions[ i ];
939 index = this.list.indexOf( action );
940 if ( index !== -1 ) {
941 action.disconnect( this );
942 this.list.splice( index, 1 );
943 }
944 }
945 this.organized = false;
946 this.emit( 'remove', actions );
947 this.changing = false;
948 this.emit( 'change' );
949
950 return this;
951 };
952
953 /**
954 * Remove all action widets from the set.
955 *
956 * To remove only specified actions, use the {@link #method-remove remove} method instead.
957 *
958 * @chainable
959 * @fires remove
960 * @fires change
961 */
962 OO.ui.ActionSet.prototype.clear = function () {
963 var i, len, action,
964 removed = this.list.slice();
965
966 this.changing = true;
967 for ( i = 0, len = this.list.length; i < len; i++ ) {
968 action = this.list[ i ];
969 action.disconnect( this );
970 }
971
972 this.list = [];
973
974 this.organized = false;
975 this.emit( 'remove', removed );
976 this.changing = false;
977 this.emit( 'change' );
978
979 return this;
980 };
981
982 /**
983 * Organize actions.
984 *
985 * This is called whenever organized information is requested. It will only reorganize the actions
986 * if something has changed since the last time it ran.
987 *
988 * @private
989 * @chainable
990 */
991 OO.ui.ActionSet.prototype.organize = function () {
992 var i, iLen, j, jLen, flag, action, category, list, item, special,
993 specialFlags = this.constructor.static.specialFlags;
994
995 if ( !this.organized ) {
996 this.categorized = {};
997 this.special = {};
998 this.others = [];
999 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1000 action = this.list[ i ];
1001 if ( action.isVisible() ) {
1002 // Populate categories
1003 for ( category in this.categories ) {
1004 if ( !this.categorized[ category ] ) {
1005 this.categorized[ category ] = {};
1006 }
1007 list = action[ this.categories[ category ] ]();
1008 if ( !Array.isArray( list ) ) {
1009 list = [ list ];
1010 }
1011 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1012 item = list[ j ];
1013 if ( !this.categorized[ category ][ item ] ) {
1014 this.categorized[ category ][ item ] = [];
1015 }
1016 this.categorized[ category ][ item ].push( action );
1017 }
1018 }
1019 // Populate special/others
1020 special = false;
1021 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1022 flag = specialFlags[ j ];
1023 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1024 this.special[ flag ] = action;
1025 special = true;
1026 break;
1027 }
1028 }
1029 if ( !special ) {
1030 this.others.push( action );
1031 }
1032 }
1033 }
1034 this.organized = true;
1035 }
1036
1037 return this;
1038 };
1039
1040 /**
1041 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1042 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1043 * connected to them and can't be interacted with.
1044 *
1045 * @abstract
1046 * @class
1047 *
1048 * @constructor
1049 * @param {Object} [config] Configuration options
1050 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1051 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1052 * for an example.
1053 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1054 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1055 * @cfg {string} [text] Text to insert
1056 * @cfg {Array} [content] An array of content elements to append (after #text).
1057 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1058 * Instances of OO.ui.Element will have their $element appended.
1059 * @cfg {jQuery} [$content] Content elements to append (after #text)
1060 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1061 * Data can also be specified with the #setData method.
1062 */
1063 OO.ui.Element = function OoUiElement( config ) {
1064 // Configuration initialization
1065 config = config || {};
1066
1067 // Properties
1068 this.$ = $;
1069 this.visible = true;
1070 this.data = config.data;
1071 this.$element = config.$element ||
1072 $( document.createElement( this.getTagName() ) );
1073 this.elementGroup = null;
1074 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1075
1076 // Initialization
1077 if ( Array.isArray( config.classes ) ) {
1078 this.$element.addClass( config.classes.join( ' ' ) );
1079 }
1080 if ( config.id ) {
1081 this.$element.attr( 'id', config.id );
1082 }
1083 if ( config.text ) {
1084 this.$element.text( config.text );
1085 }
1086 if ( config.content ) {
1087 // The `content` property treats plain strings as text; use an
1088 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1089 // appropriate $element appended.
1090 this.$element.append( config.content.map( function ( v ) {
1091 if ( typeof v === 'string' ) {
1092 // Escape string so it is properly represented in HTML.
1093 return document.createTextNode( v );
1094 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1095 // Bypass escaping.
1096 return v.toString();
1097 } else if ( v instanceof OO.ui.Element ) {
1098 return v.$element;
1099 }
1100 return v;
1101 } ) );
1102 }
1103 if ( config.$content ) {
1104 // The `$content` property treats plain strings as HTML.
1105 this.$element.append( config.$content );
1106 }
1107 };
1108
1109 /* Setup */
1110
1111 OO.initClass( OO.ui.Element );
1112
1113 /* Static Properties */
1114
1115 /**
1116 * The name of the HTML tag used by the element.
1117 *
1118 * The static value may be ignored if the #getTagName method is overridden.
1119 *
1120 * @static
1121 * @inheritable
1122 * @property {string}
1123 */
1124 OO.ui.Element.static.tagName = 'div';
1125
1126 /* Static Methods */
1127
1128 /**
1129 * Reconstitute a JavaScript object corresponding to a widget created
1130 * by the PHP implementation.
1131 *
1132 * @param {string|HTMLElement|jQuery} idOrNode
1133 * A DOM id (if a string) or node for the widget to infuse.
1134 * @return {OO.ui.Element}
1135 * The `OO.ui.Element` corresponding to this (infusable) document node.
1136 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1137 * the value returned is a newly-created Element wrapping around the existing
1138 * DOM node.
1139 */
1140 OO.ui.Element.static.infuse = function ( idOrNode ) {
1141 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1142 // Verify that the type matches up.
1143 // FIXME: uncomment after T89721 is fixed (see T90929)
1144 /*
1145 if ( !( obj instanceof this['class'] ) ) {
1146 throw new Error( 'Infusion type mismatch!' );
1147 }
1148 */
1149 return obj;
1150 };
1151
1152 /**
1153 * Implementation helper for `infuse`; skips the type check and has an
1154 * extra property so that only the top-level invocation touches the DOM.
1155 * @private
1156 * @param {string|HTMLElement|jQuery} idOrNode
1157 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1158 * when the top-level widget of this infusion is inserted into DOM,
1159 * replacing the original node; or false for top-level invocation.
1160 * @return {OO.ui.Element}
1161 */
1162 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1163 // look for a cached result of a previous infusion.
1164 var id, $elem, data, cls, parts, parent, obj, top, state;
1165 if ( typeof idOrNode === 'string' ) {
1166 id = idOrNode;
1167 $elem = $( document.getElementById( id ) );
1168 } else {
1169 $elem = $( idOrNode );
1170 id = $elem.attr( 'id' );
1171 }
1172 if ( !$elem.length ) {
1173 throw new Error( 'Widget not found: ' + id );
1174 }
1175 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1176 if ( data ) {
1177 // cached!
1178 if ( data === true ) {
1179 throw new Error( 'Circular dependency! ' + id );
1180 }
1181 return data;
1182 }
1183 data = $elem.attr( 'data-ooui' );
1184 if ( !data ) {
1185 throw new Error( 'No infusion data found: ' + id );
1186 }
1187 try {
1188 data = $.parseJSON( data );
1189 } catch ( _ ) {
1190 data = null;
1191 }
1192 if ( !( data && data._ ) ) {
1193 throw new Error( 'No valid infusion data found: ' + id );
1194 }
1195 if ( data._ === 'Tag' ) {
1196 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1197 return new OO.ui.Element( { $element: $elem } );
1198 }
1199 parts = data._.split( '.' );
1200 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1201 if ( cls === undefined ) {
1202 // The PHP output might be old and not including the "OO.ui" prefix
1203 // TODO: Remove this back-compat after next major release
1204 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1205 if ( cls === undefined ) {
1206 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1207 }
1208 }
1209
1210 // Verify that we're creating an OO.ui.Element instance
1211 parent = cls.parent;
1212
1213 while ( parent !== undefined ) {
1214 if ( parent === OO.ui.Element ) {
1215 // Safe
1216 break;
1217 }
1218
1219 parent = parent.parent;
1220 }
1221
1222 if ( parent !== OO.ui.Element ) {
1223 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1224 }
1225
1226 if ( domPromise === false ) {
1227 top = $.Deferred();
1228 domPromise = top.promise();
1229 }
1230 $elem.data( 'ooui-infused', true ); // prevent loops
1231 data.id = id; // implicit
1232 data = OO.copy( data, null, function deserialize( value ) {
1233 if ( OO.isPlainObject( value ) ) {
1234 if ( value.tag ) {
1235 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1236 }
1237 if ( value.html ) {
1238 return new OO.ui.HtmlSnippet( value.html );
1239 }
1240 }
1241 } );
1242 // jscs:disable requireCapitalizedConstructors
1243 obj = new cls( data ); // rebuild widget
1244 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1245 state = obj.gatherPreInfuseState( $elem );
1246 // now replace old DOM with this new DOM.
1247 if ( top ) {
1248 $elem.replaceWith( obj.$element );
1249 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1250 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1251 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1252 $elem[ 0 ].oouiInfused = obj;
1253 top.resolve();
1254 }
1255 obj.$element.data( 'ooui-infused', obj );
1256 // set the 'data-ooui' attribute so we can identify infused widgets
1257 obj.$element.attr( 'data-ooui', '' );
1258 // restore dynamic state after the new element is inserted into DOM
1259 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1260 return obj;
1261 };
1262
1263 /**
1264 * Get a jQuery function within a specific document.
1265 *
1266 * @static
1267 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1268 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1269 * not in an iframe
1270 * @return {Function} Bound jQuery function
1271 */
1272 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1273 function wrapper( selector ) {
1274 return $( selector, wrapper.context );
1275 }
1276
1277 wrapper.context = this.getDocument( context );
1278
1279 if ( $iframe ) {
1280 wrapper.$iframe = $iframe;
1281 }
1282
1283 return wrapper;
1284 };
1285
1286 /**
1287 * Get the document of an element.
1288 *
1289 * @static
1290 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1291 * @return {HTMLDocument|null} Document object
1292 */
1293 OO.ui.Element.static.getDocument = function ( obj ) {
1294 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1295 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1296 // Empty jQuery selections might have a context
1297 obj.context ||
1298 // HTMLElement
1299 obj.ownerDocument ||
1300 // Window
1301 obj.document ||
1302 // HTMLDocument
1303 ( obj.nodeType === 9 && obj ) ||
1304 null;
1305 };
1306
1307 /**
1308 * Get the window of an element or document.
1309 *
1310 * @static
1311 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1312 * @return {Window} Window object
1313 */
1314 OO.ui.Element.static.getWindow = function ( obj ) {
1315 var doc = this.getDocument( obj );
1316 // Support: IE 8
1317 // Standard Document.defaultView is IE9+
1318 return doc.parentWindow || doc.defaultView;
1319 };
1320
1321 /**
1322 * Get the direction of an element or document.
1323 *
1324 * @static
1325 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1326 * @return {string} Text direction, either 'ltr' or 'rtl'
1327 */
1328 OO.ui.Element.static.getDir = function ( obj ) {
1329 var isDoc, isWin;
1330
1331 if ( obj instanceof jQuery ) {
1332 obj = obj[ 0 ];
1333 }
1334 isDoc = obj.nodeType === 9;
1335 isWin = obj.document !== undefined;
1336 if ( isDoc || isWin ) {
1337 if ( isWin ) {
1338 obj = obj.document;
1339 }
1340 obj = obj.body;
1341 }
1342 return $( obj ).css( 'direction' );
1343 };
1344
1345 /**
1346 * Get the offset between two frames.
1347 *
1348 * TODO: Make this function not use recursion.
1349 *
1350 * @static
1351 * @param {Window} from Window of the child frame
1352 * @param {Window} [to=window] Window of the parent frame
1353 * @param {Object} [offset] Offset to start with, used internally
1354 * @return {Object} Offset object, containing left and top properties
1355 */
1356 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1357 var i, len, frames, frame, rect;
1358
1359 if ( !to ) {
1360 to = window;
1361 }
1362 if ( !offset ) {
1363 offset = { top: 0, left: 0 };
1364 }
1365 if ( from.parent === from ) {
1366 return offset;
1367 }
1368
1369 // Get iframe element
1370 frames = from.parent.document.getElementsByTagName( 'iframe' );
1371 for ( i = 0, len = frames.length; i < len; i++ ) {
1372 if ( frames[ i ].contentWindow === from ) {
1373 frame = frames[ i ];
1374 break;
1375 }
1376 }
1377
1378 // Recursively accumulate offset values
1379 if ( frame ) {
1380 rect = frame.getBoundingClientRect();
1381 offset.left += rect.left;
1382 offset.top += rect.top;
1383 if ( from !== to ) {
1384 this.getFrameOffset( from.parent, offset );
1385 }
1386 }
1387 return offset;
1388 };
1389
1390 /**
1391 * Get the offset between two elements.
1392 *
1393 * The two elements may be in a different frame, but in that case the frame $element is in must
1394 * be contained in the frame $anchor is in.
1395 *
1396 * @static
1397 * @param {jQuery} $element Element whose position to get
1398 * @param {jQuery} $anchor Element to get $element's position relative to
1399 * @return {Object} Translated position coordinates, containing top and left properties
1400 */
1401 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1402 var iframe, iframePos,
1403 pos = $element.offset(),
1404 anchorPos = $anchor.offset(),
1405 elementDocument = this.getDocument( $element ),
1406 anchorDocument = this.getDocument( $anchor );
1407
1408 // If $element isn't in the same document as $anchor, traverse up
1409 while ( elementDocument !== anchorDocument ) {
1410 iframe = elementDocument.defaultView.frameElement;
1411 if ( !iframe ) {
1412 throw new Error( '$element frame is not contained in $anchor frame' );
1413 }
1414 iframePos = $( iframe ).offset();
1415 pos.left += iframePos.left;
1416 pos.top += iframePos.top;
1417 elementDocument = iframe.ownerDocument;
1418 }
1419 pos.left -= anchorPos.left;
1420 pos.top -= anchorPos.top;
1421 return pos;
1422 };
1423
1424 /**
1425 * Get element border sizes.
1426 *
1427 * @static
1428 * @param {HTMLElement} el Element to measure
1429 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1430 */
1431 OO.ui.Element.static.getBorders = function ( el ) {
1432 var doc = el.ownerDocument,
1433 // Support: IE 8
1434 // Standard Document.defaultView is IE9+
1435 win = doc.parentWindow || doc.defaultView,
1436 style = win && win.getComputedStyle ?
1437 win.getComputedStyle( el, null ) :
1438 // Support: IE 8
1439 // Standard getComputedStyle() is IE9+
1440 el.currentStyle,
1441 $el = $( el ),
1442 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1443 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1444 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1445 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1446
1447 return {
1448 top: top,
1449 left: left,
1450 bottom: bottom,
1451 right: right
1452 };
1453 };
1454
1455 /**
1456 * Get dimensions of an element or window.
1457 *
1458 * @static
1459 * @param {HTMLElement|Window} el Element to measure
1460 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1461 */
1462 OO.ui.Element.static.getDimensions = function ( el ) {
1463 var $el, $win,
1464 doc = el.ownerDocument || el.document,
1465 // Support: IE 8
1466 // Standard Document.defaultView is IE9+
1467 win = doc.parentWindow || doc.defaultView;
1468
1469 if ( win === el || el === doc.documentElement ) {
1470 $win = $( win );
1471 return {
1472 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1473 scroll: {
1474 top: $win.scrollTop(),
1475 left: $win.scrollLeft()
1476 },
1477 scrollbar: { right: 0, bottom: 0 },
1478 rect: {
1479 top: 0,
1480 left: 0,
1481 bottom: $win.innerHeight(),
1482 right: $win.innerWidth()
1483 }
1484 };
1485 } else {
1486 $el = $( el );
1487 return {
1488 borders: this.getBorders( el ),
1489 scroll: {
1490 top: $el.scrollTop(),
1491 left: $el.scrollLeft()
1492 },
1493 scrollbar: {
1494 right: $el.innerWidth() - el.clientWidth,
1495 bottom: $el.innerHeight() - el.clientHeight
1496 },
1497 rect: el.getBoundingClientRect()
1498 };
1499 }
1500 };
1501
1502 /**
1503 * Get scrollable object parent
1504 *
1505 * documentElement can't be used to get or set the scrollTop
1506 * property on Blink. Changing and testing its value lets us
1507 * use 'body' or 'documentElement' based on what is working.
1508 *
1509 * https://code.google.com/p/chromium/issues/detail?id=303131
1510 *
1511 * @static
1512 * @param {HTMLElement} el Element to find scrollable parent for
1513 * @return {HTMLElement} Scrollable parent
1514 */
1515 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1516 var scrollTop, body;
1517
1518 if ( OO.ui.scrollableElement === undefined ) {
1519 body = el.ownerDocument.body;
1520 scrollTop = body.scrollTop;
1521 body.scrollTop = 1;
1522
1523 if ( body.scrollTop === 1 ) {
1524 body.scrollTop = scrollTop;
1525 OO.ui.scrollableElement = 'body';
1526 } else {
1527 OO.ui.scrollableElement = 'documentElement';
1528 }
1529 }
1530
1531 return el.ownerDocument[ OO.ui.scrollableElement ];
1532 };
1533
1534 /**
1535 * Get closest scrollable container.
1536 *
1537 * Traverses up until either a scrollable element or the root is reached, in which case the window
1538 * will be returned.
1539 *
1540 * @static
1541 * @param {HTMLElement} el Element to find scrollable container for
1542 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1543 * @return {HTMLElement} Closest scrollable container
1544 */
1545 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1546 var i, val,
1547 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1548 props = [ 'overflow-x', 'overflow-y' ],
1549 $parent = $( el ).parent();
1550
1551 if ( dimension === 'x' || dimension === 'y' ) {
1552 props = [ 'overflow-' + dimension ];
1553 }
1554
1555 while ( $parent.length ) {
1556 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1557 return $parent[ 0 ];
1558 }
1559 i = props.length;
1560 while ( i-- ) {
1561 val = $parent.css( props[ i ] );
1562 if ( val === 'auto' || val === 'scroll' ) {
1563 return $parent[ 0 ];
1564 }
1565 }
1566 $parent = $parent.parent();
1567 }
1568 return this.getDocument( el ).body;
1569 };
1570
1571 /**
1572 * Scroll element into view.
1573 *
1574 * @static
1575 * @param {HTMLElement} el Element to scroll into view
1576 * @param {Object} [config] Configuration options
1577 * @param {string} [config.duration] jQuery animation duration value
1578 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1579 * to scroll in both directions
1580 * @param {Function} [config.complete] Function to call when scrolling completes
1581 */
1582 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1583 var rel, anim, callback, sc, $sc, eld, scd, $win;
1584
1585 // Configuration initialization
1586 config = config || {};
1587
1588 anim = {};
1589 callback = typeof config.complete === 'function' && config.complete;
1590 sc = this.getClosestScrollableContainer( el, config.direction );
1591 $sc = $( sc );
1592 eld = this.getDimensions( el );
1593 scd = this.getDimensions( sc );
1594 $win = $( this.getWindow( el ) );
1595
1596 // Compute the distances between the edges of el and the edges of the scroll viewport
1597 if ( $sc.is( 'html, body' ) ) {
1598 // If the scrollable container is the root, this is easy
1599 rel = {
1600 top: eld.rect.top,
1601 bottom: $win.innerHeight() - eld.rect.bottom,
1602 left: eld.rect.left,
1603 right: $win.innerWidth() - eld.rect.right
1604 };
1605 } else {
1606 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1607 rel = {
1608 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1609 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1610 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1611 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1612 };
1613 }
1614
1615 if ( !config.direction || config.direction === 'y' ) {
1616 if ( rel.top < 0 ) {
1617 anim.scrollTop = scd.scroll.top + rel.top;
1618 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1619 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1620 }
1621 }
1622 if ( !config.direction || config.direction === 'x' ) {
1623 if ( rel.left < 0 ) {
1624 anim.scrollLeft = scd.scroll.left + rel.left;
1625 } else if ( rel.left > 0 && rel.right < 0 ) {
1626 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1627 }
1628 }
1629 if ( !$.isEmptyObject( anim ) ) {
1630 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1631 if ( callback ) {
1632 $sc.queue( function ( next ) {
1633 callback();
1634 next();
1635 } );
1636 }
1637 } else {
1638 if ( callback ) {
1639 callback();
1640 }
1641 }
1642 };
1643
1644 /**
1645 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1646 * and reserve space for them, because it probably doesn't.
1647 *
1648 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1649 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1650 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1651 * and then reattach (or show) them back.
1652 *
1653 * @static
1654 * @param {HTMLElement} el Element to reconsider the scrollbars on
1655 */
1656 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1657 var i, len, scrollLeft, scrollTop, nodes = [];
1658 // Save scroll position
1659 scrollLeft = el.scrollLeft;
1660 scrollTop = el.scrollTop;
1661 // Detach all children
1662 while ( el.firstChild ) {
1663 nodes.push( el.firstChild );
1664 el.removeChild( el.firstChild );
1665 }
1666 // Force reflow
1667 void el.offsetHeight;
1668 // Reattach all children
1669 for ( i = 0, len = nodes.length; i < len; i++ ) {
1670 el.appendChild( nodes[ i ] );
1671 }
1672 // Restore scroll position (no-op if scrollbars disappeared)
1673 el.scrollLeft = scrollLeft;
1674 el.scrollTop = scrollTop;
1675 };
1676
1677 /* Methods */
1678
1679 /**
1680 * Toggle visibility of an element.
1681 *
1682 * @param {boolean} [show] Make element visible, omit to toggle visibility
1683 * @fires visible
1684 * @chainable
1685 */
1686 OO.ui.Element.prototype.toggle = function ( show ) {
1687 show = show === undefined ? !this.visible : !!show;
1688
1689 if ( show !== this.isVisible() ) {
1690 this.visible = show;
1691 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1692 this.emit( 'toggle', show );
1693 }
1694
1695 return this;
1696 };
1697
1698 /**
1699 * Check if element is visible.
1700 *
1701 * @return {boolean} element is visible
1702 */
1703 OO.ui.Element.prototype.isVisible = function () {
1704 return this.visible;
1705 };
1706
1707 /**
1708 * Get element data.
1709 *
1710 * @return {Mixed} Element data
1711 */
1712 OO.ui.Element.prototype.getData = function () {
1713 return this.data;
1714 };
1715
1716 /**
1717 * Set element data.
1718 *
1719 * @param {Mixed} Element data
1720 * @chainable
1721 */
1722 OO.ui.Element.prototype.setData = function ( data ) {
1723 this.data = data;
1724 return this;
1725 };
1726
1727 /**
1728 * Check if element supports one or more methods.
1729 *
1730 * @param {string|string[]} methods Method or list of methods to check
1731 * @return {boolean} All methods are supported
1732 */
1733 OO.ui.Element.prototype.supports = function ( methods ) {
1734 var i, len,
1735 support = 0;
1736
1737 methods = Array.isArray( methods ) ? methods : [ methods ];
1738 for ( i = 0, len = methods.length; i < len; i++ ) {
1739 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1740 support++;
1741 }
1742 }
1743
1744 return methods.length === support;
1745 };
1746
1747 /**
1748 * Update the theme-provided classes.
1749 *
1750 * @localdoc This is called in element mixins and widget classes any time state changes.
1751 * Updating is debounced, minimizing overhead of changing multiple attributes and
1752 * guaranteeing that theme updates do not occur within an element's constructor
1753 */
1754 OO.ui.Element.prototype.updateThemeClasses = function () {
1755 this.debouncedUpdateThemeClassesHandler();
1756 };
1757
1758 /**
1759 * @private
1760 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1761 * make them synchronous.
1762 */
1763 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1764 OO.ui.theme.updateElementClasses( this );
1765 };
1766
1767 /**
1768 * Get the HTML tag name.
1769 *
1770 * Override this method to base the result on instance information.
1771 *
1772 * @return {string} HTML tag name
1773 */
1774 OO.ui.Element.prototype.getTagName = function () {
1775 return this.constructor.static.tagName;
1776 };
1777
1778 /**
1779 * Check if the element is attached to the DOM
1780 * @return {boolean} The element is attached to the DOM
1781 */
1782 OO.ui.Element.prototype.isElementAttached = function () {
1783 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1784 };
1785
1786 /**
1787 * Get the DOM document.
1788 *
1789 * @return {HTMLDocument} Document object
1790 */
1791 OO.ui.Element.prototype.getElementDocument = function () {
1792 // Don't cache this in other ways either because subclasses could can change this.$element
1793 return OO.ui.Element.static.getDocument( this.$element );
1794 };
1795
1796 /**
1797 * Get the DOM window.
1798 *
1799 * @return {Window} Window object
1800 */
1801 OO.ui.Element.prototype.getElementWindow = function () {
1802 return OO.ui.Element.static.getWindow( this.$element );
1803 };
1804
1805 /**
1806 * Get closest scrollable container.
1807 */
1808 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1809 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1810 };
1811
1812 /**
1813 * Get group element is in.
1814 *
1815 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1816 */
1817 OO.ui.Element.prototype.getElementGroup = function () {
1818 return this.elementGroup;
1819 };
1820
1821 /**
1822 * Set group element is in.
1823 *
1824 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1825 * @chainable
1826 */
1827 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1828 this.elementGroup = group;
1829 return this;
1830 };
1831
1832 /**
1833 * Scroll element into view.
1834 *
1835 * @param {Object} [config] Configuration options
1836 */
1837 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1838 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1839 };
1840
1841 /**
1842 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1843 * (and its children) that represent an Element of the same type and configuration as the current
1844 * one, generated by the PHP implementation.
1845 *
1846 * This method is called just before `node` is detached from the DOM. The return value of this
1847 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1848 * DOM to replace `node`.
1849 *
1850 * @protected
1851 * @param {HTMLElement} node
1852 * @return {Object}
1853 */
1854 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1855 return {};
1856 };
1857
1858 /**
1859 * Restore the pre-infusion dynamic state for this widget.
1860 *
1861 * This method is called after #$element has been inserted into DOM. The parameter is the return
1862 * value of #gatherPreInfuseState.
1863 *
1864 * @protected
1865 * @param {Object} state
1866 */
1867 OO.ui.Element.prototype.restorePreInfuseState = function () {
1868 };
1869
1870 /**
1871 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1872 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1873 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1874 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1875 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1876 *
1877 * @abstract
1878 * @class
1879 * @extends OO.ui.Element
1880 * @mixins OO.EventEmitter
1881 *
1882 * @constructor
1883 * @param {Object} [config] Configuration options
1884 */
1885 OO.ui.Layout = function OoUiLayout( config ) {
1886 // Configuration initialization
1887 config = config || {};
1888
1889 // Parent constructor
1890 OO.ui.Layout.parent.call( this, config );
1891
1892 // Mixin constructors
1893 OO.EventEmitter.call( this );
1894
1895 // Initialization
1896 this.$element.addClass( 'oo-ui-layout' );
1897 };
1898
1899 /* Setup */
1900
1901 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1902 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1903
1904 /**
1905 * Widgets are compositions of one or more OOjs UI elements that users can both view
1906 * and interact with. All widgets can be configured and modified via a standard API,
1907 * and their state can change dynamically according to a model.
1908 *
1909 * @abstract
1910 * @class
1911 * @extends OO.ui.Element
1912 * @mixins OO.EventEmitter
1913 *
1914 * @constructor
1915 * @param {Object} [config] Configuration options
1916 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1917 * appearance reflects this state.
1918 */
1919 OO.ui.Widget = function OoUiWidget( config ) {
1920 // Initialize config
1921 config = $.extend( { disabled: false }, config );
1922
1923 // Parent constructor
1924 OO.ui.Widget.parent.call( this, config );
1925
1926 // Mixin constructors
1927 OO.EventEmitter.call( this );
1928
1929 // Properties
1930 this.disabled = null;
1931 this.wasDisabled = null;
1932
1933 // Initialization
1934 this.$element.addClass( 'oo-ui-widget' );
1935 this.setDisabled( !!config.disabled );
1936 };
1937
1938 /* Setup */
1939
1940 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1941 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1942
1943 /* Static Properties */
1944
1945 /**
1946 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1947 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1948 * handling.
1949 *
1950 * @static
1951 * @inheritable
1952 * @property {boolean}
1953 */
1954 OO.ui.Widget.static.supportsSimpleLabel = false;
1955
1956 /* Events */
1957
1958 /**
1959 * @event disable
1960 *
1961 * A 'disable' event is emitted when a widget is disabled.
1962 *
1963 * @param {boolean} disabled Widget is disabled
1964 */
1965
1966 /**
1967 * @event toggle
1968 *
1969 * A 'toggle' event is emitted when the visibility of the widget changes.
1970 *
1971 * @param {boolean} visible Widget is visible
1972 */
1973
1974 /* Methods */
1975
1976 /**
1977 * Check if the widget is disabled.
1978 *
1979 * @return {boolean} Widget is disabled
1980 */
1981 OO.ui.Widget.prototype.isDisabled = function () {
1982 return this.disabled;
1983 };
1984
1985 /**
1986 * Set the 'disabled' state of the widget.
1987 *
1988 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1989 *
1990 * @param {boolean} disabled Disable widget
1991 * @chainable
1992 */
1993 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1994 var isDisabled;
1995
1996 this.disabled = !!disabled;
1997 isDisabled = this.isDisabled();
1998 if ( isDisabled !== this.wasDisabled ) {
1999 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2000 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2001 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2002 this.emit( 'disable', isDisabled );
2003 this.updateThemeClasses();
2004 }
2005 this.wasDisabled = isDisabled;
2006
2007 return this;
2008 };
2009
2010 /**
2011 * Update the disabled state, in case of changes in parent widget.
2012 *
2013 * @chainable
2014 */
2015 OO.ui.Widget.prototype.updateDisabled = function () {
2016 this.setDisabled( this.disabled );
2017 return this;
2018 };
2019
2020 /**
2021 * A window is a container for elements that are in a child frame. They are used with
2022 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2023 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2024 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2025 * the window manager will choose a sensible fallback.
2026 *
2027 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2028 * different processes are executed:
2029 *
2030 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2031 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2032 * the window.
2033 *
2034 * - {@link #getSetupProcess} method is called and its result executed
2035 * - {@link #getReadyProcess} method is called and its result executed
2036 *
2037 * **opened**: The window is now open
2038 *
2039 * **closing**: The closing stage begins when the window manager's
2040 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2041 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2042 *
2043 * - {@link #getHoldProcess} method is called and its result executed
2044 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2045 *
2046 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2047 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2048 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2049 * processing can complete. Always assume window processes are executed asynchronously.
2050 *
2051 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2052 *
2053 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2054 *
2055 * @abstract
2056 * @class
2057 * @extends OO.ui.Element
2058 * @mixins OO.EventEmitter
2059 *
2060 * @constructor
2061 * @param {Object} [config] Configuration options
2062 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2063 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2064 */
2065 OO.ui.Window = function OoUiWindow( config ) {
2066 // Configuration initialization
2067 config = config || {};
2068
2069 // Parent constructor
2070 OO.ui.Window.parent.call( this, config );
2071
2072 // Mixin constructors
2073 OO.EventEmitter.call( this );
2074
2075 // Properties
2076 this.manager = null;
2077 this.size = config.size || this.constructor.static.size;
2078 this.$frame = $( '<div>' );
2079 this.$overlay = $( '<div>' );
2080 this.$content = $( '<div>' );
2081
2082 // Initialization
2083 this.$overlay.addClass( 'oo-ui-window-overlay' );
2084 this.$content
2085 .addClass( 'oo-ui-window-content' )
2086 .attr( 'tabindex', 0 );
2087 this.$frame
2088 .addClass( 'oo-ui-window-frame' )
2089 .append( this.$content );
2090
2091 this.$element
2092 .addClass( 'oo-ui-window' )
2093 .append( this.$frame, this.$overlay );
2094
2095 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2096 // that reference properties not initialized at that time of parent class construction
2097 // TODO: Find a better way to handle post-constructor setup
2098 this.visible = false;
2099 this.$element.addClass( 'oo-ui-element-hidden' );
2100 };
2101
2102 /* Setup */
2103
2104 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2105 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2106
2107 /* Static Properties */
2108
2109 /**
2110 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2111 *
2112 * The static size is used if no #size is configured during construction.
2113 *
2114 * @static
2115 * @inheritable
2116 * @property {string}
2117 */
2118 OO.ui.Window.static.size = 'medium';
2119
2120 /* Methods */
2121
2122 /**
2123 * Handle mouse down events.
2124 *
2125 * @private
2126 * @param {jQuery.Event} e Mouse down event
2127 */
2128 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2129 // Prevent clicking on the click-block from stealing focus
2130 if ( e.target === this.$element[ 0 ] ) {
2131 return false;
2132 }
2133 };
2134
2135 /**
2136 * Check if the window has been initialized.
2137 *
2138 * Initialization occurs when a window is added to a manager.
2139 *
2140 * @return {boolean} Window has been initialized
2141 */
2142 OO.ui.Window.prototype.isInitialized = function () {
2143 return !!this.manager;
2144 };
2145
2146 /**
2147 * Check if the window is visible.
2148 *
2149 * @return {boolean} Window is visible
2150 */
2151 OO.ui.Window.prototype.isVisible = function () {
2152 return this.visible;
2153 };
2154
2155 /**
2156 * Check if the window is opening.
2157 *
2158 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2159 * method.
2160 *
2161 * @return {boolean} Window is opening
2162 */
2163 OO.ui.Window.prototype.isOpening = function () {
2164 return this.manager.isOpening( this );
2165 };
2166
2167 /**
2168 * Check if the window is closing.
2169 *
2170 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2171 *
2172 * @return {boolean} Window is closing
2173 */
2174 OO.ui.Window.prototype.isClosing = function () {
2175 return this.manager.isClosing( this );
2176 };
2177
2178 /**
2179 * Check if the window is opened.
2180 *
2181 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2182 *
2183 * @return {boolean} Window is opened
2184 */
2185 OO.ui.Window.prototype.isOpened = function () {
2186 return this.manager.isOpened( this );
2187 };
2188
2189 /**
2190 * Get the window manager.
2191 *
2192 * All windows must be attached to a window manager, which is used to open
2193 * and close the window and control its presentation.
2194 *
2195 * @return {OO.ui.WindowManager} Manager of window
2196 */
2197 OO.ui.Window.prototype.getManager = function () {
2198 return this.manager;
2199 };
2200
2201 /**
2202 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2203 *
2204 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2205 */
2206 OO.ui.Window.prototype.getSize = function () {
2207 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2208 sizes = this.manager.constructor.static.sizes,
2209 size = this.size;
2210
2211 if ( !sizes[ size ] ) {
2212 size = this.manager.constructor.static.defaultSize;
2213 }
2214 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2215 size = 'full';
2216 }
2217
2218 return size;
2219 };
2220
2221 /**
2222 * Get the size properties associated with the current window size
2223 *
2224 * @return {Object} Size properties
2225 */
2226 OO.ui.Window.prototype.getSizeProperties = function () {
2227 return this.manager.constructor.static.sizes[ this.getSize() ];
2228 };
2229
2230 /**
2231 * Disable transitions on window's frame for the duration of the callback function, then enable them
2232 * back.
2233 *
2234 * @private
2235 * @param {Function} callback Function to call while transitions are disabled
2236 */
2237 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2238 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2239 // Disable transitions first, otherwise we'll get values from when the window was animating.
2240 var oldTransition,
2241 styleObj = this.$frame[ 0 ].style;
2242 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2243 styleObj.MozTransition || styleObj.WebkitTransition;
2244 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2245 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2246 callback();
2247 // Force reflow to make sure the style changes done inside callback really are not transitioned
2248 this.$frame.height();
2249 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2250 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2251 };
2252
2253 /**
2254 * Get the height of the full window contents (i.e., the window head, body and foot together).
2255 *
2256 * What consistitutes the head, body, and foot varies depending on the window type.
2257 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2258 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2259 * and special actions in the head, and dialog content in the body.
2260 *
2261 * To get just the height of the dialog body, use the #getBodyHeight method.
2262 *
2263 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2264 */
2265 OO.ui.Window.prototype.getContentHeight = function () {
2266 var bodyHeight,
2267 win = this,
2268 bodyStyleObj = this.$body[ 0 ].style,
2269 frameStyleObj = this.$frame[ 0 ].style;
2270
2271 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2272 // Disable transitions first, otherwise we'll get values from when the window was animating.
2273 this.withoutSizeTransitions( function () {
2274 var oldHeight = frameStyleObj.height,
2275 oldPosition = bodyStyleObj.position;
2276 frameStyleObj.height = '1px';
2277 // Force body to resize to new width
2278 bodyStyleObj.position = 'relative';
2279 bodyHeight = win.getBodyHeight();
2280 frameStyleObj.height = oldHeight;
2281 bodyStyleObj.position = oldPosition;
2282 } );
2283
2284 return (
2285 // Add buffer for border
2286 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2287 // Use combined heights of children
2288 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2289 );
2290 };
2291
2292 /**
2293 * Get the height of the window body.
2294 *
2295 * To get the height of the full window contents (the window body, head, and foot together),
2296 * use #getContentHeight.
2297 *
2298 * When this function is called, the window will temporarily have been resized
2299 * to height=1px, so .scrollHeight measurements can be taken accurately.
2300 *
2301 * @return {number} Height of the window body in pixels
2302 */
2303 OO.ui.Window.prototype.getBodyHeight = function () {
2304 return this.$body[ 0 ].scrollHeight;
2305 };
2306
2307 /**
2308 * Get the directionality of the frame (right-to-left or left-to-right).
2309 *
2310 * @return {string} Directionality: `'ltr'` or `'rtl'`
2311 */
2312 OO.ui.Window.prototype.getDir = function () {
2313 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2314 };
2315
2316 /**
2317 * Get the 'setup' process.
2318 *
2319 * The setup process is used to set up a window for use in a particular context,
2320 * based on the `data` argument. This method is called during the opening phase of the window’s
2321 * lifecycle.
2322 *
2323 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2324 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2325 * of OO.ui.Process.
2326 *
2327 * To add window content that persists between openings, you may wish to use the #initialize method
2328 * instead.
2329 *
2330 * @abstract
2331 * @param {Object} [data] Window opening data
2332 * @return {OO.ui.Process} Setup process
2333 */
2334 OO.ui.Window.prototype.getSetupProcess = function () {
2335 return new OO.ui.Process();
2336 };
2337
2338 /**
2339 * Get the ‘ready’ process.
2340 *
2341 * The ready process is used to ready a window for use in a particular
2342 * context, based on the `data` argument. This method is called during the opening phase of
2343 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2344 *
2345 * Override this method to add additional steps to the ‘ready’ process the parent method
2346 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2347 * methods of OO.ui.Process.
2348 *
2349 * @abstract
2350 * @param {Object} [data] Window opening data
2351 * @return {OO.ui.Process} Ready process
2352 */
2353 OO.ui.Window.prototype.getReadyProcess = function () {
2354 return new OO.ui.Process();
2355 };
2356
2357 /**
2358 * Get the 'hold' process.
2359 *
2360 * The hold proccess is used to keep a window from being used in a particular context,
2361 * based on the `data` argument. This method is called during the closing phase of the window’s
2362 * lifecycle.
2363 *
2364 * Override this method to add additional steps to the 'hold' process the parent method provides
2365 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2366 * of OO.ui.Process.
2367 *
2368 * @abstract
2369 * @param {Object} [data] Window closing data
2370 * @return {OO.ui.Process} Hold process
2371 */
2372 OO.ui.Window.prototype.getHoldProcess = function () {
2373 return new OO.ui.Process();
2374 };
2375
2376 /**
2377 * Get the ‘teardown’ process.
2378 *
2379 * The teardown process is used to teardown a window after use. During teardown,
2380 * user interactions within the window are conveyed and the window is closed, based on the `data`
2381 * argument. This method is called during the closing phase of the window’s lifecycle.
2382 *
2383 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2384 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2385 * of OO.ui.Process.
2386 *
2387 * @abstract
2388 * @param {Object} [data] Window closing data
2389 * @return {OO.ui.Process} Teardown process
2390 */
2391 OO.ui.Window.prototype.getTeardownProcess = function () {
2392 return new OO.ui.Process();
2393 };
2394
2395 /**
2396 * Set the window manager.
2397 *
2398 * This will cause the window to initialize. Calling it more than once will cause an error.
2399 *
2400 * @param {OO.ui.WindowManager} manager Manager for this window
2401 * @throws {Error} An error is thrown if the method is called more than once
2402 * @chainable
2403 */
2404 OO.ui.Window.prototype.setManager = function ( manager ) {
2405 if ( this.manager ) {
2406 throw new Error( 'Cannot set window manager, window already has a manager' );
2407 }
2408
2409 this.manager = manager;
2410 this.initialize();
2411
2412 return this;
2413 };
2414
2415 /**
2416 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2417 *
2418 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2419 * `full`
2420 * @chainable
2421 */
2422 OO.ui.Window.prototype.setSize = function ( size ) {
2423 this.size = size;
2424 this.updateSize();
2425 return this;
2426 };
2427
2428 /**
2429 * Update the window size.
2430 *
2431 * @throws {Error} An error is thrown if the window is not attached to a window manager
2432 * @chainable
2433 */
2434 OO.ui.Window.prototype.updateSize = function () {
2435 if ( !this.manager ) {
2436 throw new Error( 'Cannot update window size, must be attached to a manager' );
2437 }
2438
2439 this.manager.updateWindowSize( this );
2440
2441 return this;
2442 };
2443
2444 /**
2445 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2446 * when the window is opening. In general, setDimensions should not be called directly.
2447 *
2448 * To set the size of the window, use the #setSize method.
2449 *
2450 * @param {Object} dim CSS dimension properties
2451 * @param {string|number} [dim.width] Width
2452 * @param {string|number} [dim.minWidth] Minimum width
2453 * @param {string|number} [dim.maxWidth] Maximum width
2454 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2455 * @param {string|number} [dim.minWidth] Minimum height
2456 * @param {string|number} [dim.maxWidth] Maximum height
2457 * @chainable
2458 */
2459 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2460 var height,
2461 win = this,
2462 styleObj = this.$frame[ 0 ].style;
2463
2464 // Calculate the height we need to set using the correct width
2465 if ( dim.height === undefined ) {
2466 this.withoutSizeTransitions( function () {
2467 var oldWidth = styleObj.width;
2468 win.$frame.css( 'width', dim.width || '' );
2469 height = win.getContentHeight();
2470 styleObj.width = oldWidth;
2471 } );
2472 } else {
2473 height = dim.height;
2474 }
2475
2476 this.$frame.css( {
2477 width: dim.width || '',
2478 minWidth: dim.minWidth || '',
2479 maxWidth: dim.maxWidth || '',
2480 height: height || '',
2481 minHeight: dim.minHeight || '',
2482 maxHeight: dim.maxHeight || ''
2483 } );
2484
2485 return this;
2486 };
2487
2488 /**
2489 * Initialize window contents.
2490 *
2491 * Before the window is opened for the first time, #initialize is called so that content that
2492 * persists between openings can be added to the window.
2493 *
2494 * To set up a window with new content each time the window opens, use #getSetupProcess.
2495 *
2496 * @throws {Error} An error is thrown if the window is not attached to a window manager
2497 * @chainable
2498 */
2499 OO.ui.Window.prototype.initialize = function () {
2500 if ( !this.manager ) {
2501 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2502 }
2503
2504 // Properties
2505 this.$head = $( '<div>' );
2506 this.$body = $( '<div>' );
2507 this.$foot = $( '<div>' );
2508 this.$document = $( this.getElementDocument() );
2509
2510 // Events
2511 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2512
2513 // Initialization
2514 this.$head.addClass( 'oo-ui-window-head' );
2515 this.$body.addClass( 'oo-ui-window-body' );
2516 this.$foot.addClass( 'oo-ui-window-foot' );
2517 this.$content.append( this.$head, this.$body, this.$foot );
2518
2519 return this;
2520 };
2521
2522 /**
2523 * Open the window.
2524 *
2525 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2526 * method, which returns a promise resolved when the window is done opening.
2527 *
2528 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2529 *
2530 * @param {Object} [data] Window opening data
2531 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2532 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2533 * value is a new promise, which is resolved when the window begins closing.
2534 * @throws {Error} An error is thrown if the window is not attached to a window manager
2535 */
2536 OO.ui.Window.prototype.open = function ( data ) {
2537 if ( !this.manager ) {
2538 throw new Error( 'Cannot open window, must be attached to a manager' );
2539 }
2540
2541 return this.manager.openWindow( this, data );
2542 };
2543
2544 /**
2545 * Close the window.
2546 *
2547 * This method is a wrapper around a call to the window
2548 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2549 * which returns a closing promise resolved when the window is done closing.
2550 *
2551 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2552 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2553 * the window closes.
2554 *
2555 * @param {Object} [data] Window closing data
2556 * @return {jQuery.Promise} Promise resolved when window is closed
2557 * @throws {Error} An error is thrown if the window is not attached to a window manager
2558 */
2559 OO.ui.Window.prototype.close = function ( data ) {
2560 if ( !this.manager ) {
2561 throw new Error( 'Cannot close window, must be attached to a manager' );
2562 }
2563
2564 return this.manager.closeWindow( this, data );
2565 };
2566
2567 /**
2568 * Setup window.
2569 *
2570 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2571 * by other systems.
2572 *
2573 * @param {Object} [data] Window opening data
2574 * @return {jQuery.Promise} Promise resolved when window is setup
2575 */
2576 OO.ui.Window.prototype.setup = function ( data ) {
2577 var win = this,
2578 deferred = $.Deferred();
2579
2580 this.toggle( true );
2581
2582 this.getSetupProcess( data ).execute().done( function () {
2583 // Force redraw by asking the browser to measure the elements' widths
2584 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2585 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2586 deferred.resolve();
2587 } );
2588
2589 return deferred.promise();
2590 };
2591
2592 /**
2593 * Ready window.
2594 *
2595 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2596 * by other systems.
2597 *
2598 * @param {Object} [data] Window opening data
2599 * @return {jQuery.Promise} Promise resolved when window is ready
2600 */
2601 OO.ui.Window.prototype.ready = function ( data ) {
2602 var win = this,
2603 deferred = $.Deferred();
2604
2605 this.$content.focus();
2606 this.getReadyProcess( data ).execute().done( function () {
2607 // Force redraw by asking the browser to measure the elements' widths
2608 win.$element.addClass( 'oo-ui-window-ready' ).width();
2609 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2610 deferred.resolve();
2611 } );
2612
2613 return deferred.promise();
2614 };
2615
2616 /**
2617 * Hold window.
2618 *
2619 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2620 * by other systems.
2621 *
2622 * @param {Object} [data] Window closing data
2623 * @return {jQuery.Promise} Promise resolved when window is held
2624 */
2625 OO.ui.Window.prototype.hold = function ( data ) {
2626 var win = this,
2627 deferred = $.Deferred();
2628
2629 this.getHoldProcess( data ).execute().done( function () {
2630 // Get the focused element within the window's content
2631 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2632
2633 // Blur the focused element
2634 if ( $focus.length ) {
2635 $focus[ 0 ].blur();
2636 }
2637
2638 // Force redraw by asking the browser to measure the elements' widths
2639 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2640 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2641 deferred.resolve();
2642 } );
2643
2644 return deferred.promise();
2645 };
2646
2647 /**
2648 * Teardown window.
2649 *
2650 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2651 * by other systems.
2652 *
2653 * @param {Object} [data] Window closing data
2654 * @return {jQuery.Promise} Promise resolved when window is torn down
2655 */
2656 OO.ui.Window.prototype.teardown = function ( data ) {
2657 var win = this;
2658
2659 return this.getTeardownProcess( data ).execute()
2660 .done( function () {
2661 // Force redraw by asking the browser to measure the elements' widths
2662 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2663 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2664 win.toggle( false );
2665 } );
2666 };
2667
2668 /**
2669 * The Dialog class serves as the base class for the other types of dialogs.
2670 * Unless extended to include controls, the rendered dialog box is a simple window
2671 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2672 * which opens, closes, and controls the presentation of the window. See the
2673 * [OOjs UI documentation on MediaWiki] [1] for more information.
2674 *
2675 * @example
2676 * // A simple dialog window.
2677 * function MyDialog( config ) {
2678 * MyDialog.parent.call( this, config );
2679 * }
2680 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2681 * MyDialog.prototype.initialize = function () {
2682 * MyDialog.parent.prototype.initialize.call( this );
2683 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2684 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2685 * this.$body.append( this.content.$element );
2686 * };
2687 * MyDialog.prototype.getBodyHeight = function () {
2688 * return this.content.$element.outerHeight( true );
2689 * };
2690 * var myDialog = new MyDialog( {
2691 * size: 'medium'
2692 * } );
2693 * // Create and append a window manager, which opens and closes the window.
2694 * var windowManager = new OO.ui.WindowManager();
2695 * $( 'body' ).append( windowManager.$element );
2696 * windowManager.addWindows( [ myDialog ] );
2697 * // Open the window!
2698 * windowManager.openWindow( myDialog );
2699 *
2700 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2701 *
2702 * @abstract
2703 * @class
2704 * @extends OO.ui.Window
2705 * @mixins OO.ui.mixin.PendingElement
2706 *
2707 * @constructor
2708 * @param {Object} [config] Configuration options
2709 */
2710 OO.ui.Dialog = function OoUiDialog( config ) {
2711 // Parent constructor
2712 OO.ui.Dialog.parent.call( this, config );
2713
2714 // Mixin constructors
2715 OO.ui.mixin.PendingElement.call( this );
2716
2717 // Properties
2718 this.actions = new OO.ui.ActionSet();
2719 this.attachedActions = [];
2720 this.currentAction = null;
2721 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2722
2723 // Events
2724 this.actions.connect( this, {
2725 click: 'onActionClick',
2726 resize: 'onActionResize',
2727 change: 'onActionsChange'
2728 } );
2729
2730 // Initialization
2731 this.$element
2732 .addClass( 'oo-ui-dialog' )
2733 .attr( 'role', 'dialog' );
2734 };
2735
2736 /* Setup */
2737
2738 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2739 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2740
2741 /* Static Properties */
2742
2743 /**
2744 * Symbolic name of dialog.
2745 *
2746 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2747 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2748 *
2749 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2750 *
2751 * @abstract
2752 * @static
2753 * @inheritable
2754 * @property {string}
2755 */
2756 OO.ui.Dialog.static.name = '';
2757
2758 /**
2759 * The dialog title.
2760 *
2761 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2762 * that will produce a Label node or string. The title can also be specified with data passed to the
2763 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2764 *
2765 * @abstract
2766 * @static
2767 * @inheritable
2768 * @property {jQuery|string|Function}
2769 */
2770 OO.ui.Dialog.static.title = '';
2771
2772 /**
2773 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2774 *
2775 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2776 * value will be overriden.
2777 *
2778 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2779 *
2780 * @static
2781 * @inheritable
2782 * @property {Object[]}
2783 */
2784 OO.ui.Dialog.static.actions = [];
2785
2786 /**
2787 * Close the dialog when the 'Esc' key is pressed.
2788 *
2789 * @static
2790 * @abstract
2791 * @inheritable
2792 * @property {boolean}
2793 */
2794 OO.ui.Dialog.static.escapable = true;
2795
2796 /* Methods */
2797
2798 /**
2799 * Handle frame document key down events.
2800 *
2801 * @private
2802 * @param {jQuery.Event} e Key down event
2803 */
2804 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2805 if ( e.which === OO.ui.Keys.ESCAPE ) {
2806 this.close();
2807 e.preventDefault();
2808 e.stopPropagation();
2809 }
2810 };
2811
2812 /**
2813 * Handle action resized events.
2814 *
2815 * @private
2816 * @param {OO.ui.ActionWidget} action Action that was resized
2817 */
2818 OO.ui.Dialog.prototype.onActionResize = function () {
2819 // Override in subclass
2820 };
2821
2822 /**
2823 * Handle action click events.
2824 *
2825 * @private
2826 * @param {OO.ui.ActionWidget} action Action that was clicked
2827 */
2828 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2829 if ( !this.isPending() ) {
2830 this.executeAction( action.getAction() );
2831 }
2832 };
2833
2834 /**
2835 * Handle actions change event.
2836 *
2837 * @private
2838 */
2839 OO.ui.Dialog.prototype.onActionsChange = function () {
2840 this.detachActions();
2841 if ( !this.isClosing() ) {
2842 this.attachActions();
2843 }
2844 };
2845
2846 /**
2847 * Get the set of actions used by the dialog.
2848 *
2849 * @return {OO.ui.ActionSet}
2850 */
2851 OO.ui.Dialog.prototype.getActions = function () {
2852 return this.actions;
2853 };
2854
2855 /**
2856 * Get a process for taking action.
2857 *
2858 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2859 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2860 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2861 *
2862 * @abstract
2863 * @param {string} [action] Symbolic name of action
2864 * @return {OO.ui.Process} Action process
2865 */
2866 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2867 return new OO.ui.Process()
2868 .next( function () {
2869 if ( !action ) {
2870 // An empty action always closes the dialog without data, which should always be
2871 // safe and make no changes
2872 this.close();
2873 }
2874 }, this );
2875 };
2876
2877 /**
2878 * @inheritdoc
2879 *
2880 * @param {Object} [data] Dialog opening data
2881 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2882 * the {@link #static-title static title}
2883 * @param {Object[]} [data.actions] List of configuration options for each
2884 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2885 */
2886 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2887 data = data || {};
2888
2889 // Parent method
2890 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2891 .next( function () {
2892 var config = this.constructor.static,
2893 actions = data.actions !== undefined ? data.actions : config.actions;
2894
2895 this.title.setLabel(
2896 data.title !== undefined ? data.title : this.constructor.static.title
2897 );
2898 this.actions.add( this.getActionWidgets( actions ) );
2899
2900 if ( this.constructor.static.escapable ) {
2901 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2902 }
2903 }, this );
2904 };
2905
2906 /**
2907 * @inheritdoc
2908 */
2909 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2910 // Parent method
2911 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2912 .first( function () {
2913 if ( this.constructor.static.escapable ) {
2914 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2915 }
2916
2917 this.actions.clear();
2918 this.currentAction = null;
2919 }, this );
2920 };
2921
2922 /**
2923 * @inheritdoc
2924 */
2925 OO.ui.Dialog.prototype.initialize = function () {
2926 var titleId;
2927
2928 // Parent method
2929 OO.ui.Dialog.parent.prototype.initialize.call( this );
2930
2931 titleId = OO.ui.generateElementId();
2932
2933 // Properties
2934 this.title = new OO.ui.LabelWidget( {
2935 id: titleId
2936 } );
2937
2938 // Initialization
2939 this.$content.addClass( 'oo-ui-dialog-content' );
2940 this.$element.attr( 'aria-labelledby', titleId );
2941 this.setPendingElement( this.$head );
2942 };
2943
2944 /**
2945 * Get action widgets from a list of configs
2946 *
2947 * @param {Object[]} actions Action widget configs
2948 * @return {OO.ui.ActionWidget[]} Action widgets
2949 */
2950 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2951 var i, len, widgets = [];
2952 for ( i = 0, len = actions.length; i < len; i++ ) {
2953 widgets.push(
2954 new OO.ui.ActionWidget( actions[ i ] )
2955 );
2956 }
2957 return widgets;
2958 };
2959
2960 /**
2961 * Attach action actions.
2962 *
2963 * @protected
2964 */
2965 OO.ui.Dialog.prototype.attachActions = function () {
2966 // Remember the list of potentially attached actions
2967 this.attachedActions = this.actions.get();
2968 };
2969
2970 /**
2971 * Detach action actions.
2972 *
2973 * @protected
2974 * @chainable
2975 */
2976 OO.ui.Dialog.prototype.detachActions = function () {
2977 var i, len;
2978
2979 // Detach all actions that may have been previously attached
2980 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2981 this.attachedActions[ i ].$element.detach();
2982 }
2983 this.attachedActions = [];
2984 };
2985
2986 /**
2987 * Execute an action.
2988 *
2989 * @param {string} action Symbolic name of action to execute
2990 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2991 */
2992 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2993 this.pushPending();
2994 this.currentAction = action;
2995 return this.getActionProcess( action ).execute()
2996 .always( this.popPending.bind( this ) );
2997 };
2998
2999 /**
3000 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3001 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3002 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3003 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3004 * pertinent data and reused.
3005 *
3006 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3007 * `opened`, and `closing`, which represent the primary stages of the cycle:
3008 *
3009 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3010 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3011 *
3012 * - an `opening` event is emitted with an `opening` promise
3013 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3014 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3015 * window and its result executed
3016 * - a `setup` progress notification is emitted from the `opening` promise
3017 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3018 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3019 * window and its result executed
3020 * - a `ready` progress notification is emitted from the `opening` promise
3021 * - the `opening` promise is resolved with an `opened` promise
3022 *
3023 * **Opened**: the window is now open.
3024 *
3025 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3026 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3027 * to close the window.
3028 *
3029 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3030 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3031 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3032 * window and its result executed
3033 * - a `hold` progress notification is emitted from the `closing` promise
3034 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3035 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3036 * window and its result executed
3037 * - a `teardown` progress notification is emitted from the `closing` promise
3038 * - the `closing` promise is resolved. The window is now closed
3039 *
3040 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3041 *
3042 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3043 *
3044 * @class
3045 * @extends OO.ui.Element
3046 * @mixins OO.EventEmitter
3047 *
3048 * @constructor
3049 * @param {Object} [config] Configuration options
3050 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3051 * Note that window classes that are instantiated with a factory must have
3052 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3053 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3054 */
3055 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3056 // Configuration initialization
3057 config = config || {};
3058
3059 // Parent constructor
3060 OO.ui.WindowManager.parent.call( this, config );
3061
3062 // Mixin constructors
3063 OO.EventEmitter.call( this );
3064
3065 // Properties
3066 this.factory = config.factory;
3067 this.modal = config.modal === undefined || !!config.modal;
3068 this.windows = {};
3069 this.opening = null;
3070 this.opened = null;
3071 this.closing = null;
3072 this.preparingToOpen = null;
3073 this.preparingToClose = null;
3074 this.currentWindow = null;
3075 this.globalEvents = false;
3076 this.$ariaHidden = null;
3077 this.onWindowResizeTimeout = null;
3078 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3079 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3080
3081 // Initialization
3082 this.$element
3083 .addClass( 'oo-ui-windowManager' )
3084 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3085 };
3086
3087 /* Setup */
3088
3089 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3090 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3091
3092 /* Events */
3093
3094 /**
3095 * An 'opening' event is emitted when the window begins to be opened.
3096 *
3097 * @event opening
3098 * @param {OO.ui.Window} win Window that's being opened
3099 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3100 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3101 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3102 * @param {Object} data Window opening data
3103 */
3104
3105 /**
3106 * A 'closing' event is emitted when the window begins to be closed.
3107 *
3108 * @event closing
3109 * @param {OO.ui.Window} win Window that's being closed
3110 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3111 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3112 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3113 * is the closing data.
3114 * @param {Object} data Window closing data
3115 */
3116
3117 /**
3118 * A 'resize' event is emitted when a window is resized.
3119 *
3120 * @event resize
3121 * @param {OO.ui.Window} win Window that was resized
3122 */
3123
3124 /* Static Properties */
3125
3126 /**
3127 * Map of the symbolic name of each window size and its CSS properties.
3128 *
3129 * @static
3130 * @inheritable
3131 * @property {Object}
3132 */
3133 OO.ui.WindowManager.static.sizes = {
3134 small: {
3135 width: 300
3136 },
3137 medium: {
3138 width: 500
3139 },
3140 large: {
3141 width: 700
3142 },
3143 larger: {
3144 width: 900
3145 },
3146 full: {
3147 // These can be non-numeric because they are never used in calculations
3148 width: '100%',
3149 height: '100%'
3150 }
3151 };
3152
3153 /**
3154 * Symbolic name of the default window size.
3155 *
3156 * The default size is used if the window's requested size is not recognized.
3157 *
3158 * @static
3159 * @inheritable
3160 * @property {string}
3161 */
3162 OO.ui.WindowManager.static.defaultSize = 'medium';
3163
3164 /* Methods */
3165
3166 /**
3167 * Handle window resize events.
3168 *
3169 * @private
3170 * @param {jQuery.Event} e Window resize event
3171 */
3172 OO.ui.WindowManager.prototype.onWindowResize = function () {
3173 clearTimeout( this.onWindowResizeTimeout );
3174 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3175 };
3176
3177 /**
3178 * Handle window resize events.
3179 *
3180 * @private
3181 * @param {jQuery.Event} e Window resize event
3182 */
3183 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3184 if ( this.currentWindow ) {
3185 this.updateWindowSize( this.currentWindow );
3186 }
3187 };
3188
3189 /**
3190 * Check if window is opening.
3191 *
3192 * @return {boolean} Window is opening
3193 */
3194 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3195 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3196 };
3197
3198 /**
3199 * Check if window is closing.
3200 *
3201 * @return {boolean} Window is closing
3202 */
3203 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3204 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3205 };
3206
3207 /**
3208 * Check if window is opened.
3209 *
3210 * @return {boolean} Window is opened
3211 */
3212 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3213 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3214 };
3215
3216 /**
3217 * Check if a window is being managed.
3218 *
3219 * @param {OO.ui.Window} win Window to check
3220 * @return {boolean} Window is being managed
3221 */
3222 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3223 var name;
3224
3225 for ( name in this.windows ) {
3226 if ( this.windows[ name ] === win ) {
3227 return true;
3228 }
3229 }
3230
3231 return false;
3232 };
3233
3234 /**
3235 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3236 *
3237 * @param {OO.ui.Window} win Window being opened
3238 * @param {Object} [data] Window opening data
3239 * @return {number} Milliseconds to wait
3240 */
3241 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3242 return 0;
3243 };
3244
3245 /**
3246 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3247 *
3248 * @param {OO.ui.Window} win Window being opened
3249 * @param {Object} [data] Window opening data
3250 * @return {number} Milliseconds to wait
3251 */
3252 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3253 return 0;
3254 };
3255
3256 /**
3257 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3258 *
3259 * @param {OO.ui.Window} win Window being closed
3260 * @param {Object} [data] Window closing data
3261 * @return {number} Milliseconds to wait
3262 */
3263 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3264 return 0;
3265 };
3266
3267 /**
3268 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3269 * executing the ‘teardown’ process.
3270 *
3271 * @param {OO.ui.Window} win Window being closed
3272 * @param {Object} [data] Window closing data
3273 * @return {number} Milliseconds to wait
3274 */
3275 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3276 return this.modal ? 250 : 0;
3277 };
3278
3279 /**
3280 * Get a window by its symbolic name.
3281 *
3282 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3283 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3284 * for more information about using factories.
3285 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3286 *
3287 * @param {string} name Symbolic name of the window
3288 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3289 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3290 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3291 */
3292 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3293 var deferred = $.Deferred(),
3294 win = this.windows[ name ];
3295
3296 if ( !( win instanceof OO.ui.Window ) ) {
3297 if ( this.factory ) {
3298 if ( !this.factory.lookup( name ) ) {
3299 deferred.reject( new OO.ui.Error(
3300 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3301 ) );
3302 } else {
3303 win = this.factory.create( name );
3304 this.addWindows( [ win ] );
3305 deferred.resolve( win );
3306 }
3307 } else {
3308 deferred.reject( new OO.ui.Error(
3309 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3310 ) );
3311 }
3312 } else {
3313 deferred.resolve( win );
3314 }
3315
3316 return deferred.promise();
3317 };
3318
3319 /**
3320 * Get current window.
3321 *
3322 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3323 */
3324 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3325 return this.currentWindow;
3326 };
3327
3328 /**
3329 * Open a window.
3330 *
3331 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3332 * @param {Object} [data] Window opening data
3333 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3334 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3335 * @fires opening
3336 */
3337 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3338 var manager = this,
3339 opening = $.Deferred();
3340
3341 // Argument handling
3342 if ( typeof win === 'string' ) {
3343 return this.getWindow( win ).then( function ( win ) {
3344 return manager.openWindow( win, data );
3345 } );
3346 }
3347
3348 // Error handling
3349 if ( !this.hasWindow( win ) ) {
3350 opening.reject( new OO.ui.Error(
3351 'Cannot open window: window is not attached to manager'
3352 ) );
3353 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3354 opening.reject( new OO.ui.Error(
3355 'Cannot open window: another window is opening or open'
3356 ) );
3357 }
3358
3359 // Window opening
3360 if ( opening.state() !== 'rejected' ) {
3361 // If a window is currently closing, wait for it to complete
3362 this.preparingToOpen = $.when( this.closing );
3363 // Ensure handlers get called after preparingToOpen is set
3364 this.preparingToOpen.done( function () {
3365 if ( manager.modal ) {
3366 manager.toggleGlobalEvents( true );
3367 manager.toggleAriaIsolation( true );
3368 }
3369 manager.currentWindow = win;
3370 manager.opening = opening;
3371 manager.preparingToOpen = null;
3372 manager.emit( 'opening', win, opening, data );
3373 setTimeout( function () {
3374 win.setup( data ).then( function () {
3375 manager.updateWindowSize( win );
3376 manager.opening.notify( { state: 'setup' } );
3377 setTimeout( function () {
3378 win.ready( data ).then( function () {
3379 manager.opening.notify( { state: 'ready' } );
3380 manager.opening = null;
3381 manager.opened = $.Deferred();
3382 opening.resolve( manager.opened.promise(), data );
3383 } );
3384 }, manager.getReadyDelay() );
3385 } );
3386 }, manager.getSetupDelay() );
3387 } );
3388 }
3389
3390 return opening.promise();
3391 };
3392
3393 /**
3394 * Close a window.
3395 *
3396 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3397 * @param {Object} [data] Window closing data
3398 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3399 * See {@link #event-closing 'closing' event} for more information about closing promises.
3400 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3401 * @fires closing
3402 */
3403 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3404 var manager = this,
3405 closing = $.Deferred(),
3406 opened;
3407
3408 // Argument handling
3409 if ( typeof win === 'string' ) {
3410 win = this.windows[ win ];
3411 } else if ( !this.hasWindow( win ) ) {
3412 win = null;
3413 }
3414
3415 // Error handling
3416 if ( !win ) {
3417 closing.reject( new OO.ui.Error(
3418 'Cannot close window: window is not attached to manager'
3419 ) );
3420 } else if ( win !== this.currentWindow ) {
3421 closing.reject( new OO.ui.Error(
3422 'Cannot close window: window already closed with different data'
3423 ) );
3424 } else if ( this.preparingToClose || this.closing ) {
3425 closing.reject( new OO.ui.Error(
3426 'Cannot close window: window already closing with different data'
3427 ) );
3428 }
3429
3430 // Window closing
3431 if ( closing.state() !== 'rejected' ) {
3432 // If the window is currently opening, close it when it's done
3433 this.preparingToClose = $.when( this.opening );
3434 // Ensure handlers get called after preparingToClose is set
3435 this.preparingToClose.done( function () {
3436 manager.closing = closing;
3437 manager.preparingToClose = null;
3438 manager.emit( 'closing', win, closing, data );
3439 opened = manager.opened;
3440 manager.opened = null;
3441 opened.resolve( closing.promise(), data );
3442 setTimeout( function () {
3443 win.hold( data ).then( function () {
3444 closing.notify( { state: 'hold' } );
3445 setTimeout( function () {
3446 win.teardown( data ).then( function () {
3447 closing.notify( { state: 'teardown' } );
3448 if ( manager.modal ) {
3449 manager.toggleGlobalEvents( false );
3450 manager.toggleAriaIsolation( false );
3451 }
3452 manager.closing = null;
3453 manager.currentWindow = null;
3454 closing.resolve( data );
3455 } );
3456 }, manager.getTeardownDelay() );
3457 } );
3458 }, manager.getHoldDelay() );
3459 } );
3460 }
3461
3462 return closing.promise();
3463 };
3464
3465 /**
3466 * Add windows to the window manager.
3467 *
3468 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3469 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3470 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3471 *
3472 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3473 * by reference, symbolic name, or explicitly defined symbolic names.
3474 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3475 * explicit nor a statically configured symbolic name.
3476 */
3477 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3478 var i, len, win, name, list;
3479
3480 if ( Array.isArray( windows ) ) {
3481 // Convert to map of windows by looking up symbolic names from static configuration
3482 list = {};
3483 for ( i = 0, len = windows.length; i < len; i++ ) {
3484 name = windows[ i ].constructor.static.name;
3485 if ( typeof name !== 'string' ) {
3486 throw new Error( 'Cannot add window' );
3487 }
3488 list[ name ] = windows[ i ];
3489 }
3490 } else if ( OO.isPlainObject( windows ) ) {
3491 list = windows;
3492 }
3493
3494 // Add windows
3495 for ( name in list ) {
3496 win = list[ name ];
3497 this.windows[ name ] = win.toggle( false );
3498 this.$element.append( win.$element );
3499 win.setManager( this );
3500 }
3501 };
3502
3503 /**
3504 * Remove the specified windows from the windows manager.
3505 *
3506 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3507 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3508 * longer listens to events, use the #destroy method.
3509 *
3510 * @param {string[]} names Symbolic names of windows to remove
3511 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3512 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3513 */
3514 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3515 var i, len, win, name, cleanupWindow,
3516 manager = this,
3517 promises = [],
3518 cleanup = function ( name, win ) {
3519 delete manager.windows[ name ];
3520 win.$element.detach();
3521 };
3522
3523 for ( i = 0, len = names.length; i < len; i++ ) {
3524 name = names[ i ];
3525 win = this.windows[ name ];
3526 if ( !win ) {
3527 throw new Error( 'Cannot remove window' );
3528 }
3529 cleanupWindow = cleanup.bind( null, name, win );
3530 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3531 }
3532
3533 return $.when.apply( $, promises );
3534 };
3535
3536 /**
3537 * Remove all windows from the window manager.
3538 *
3539 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3540 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3541 * To remove just a subset of windows, use the #removeWindows method.
3542 *
3543 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3544 */
3545 OO.ui.WindowManager.prototype.clearWindows = function () {
3546 return this.removeWindows( Object.keys( this.windows ) );
3547 };
3548
3549 /**
3550 * Set dialog size. In general, this method should not be called directly.
3551 *
3552 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3553 *
3554 * @chainable
3555 */
3556 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3557 var isFullscreen;
3558
3559 // Bypass for non-current, and thus invisible, windows
3560 if ( win !== this.currentWindow ) {
3561 return;
3562 }
3563
3564 isFullscreen = win.getSize() === 'full';
3565
3566 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3567 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3568 win.setDimensions( win.getSizeProperties() );
3569
3570 this.emit( 'resize', win );
3571
3572 return this;
3573 };
3574
3575 /**
3576 * Bind or unbind global events for scrolling.
3577 *
3578 * @private
3579 * @param {boolean} [on] Bind global events
3580 * @chainable
3581 */
3582 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3583 var scrollWidth, bodyMargin,
3584 $body = $( this.getElementDocument().body ),
3585 // We could have multiple window managers open so only modify
3586 // the body css at the bottom of the stack
3587 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3588
3589 on = on === undefined ? !!this.globalEvents : !!on;
3590
3591 if ( on ) {
3592 if ( !this.globalEvents ) {
3593 $( this.getElementWindow() ).on( {
3594 // Start listening for top-level window dimension changes
3595 'orientationchange resize': this.onWindowResizeHandler
3596 } );
3597 if ( stackDepth === 0 ) {
3598 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3599 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3600 $body.css( {
3601 overflow: 'hidden',
3602 'margin-right': bodyMargin + scrollWidth
3603 } );
3604 }
3605 stackDepth++;
3606 this.globalEvents = true;
3607 }
3608 } else if ( this.globalEvents ) {
3609 $( this.getElementWindow() ).off( {
3610 // Stop listening for top-level window dimension changes
3611 'orientationchange resize': this.onWindowResizeHandler
3612 } );
3613 stackDepth--;
3614 if ( stackDepth === 0 ) {
3615 $body.css( {
3616 overflow: '',
3617 'margin-right': ''
3618 } );
3619 }
3620 this.globalEvents = false;
3621 }
3622 $body.data( 'windowManagerGlobalEvents', stackDepth );
3623
3624 return this;
3625 };
3626
3627 /**
3628 * Toggle screen reader visibility of content other than the window manager.
3629 *
3630 * @private
3631 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3632 * @chainable
3633 */
3634 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3635 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3636
3637 if ( isolate ) {
3638 if ( !this.$ariaHidden ) {
3639 // Hide everything other than the window manager from screen readers
3640 this.$ariaHidden = $( 'body' )
3641 .children()
3642 .not( this.$element.parentsUntil( 'body' ).last() )
3643 .attr( 'aria-hidden', '' );
3644 }
3645 } else if ( this.$ariaHidden ) {
3646 // Restore screen reader visibility
3647 this.$ariaHidden.removeAttr( 'aria-hidden' );
3648 this.$ariaHidden = null;
3649 }
3650
3651 return this;
3652 };
3653
3654 /**
3655 * Destroy the window manager.
3656 *
3657 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3658 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3659 * instead.
3660 */
3661 OO.ui.WindowManager.prototype.destroy = function () {
3662 this.toggleGlobalEvents( false );
3663 this.toggleAriaIsolation( false );
3664 this.clearWindows();
3665 this.$element.remove();
3666 };
3667
3668 /**
3669 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3670 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3671 * appearance and functionality of the error interface.
3672 *
3673 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3674 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3675 * that initiated the failed process will be disabled.
3676 *
3677 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3678 * process again.
3679 *
3680 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3681 *
3682 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3683 *
3684 * @class
3685 *
3686 * @constructor
3687 * @param {string|jQuery} message Description of error
3688 * @param {Object} [config] Configuration options
3689 * @cfg {boolean} [recoverable=true] Error is recoverable.
3690 * By default, errors are recoverable, and users can try the process again.
3691 * @cfg {boolean} [warning=false] Error is a warning.
3692 * If the error is a warning, the error interface will include a
3693 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3694 * is not triggered a second time if the user chooses to continue.
3695 */
3696 OO.ui.Error = function OoUiError( message, config ) {
3697 // Allow passing positional parameters inside the config object
3698 if ( OO.isPlainObject( message ) && config === undefined ) {
3699 config = message;
3700 message = config.message;
3701 }
3702
3703 // Configuration initialization
3704 config = config || {};
3705
3706 // Properties
3707 this.message = message instanceof jQuery ? message : String( message );
3708 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3709 this.warning = !!config.warning;
3710 };
3711
3712 /* Setup */
3713
3714 OO.initClass( OO.ui.Error );
3715
3716 /* Methods */
3717
3718 /**
3719 * Check if the error is recoverable.
3720 *
3721 * If the error is recoverable, users are able to try the process again.
3722 *
3723 * @return {boolean} Error is recoverable
3724 */
3725 OO.ui.Error.prototype.isRecoverable = function () {
3726 return this.recoverable;
3727 };
3728
3729 /**
3730 * Check if the error is a warning.
3731 *
3732 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3733 *
3734 * @return {boolean} Error is warning
3735 */
3736 OO.ui.Error.prototype.isWarning = function () {
3737 return this.warning;
3738 };
3739
3740 /**
3741 * Get error message as DOM nodes.
3742 *
3743 * @return {jQuery} Error message in DOM nodes
3744 */
3745 OO.ui.Error.prototype.getMessage = function () {
3746 return this.message instanceof jQuery ?
3747 this.message.clone() :
3748 $( '<div>' ).text( this.message ).contents();
3749 };
3750
3751 /**
3752 * Get the error message text.
3753 *
3754 * @return {string} Error message
3755 */
3756 OO.ui.Error.prototype.getMessageText = function () {
3757 return this.message instanceof jQuery ? this.message.text() : this.message;
3758 };
3759
3760 /**
3761 * Wraps an HTML snippet for use with configuration values which default
3762 * to strings. This bypasses the default html-escaping done to string
3763 * values.
3764 *
3765 * @class
3766 *
3767 * @constructor
3768 * @param {string} [content] HTML content
3769 */
3770 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3771 // Properties
3772 this.content = content;
3773 };
3774
3775 /* Setup */
3776
3777 OO.initClass( OO.ui.HtmlSnippet );
3778
3779 /* Methods */
3780
3781 /**
3782 * Render into HTML.
3783 *
3784 * @return {string} Unchanged HTML snippet.
3785 */
3786 OO.ui.HtmlSnippet.prototype.toString = function () {
3787 return this.content;
3788 };
3789
3790 /**
3791 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3792 * or a function:
3793 *
3794 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3795 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3796 * or stop if the promise is rejected.
3797 * - **function**: the process will execute the function. The process will stop if the function returns
3798 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3799 * will wait for that number of milliseconds before proceeding.
3800 *
3801 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3802 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3803 * its remaining steps will not be performed.
3804 *
3805 * @class
3806 *
3807 * @constructor
3808 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3809 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3810 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3811 * a number or promise.
3812 * @return {Object} Step object, with `callback` and `context` properties
3813 */
3814 OO.ui.Process = function ( step, context ) {
3815 // Properties
3816 this.steps = [];
3817
3818 // Initialization
3819 if ( step !== undefined ) {
3820 this.next( step, context );
3821 }
3822 };
3823
3824 /* Setup */
3825
3826 OO.initClass( OO.ui.Process );
3827
3828 /* Methods */
3829
3830 /**
3831 * Start the process.
3832 *
3833 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3834 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3835 * and any remaining steps are not performed.
3836 */
3837 OO.ui.Process.prototype.execute = function () {
3838 var i, len, promise;
3839
3840 /**
3841 * Continue execution.
3842 *
3843 * @ignore
3844 * @param {Array} step A function and the context it should be called in
3845 * @return {Function} Function that continues the process
3846 */
3847 function proceed( step ) {
3848 return function () {
3849 // Execute step in the correct context
3850 var deferred,
3851 result = step.callback.call( step.context );
3852
3853 if ( result === false ) {
3854 // Use rejected promise for boolean false results
3855 return $.Deferred().reject( [] ).promise();
3856 }
3857 if ( typeof result === 'number' ) {
3858 if ( result < 0 ) {
3859 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3860 }
3861 // Use a delayed promise for numbers, expecting them to be in milliseconds
3862 deferred = $.Deferred();
3863 setTimeout( deferred.resolve, result );
3864 return deferred.promise();
3865 }
3866 if ( result instanceof OO.ui.Error ) {
3867 // Use rejected promise for error
3868 return $.Deferred().reject( [ result ] ).promise();
3869 }
3870 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3871 // Use rejected promise for list of errors
3872 return $.Deferred().reject( result ).promise();
3873 }
3874 // Duck-type the object to see if it can produce a promise
3875 if ( result && $.isFunction( result.promise ) ) {
3876 // Use a promise generated from the result
3877 return result.promise();
3878 }
3879 // Use resolved promise for other results
3880 return $.Deferred().resolve().promise();
3881 };
3882 }
3883
3884 if ( this.steps.length ) {
3885 // Generate a chain reaction of promises
3886 promise = proceed( this.steps[ 0 ] )();
3887 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3888 promise = promise.then( proceed( this.steps[ i ] ) );
3889 }
3890 } else {
3891 promise = $.Deferred().resolve().promise();
3892 }
3893
3894 return promise;
3895 };
3896
3897 /**
3898 * Create a process step.
3899 *
3900 * @private
3901 * @param {number|jQuery.Promise|Function} step
3902 *
3903 * - Number of milliseconds to wait before proceeding
3904 * - Promise that must be resolved before proceeding
3905 * - Function to execute
3906 * - If the function returns a boolean false the process will stop
3907 * - If the function returns a promise, the process will continue to the next
3908 * step when the promise is resolved or stop if the promise is rejected
3909 * - If the function returns a number, the process will wait for that number of
3910 * milliseconds before proceeding
3911 * @param {Object} [context=null] Execution context of the function. The context is
3912 * ignored if the step is a number or promise.
3913 * @return {Object} Step object, with `callback` and `context` properties
3914 */
3915 OO.ui.Process.prototype.createStep = function ( step, context ) {
3916 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3917 return {
3918 callback: function () {
3919 return step;
3920 },
3921 context: null
3922 };
3923 }
3924 if ( $.isFunction( step ) ) {
3925 return {
3926 callback: step,
3927 context: context
3928 };
3929 }
3930 throw new Error( 'Cannot create process step: number, promise or function expected' );
3931 };
3932
3933 /**
3934 * Add step to the beginning of the process.
3935 *
3936 * @inheritdoc #createStep
3937 * @return {OO.ui.Process} this
3938 * @chainable
3939 */
3940 OO.ui.Process.prototype.first = function ( step, context ) {
3941 this.steps.unshift( this.createStep( step, context ) );
3942 return this;
3943 };
3944
3945 /**
3946 * Add step to the end of the process.
3947 *
3948 * @inheritdoc #createStep
3949 * @return {OO.ui.Process} this
3950 * @chainable
3951 */
3952 OO.ui.Process.prototype.next = function ( step, context ) {
3953 this.steps.push( this.createStep( step, context ) );
3954 return this;
3955 };
3956
3957 /**
3958 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3959 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3960 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3961 *
3962 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3963 *
3964 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3965 *
3966 * @class
3967 * @extends OO.Factory
3968 * @constructor
3969 */
3970 OO.ui.ToolFactory = function OoUiToolFactory() {
3971 // Parent constructor
3972 OO.ui.ToolFactory.parent.call( this );
3973 };
3974
3975 /* Setup */
3976
3977 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3978
3979 /* Methods */
3980
3981 /**
3982 * Get tools from the factory
3983 *
3984 * @param {Array} include Included tools
3985 * @param {Array} exclude Excluded tools
3986 * @param {Array} promote Promoted tools
3987 * @param {Array} demote Demoted tools
3988 * @return {string[]} List of tools
3989 */
3990 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3991 var i, len, included, promoted, demoted,
3992 auto = [],
3993 used = {};
3994
3995 // Collect included and not excluded tools
3996 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3997
3998 // Promotion
3999 promoted = this.extract( promote, used );
4000 demoted = this.extract( demote, used );
4001
4002 // Auto
4003 for ( i = 0, len = included.length; i < len; i++ ) {
4004 if ( !used[ included[ i ] ] ) {
4005 auto.push( included[ i ] );
4006 }
4007 }
4008
4009 return promoted.concat( auto ).concat( demoted );
4010 };
4011
4012 /**
4013 * Get a flat list of names from a list of names or groups.
4014 *
4015 * Tools can be specified in the following ways:
4016 *
4017 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4018 * - All tools in a group: `{ group: 'group-name' }`
4019 * - All tools: `'*'`
4020 *
4021 * @private
4022 * @param {Array|string} collection List of tools
4023 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4024 * names will be added as properties
4025 * @return {string[]} List of extracted names
4026 */
4027 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4028 var i, len, item, name, tool,
4029 names = [];
4030
4031 if ( collection === '*' ) {
4032 for ( name in this.registry ) {
4033 tool = this.registry[ name ];
4034 if (
4035 // Only add tools by group name when auto-add is enabled
4036 tool.static.autoAddToCatchall &&
4037 // Exclude already used tools
4038 ( !used || !used[ name ] )
4039 ) {
4040 names.push( name );
4041 if ( used ) {
4042 used[ name ] = true;
4043 }
4044 }
4045 }
4046 } else if ( Array.isArray( collection ) ) {
4047 for ( i = 0, len = collection.length; i < len; i++ ) {
4048 item = collection[ i ];
4049 // Allow plain strings as shorthand for named tools
4050 if ( typeof item === 'string' ) {
4051 item = { name: item };
4052 }
4053 if ( OO.isPlainObject( item ) ) {
4054 if ( item.group ) {
4055 for ( name in this.registry ) {
4056 tool = this.registry[ name ];
4057 if (
4058 // Include tools with matching group
4059 tool.static.group === item.group &&
4060 // Only add tools by group name when auto-add is enabled
4061 tool.static.autoAddToGroup &&
4062 // Exclude already used tools
4063 ( !used || !used[ name ] )
4064 ) {
4065 names.push( name );
4066 if ( used ) {
4067 used[ name ] = true;
4068 }
4069 }
4070 }
4071 // Include tools with matching name and exclude already used tools
4072 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4073 names.push( item.name );
4074 if ( used ) {
4075 used[ item.name ] = true;
4076 }
4077 }
4078 }
4079 }
4080 }
4081 return names;
4082 };
4083
4084 /**
4085 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4086 * specify a symbolic name and be registered with the factory. The following classes are registered by
4087 * default:
4088 *
4089 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4090 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4091 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4092 *
4093 * See {@link OO.ui.Toolbar toolbars} for an example.
4094 *
4095 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4096 *
4097 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4098 * @class
4099 * @extends OO.Factory
4100 * @constructor
4101 */
4102 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4103 var i, l, defaultClasses;
4104 // Parent constructor
4105 OO.Factory.call( this );
4106
4107 defaultClasses = this.constructor.static.getDefaultClasses();
4108
4109 // Register default toolgroups
4110 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4111 this.register( defaultClasses[ i ] );
4112 }
4113 };
4114
4115 /* Setup */
4116
4117 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4118
4119 /* Static Methods */
4120
4121 /**
4122 * Get a default set of classes to be registered on construction.
4123 *
4124 * @return {Function[]} Default classes
4125 */
4126 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4127 return [
4128 OO.ui.BarToolGroup,
4129 OO.ui.ListToolGroup,
4130 OO.ui.MenuToolGroup
4131 ];
4132 };
4133
4134 /**
4135 * Theme logic.
4136 *
4137 * @abstract
4138 * @class
4139 *
4140 * @constructor
4141 * @param {Object} [config] Configuration options
4142 */
4143 OO.ui.Theme = function OoUiTheme( config ) {
4144 // Configuration initialization
4145 config = config || {};
4146 };
4147
4148 /* Setup */
4149
4150 OO.initClass( OO.ui.Theme );
4151
4152 /* Methods */
4153
4154 /**
4155 * Get a list of classes to be applied to a widget.
4156 *
4157 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4158 * otherwise state transitions will not work properly.
4159 *
4160 * @param {OO.ui.Element} element Element for which to get classes
4161 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4162 */
4163 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4164 return { on: [], off: [] };
4165 };
4166
4167 /**
4168 * Update CSS classes provided by the theme.
4169 *
4170 * For elements with theme logic hooks, this should be called any time there's a state change.
4171 *
4172 * @param {OO.ui.Element} element Element for which to update classes
4173 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4174 */
4175 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4176 var $elements = $( [] ),
4177 classes = this.getElementClasses( element );
4178
4179 if ( element.$icon ) {
4180 $elements = $elements.add( element.$icon );
4181 }
4182 if ( element.$indicator ) {
4183 $elements = $elements.add( element.$indicator );
4184 }
4185
4186 $elements
4187 .removeClass( classes.off.join( ' ' ) )
4188 .addClass( classes.on.join( ' ' ) );
4189 };
4190
4191 /**
4192 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4193 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4194 * order in which users will navigate through the focusable elements via the "tab" key.
4195 *
4196 * @example
4197 * // TabIndexedElement is mixed into the ButtonWidget class
4198 * // to provide a tabIndex property.
4199 * var button1 = new OO.ui.ButtonWidget( {
4200 * label: 'fourth',
4201 * tabIndex: 4
4202 * } );
4203 * var button2 = new OO.ui.ButtonWidget( {
4204 * label: 'second',
4205 * tabIndex: 2
4206 * } );
4207 * var button3 = new OO.ui.ButtonWidget( {
4208 * label: 'third',
4209 * tabIndex: 3
4210 * } );
4211 * var button4 = new OO.ui.ButtonWidget( {
4212 * label: 'first',
4213 * tabIndex: 1
4214 * } );
4215 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4216 *
4217 * @abstract
4218 * @class
4219 *
4220 * @constructor
4221 * @param {Object} [config] Configuration options
4222 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4223 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4224 * functionality will be applied to it instead.
4225 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4226 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4227 * to remove the element from the tab-navigation flow.
4228 */
4229 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4230 // Configuration initialization
4231 config = $.extend( { tabIndex: 0 }, config );
4232
4233 // Properties
4234 this.$tabIndexed = null;
4235 this.tabIndex = null;
4236
4237 // Events
4238 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4239
4240 // Initialization
4241 this.setTabIndex( config.tabIndex );
4242 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4243 };
4244
4245 /* Setup */
4246
4247 OO.initClass( OO.ui.mixin.TabIndexedElement );
4248
4249 /* Methods */
4250
4251 /**
4252 * Set the element that should use the tabindex functionality.
4253 *
4254 * This method is used to retarget a tabindex mixin so that its functionality applies
4255 * to the specified element. If an element is currently using the functionality, the mixin’s
4256 * effect on that element is removed before the new element is set up.
4257 *
4258 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4259 * @chainable
4260 */
4261 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4262 var tabIndex = this.tabIndex;
4263 // Remove attributes from old $tabIndexed
4264 this.setTabIndex( null );
4265 // Force update of new $tabIndexed
4266 this.$tabIndexed = $tabIndexed;
4267 this.tabIndex = tabIndex;
4268 return this.updateTabIndex();
4269 };
4270
4271 /**
4272 * Set the value of the tabindex.
4273 *
4274 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4275 * @chainable
4276 */
4277 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4278 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4279
4280 if ( this.tabIndex !== tabIndex ) {
4281 this.tabIndex = tabIndex;
4282 this.updateTabIndex();
4283 }
4284
4285 return this;
4286 };
4287
4288 /**
4289 * Update the `tabindex` attribute, in case of changes to tab index or
4290 * disabled state.
4291 *
4292 * @private
4293 * @chainable
4294 */
4295 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4296 if ( this.$tabIndexed ) {
4297 if ( this.tabIndex !== null ) {
4298 // Do not index over disabled elements
4299 this.$tabIndexed.attr( {
4300 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4301 // Support: ChromeVox and NVDA
4302 // These do not seem to inherit aria-disabled from parent elements
4303 'aria-disabled': this.isDisabled().toString()
4304 } );
4305 } else {
4306 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4307 }
4308 }
4309 return this;
4310 };
4311
4312 /**
4313 * Handle disable events.
4314 *
4315 * @private
4316 * @param {boolean} disabled Element is disabled
4317 */
4318 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4319 this.updateTabIndex();
4320 };
4321
4322 /**
4323 * Get the value of the tabindex.
4324 *
4325 * @return {number|null} Tabindex value
4326 */
4327 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4328 return this.tabIndex;
4329 };
4330
4331 /**
4332 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4333 * interface element that can be configured with access keys for accessibility.
4334 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4335 *
4336 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4337 * @abstract
4338 * @class
4339 *
4340 * @constructor
4341 * @param {Object} [config] Configuration options
4342 * @cfg {jQuery} [$button] The button element created by the class.
4343 * If this configuration is omitted, the button element will use a generated `<a>`.
4344 * @cfg {boolean} [framed=true] Render the button with a frame
4345 */
4346 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4347 // Configuration initialization
4348 config = config || {};
4349
4350 // Properties
4351 this.$button = null;
4352 this.framed = null;
4353 this.active = false;
4354 this.onMouseUpHandler = this.onMouseUp.bind( this );
4355 this.onMouseDownHandler = this.onMouseDown.bind( this );
4356 this.onKeyDownHandler = this.onKeyDown.bind( this );
4357 this.onKeyUpHandler = this.onKeyUp.bind( this );
4358 this.onClickHandler = this.onClick.bind( this );
4359 this.onKeyPressHandler = this.onKeyPress.bind( this );
4360
4361 // Initialization
4362 this.$element.addClass( 'oo-ui-buttonElement' );
4363 this.toggleFramed( config.framed === undefined || config.framed );
4364 this.setButtonElement( config.$button || $( '<a>' ) );
4365 };
4366
4367 /* Setup */
4368
4369 OO.initClass( OO.ui.mixin.ButtonElement );
4370
4371 /* Static Properties */
4372
4373 /**
4374 * Cancel mouse down events.
4375 *
4376 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4377 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4378 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4379 * parent widget.
4380 *
4381 * @static
4382 * @inheritable
4383 * @property {boolean}
4384 */
4385 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4386
4387 /* Events */
4388
4389 /**
4390 * A 'click' event is emitted when the button element is clicked.
4391 *
4392 * @event click
4393 */
4394
4395 /* Methods */
4396
4397 /**
4398 * Set the button element.
4399 *
4400 * This method is used to retarget a button mixin so that its functionality applies to
4401 * the specified button element instead of the one created by the class. If a button element
4402 * is already set, the method will remove the mixin’s effect on that element.
4403 *
4404 * @param {jQuery} $button Element to use as button
4405 */
4406 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4407 if ( this.$button ) {
4408 this.$button
4409 .removeClass( 'oo-ui-buttonElement-button' )
4410 .removeAttr( 'role accesskey' )
4411 .off( {
4412 mousedown: this.onMouseDownHandler,
4413 keydown: this.onKeyDownHandler,
4414 click: this.onClickHandler,
4415 keypress: this.onKeyPressHandler
4416 } );
4417 }
4418
4419 this.$button = $button
4420 .addClass( 'oo-ui-buttonElement-button' )
4421 .attr( { role: 'button' } )
4422 .on( {
4423 mousedown: this.onMouseDownHandler,
4424 keydown: this.onKeyDownHandler,
4425 click: this.onClickHandler,
4426 keypress: this.onKeyPressHandler
4427 } );
4428 };
4429
4430 /**
4431 * Handles mouse down events.
4432 *
4433 * @protected
4434 * @param {jQuery.Event} e Mouse down event
4435 */
4436 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4437 if ( this.isDisabled() || e.which !== 1 ) {
4438 return;
4439 }
4440 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4441 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4442 // reliably remove the pressed class
4443 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4444 // Prevent change of focus unless specifically configured otherwise
4445 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4446 return false;
4447 }
4448 };
4449
4450 /**
4451 * Handles mouse up events.
4452 *
4453 * @protected
4454 * @param {jQuery.Event} e Mouse up event
4455 */
4456 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4457 if ( this.isDisabled() || e.which !== 1 ) {
4458 return;
4459 }
4460 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4461 // Stop listening for mouseup, since we only needed this once
4462 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4463 };
4464
4465 /**
4466 * Handles mouse click events.
4467 *
4468 * @protected
4469 * @param {jQuery.Event} e Mouse click event
4470 * @fires click
4471 */
4472 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4473 if ( !this.isDisabled() && e.which === 1 ) {
4474 if ( this.emit( 'click' ) ) {
4475 return false;
4476 }
4477 }
4478 };
4479
4480 /**
4481 * Handles key down events.
4482 *
4483 * @protected
4484 * @param {jQuery.Event} e Key down event
4485 */
4486 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4487 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4488 return;
4489 }
4490 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4491 // Run the keyup handler no matter where the key is when the button is let go, so we can
4492 // reliably remove the pressed class
4493 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4494 };
4495
4496 /**
4497 * Handles key up events.
4498 *
4499 * @protected
4500 * @param {jQuery.Event} e Key up event
4501 */
4502 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4503 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4504 return;
4505 }
4506 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4507 // Stop listening for keyup, since we only needed this once
4508 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4509 };
4510
4511 /**
4512 * Handles key press events.
4513 *
4514 * @protected
4515 * @param {jQuery.Event} e Key press event
4516 * @fires click
4517 */
4518 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4519 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4520 if ( this.emit( 'click' ) ) {
4521 return false;
4522 }
4523 }
4524 };
4525
4526 /**
4527 * Check if button has a frame.
4528 *
4529 * @return {boolean} Button is framed
4530 */
4531 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4532 return this.framed;
4533 };
4534
4535 /**
4536 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4537 *
4538 * @param {boolean} [framed] Make button framed, omit to toggle
4539 * @chainable
4540 */
4541 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4542 framed = framed === undefined ? !this.framed : !!framed;
4543 if ( framed !== this.framed ) {
4544 this.framed = framed;
4545 this.$element
4546 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4547 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4548 this.updateThemeClasses();
4549 }
4550
4551 return this;
4552 };
4553
4554 /**
4555 * Set the button to its 'active' state.
4556 *
4557 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4558 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4559 * for other button types.
4560 *
4561 * @param {boolean} [value] Make button active
4562 * @chainable
4563 */
4564 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4565 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4566 return this;
4567 };
4568
4569 /**
4570 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4571 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4572 * items from the group is done through the interface the class provides.
4573 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4574 *
4575 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4576 *
4577 * @abstract
4578 * @class
4579 *
4580 * @constructor
4581 * @param {Object} [config] Configuration options
4582 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4583 * is omitted, the group element will use a generated `<div>`.
4584 */
4585 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4586 // Configuration initialization
4587 config = config || {};
4588
4589 // Properties
4590 this.$group = null;
4591 this.items = [];
4592 this.aggregateItemEvents = {};
4593
4594 // Initialization
4595 this.setGroupElement( config.$group || $( '<div>' ) );
4596 };
4597
4598 /* Methods */
4599
4600 /**
4601 * Set the group element.
4602 *
4603 * If an element is already set, items will be moved to the new element.
4604 *
4605 * @param {jQuery} $group Element to use as group
4606 */
4607 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4608 var i, len;
4609
4610 this.$group = $group;
4611 for ( i = 0, len = this.items.length; i < len; i++ ) {
4612 this.$group.append( this.items[ i ].$element );
4613 }
4614 };
4615
4616 /**
4617 * Check if a group contains no items.
4618 *
4619 * @return {boolean} Group is empty
4620 */
4621 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4622 return !this.items.length;
4623 };
4624
4625 /**
4626 * Get all items in the group.
4627 *
4628 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4629 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4630 * from a group).
4631 *
4632 * @return {OO.ui.Element[]} An array of items.
4633 */
4634 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4635 return this.items.slice( 0 );
4636 };
4637
4638 /**
4639 * Get an item by its data.
4640 *
4641 * Only the first item with matching data will be returned. To return all matching items,
4642 * use the #getItemsFromData method.
4643 *
4644 * @param {Object} data Item data to search for
4645 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4646 */
4647 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4648 var i, len, item,
4649 hash = OO.getHash( data );
4650
4651 for ( i = 0, len = this.items.length; i < len; i++ ) {
4652 item = this.items[ i ];
4653 if ( hash === OO.getHash( item.getData() ) ) {
4654 return item;
4655 }
4656 }
4657
4658 return null;
4659 };
4660
4661 /**
4662 * Get items by their data.
4663 *
4664 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4665 *
4666 * @param {Object} data Item data to search for
4667 * @return {OO.ui.Element[]} Items with equivalent data
4668 */
4669 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4670 var i, len, item,
4671 hash = OO.getHash( data ),
4672 items = [];
4673
4674 for ( i = 0, len = this.items.length; i < len; i++ ) {
4675 item = this.items[ i ];
4676 if ( hash === OO.getHash( item.getData() ) ) {
4677 items.push( item );
4678 }
4679 }
4680
4681 return items;
4682 };
4683
4684 /**
4685 * Aggregate the events emitted by the group.
4686 *
4687 * When events are aggregated, the group will listen to all contained items for the event,
4688 * and then emit the event under a new name. The new event will contain an additional leading
4689 * parameter containing the item that emitted the original event. Other arguments emitted from
4690 * the original event are passed through.
4691 *
4692 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4693 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4694 * A `null` value will remove aggregated events.
4695
4696 * @throws {Error} An error is thrown if aggregation already exists.
4697 */
4698 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4699 var i, len, item, add, remove, itemEvent, groupEvent;
4700
4701 for ( itemEvent in events ) {
4702 groupEvent = events[ itemEvent ];
4703
4704 // Remove existing aggregated event
4705 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4706 // Don't allow duplicate aggregations
4707 if ( groupEvent ) {
4708 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4709 }
4710 // Remove event aggregation from existing items
4711 for ( i = 0, len = this.items.length; i < len; i++ ) {
4712 item = this.items[ i ];
4713 if ( item.connect && item.disconnect ) {
4714 remove = {};
4715 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4716 item.disconnect( this, remove );
4717 }
4718 }
4719 // Prevent future items from aggregating event
4720 delete this.aggregateItemEvents[ itemEvent ];
4721 }
4722
4723 // Add new aggregate event
4724 if ( groupEvent ) {
4725 // Make future items aggregate event
4726 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4727 // Add event aggregation to existing items
4728 for ( i = 0, len = this.items.length; i < len; i++ ) {
4729 item = this.items[ i ];
4730 if ( item.connect && item.disconnect ) {
4731 add = {};
4732 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4733 item.connect( this, add );
4734 }
4735 }
4736 }
4737 }
4738 };
4739
4740 /**
4741 * Add items to the group.
4742 *
4743 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4744 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4745 *
4746 * @param {OO.ui.Element[]} items An array of items to add to the group
4747 * @param {number} [index] Index of the insertion point
4748 * @chainable
4749 */
4750 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4751 var i, len, item, event, events, currentIndex,
4752 itemElements = [];
4753
4754 for ( i = 0, len = items.length; i < len; i++ ) {
4755 item = items[ i ];
4756
4757 // Check if item exists then remove it first, effectively "moving" it
4758 currentIndex = this.items.indexOf( item );
4759 if ( currentIndex >= 0 ) {
4760 this.removeItems( [ item ] );
4761 // Adjust index to compensate for removal
4762 if ( currentIndex < index ) {
4763 index--;
4764 }
4765 }
4766 // Add the item
4767 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4768 events = {};
4769 for ( event in this.aggregateItemEvents ) {
4770 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4771 }
4772 item.connect( this, events );
4773 }
4774 item.setElementGroup( this );
4775 itemElements.push( item.$element.get( 0 ) );
4776 }
4777
4778 if ( index === undefined || index < 0 || index >= this.items.length ) {
4779 this.$group.append( itemElements );
4780 this.items.push.apply( this.items, items );
4781 } else if ( index === 0 ) {
4782 this.$group.prepend( itemElements );
4783 this.items.unshift.apply( this.items, items );
4784 } else {
4785 this.items[ index ].$element.before( itemElements );
4786 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4787 }
4788
4789 return this;
4790 };
4791
4792 /**
4793 * Remove the specified items from a group.
4794 *
4795 * Removed items are detached (not removed) from the DOM so that they may be reused.
4796 * To remove all items from a group, you may wish to use the #clearItems method instead.
4797 *
4798 * @param {OO.ui.Element[]} items An array of items to remove
4799 * @chainable
4800 */
4801 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4802 var i, len, item, index, remove, itemEvent;
4803
4804 // Remove specific items
4805 for ( i = 0, len = items.length; i < len; i++ ) {
4806 item = items[ i ];
4807 index = this.items.indexOf( item );
4808 if ( index !== -1 ) {
4809 if (
4810 item.connect && item.disconnect &&
4811 !$.isEmptyObject( this.aggregateItemEvents )
4812 ) {
4813 remove = {};
4814 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4815 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4816 }
4817 item.disconnect( this, remove );
4818 }
4819 item.setElementGroup( null );
4820 this.items.splice( index, 1 );
4821 item.$element.detach();
4822 }
4823 }
4824
4825 return this;
4826 };
4827
4828 /**
4829 * Clear all items from the group.
4830 *
4831 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4832 * To remove only a subset of items from a group, use the #removeItems method.
4833 *
4834 * @chainable
4835 */
4836 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4837 var i, len, item, remove, itemEvent;
4838
4839 // Remove all items
4840 for ( i = 0, len = this.items.length; i < len; i++ ) {
4841 item = this.items[ i ];
4842 if (
4843 item.connect && item.disconnect &&
4844 !$.isEmptyObject( this.aggregateItemEvents )
4845 ) {
4846 remove = {};
4847 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4848 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4849 }
4850 item.disconnect( this, remove );
4851 }
4852 item.setElementGroup( null );
4853 item.$element.detach();
4854 }
4855
4856 this.items = [];
4857 return this;
4858 };
4859
4860 /**
4861 * DraggableElement is a mixin class used to create elements that can be clicked
4862 * and dragged by a mouse to a new position within a group. This class must be used
4863 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4864 * the draggable elements.
4865 *
4866 * @abstract
4867 * @class
4868 *
4869 * @constructor
4870 */
4871 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4872 // Properties
4873 this.index = null;
4874
4875 // Initialize and events
4876 this.$element
4877 .attr( 'draggable', true )
4878 .addClass( 'oo-ui-draggableElement' )
4879 .on( {
4880 dragstart: this.onDragStart.bind( this ),
4881 dragover: this.onDragOver.bind( this ),
4882 dragend: this.onDragEnd.bind( this ),
4883 drop: this.onDrop.bind( this )
4884 } );
4885 };
4886
4887 OO.initClass( OO.ui.mixin.DraggableElement );
4888
4889 /* Events */
4890
4891 /**
4892 * @event dragstart
4893 *
4894 * A dragstart event is emitted when the user clicks and begins dragging an item.
4895 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4896 */
4897
4898 /**
4899 * @event dragend
4900 * A dragend event is emitted when the user drags an item and releases the mouse,
4901 * thus terminating the drag operation.
4902 */
4903
4904 /**
4905 * @event drop
4906 * A drop event is emitted when the user drags an item and then releases the mouse button
4907 * over a valid target.
4908 */
4909
4910 /* Static Properties */
4911
4912 /**
4913 * @inheritdoc OO.ui.mixin.ButtonElement
4914 */
4915 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4916
4917 /* Methods */
4918
4919 /**
4920 * Respond to dragstart event.
4921 *
4922 * @private
4923 * @param {jQuery.Event} event jQuery event
4924 * @fires dragstart
4925 */
4926 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
4927 var dataTransfer = e.originalEvent.dataTransfer;
4928 // Define drop effect
4929 dataTransfer.dropEffect = 'none';
4930 dataTransfer.effectAllowed = 'move';
4931 // Support: Firefox
4932 // We must set up a dataTransfer data property or Firefox seems to
4933 // ignore the fact the element is draggable.
4934 try {
4935 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4936 } catch ( err ) {
4937 // The above is only for Firefox. Move on if it fails.
4938 }
4939 // Add dragging class
4940 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4941 // Emit event
4942 this.emit( 'dragstart', this );
4943 return true;
4944 };
4945
4946 /**
4947 * Respond to dragend event.
4948 *
4949 * @private
4950 * @fires dragend
4951 */
4952 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
4953 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4954 this.emit( 'dragend' );
4955 };
4956
4957 /**
4958 * Handle drop event.
4959 *
4960 * @private
4961 * @param {jQuery.Event} event jQuery event
4962 * @fires drop
4963 */
4964 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
4965 e.preventDefault();
4966 this.emit( 'drop', e );
4967 };
4968
4969 /**
4970 * In order for drag/drop to work, the dragover event must
4971 * return false and stop propogation.
4972 *
4973 * @private
4974 */
4975 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
4976 e.preventDefault();
4977 };
4978
4979 /**
4980 * Set item index.
4981 * Store it in the DOM so we can access from the widget drag event
4982 *
4983 * @private
4984 * @param {number} Item index
4985 */
4986 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
4987 if ( this.index !== index ) {
4988 this.index = index;
4989 this.$element.data( 'index', index );
4990 }
4991 };
4992
4993 /**
4994 * Get item index
4995 *
4996 * @private
4997 * @return {number} Item index
4998 */
4999 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5000 return this.index;
5001 };
5002
5003 /**
5004 * DraggableGroupElement is a mixin class used to create a group element to
5005 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5006 * The class is used with OO.ui.mixin.DraggableElement.
5007 *
5008 * @abstract
5009 * @class
5010 * @mixins OO.ui.mixin.GroupElement
5011 *
5012 * @constructor
5013 * @param {Object} [config] Configuration options
5014 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5015 * should match the layout of the items. Items displayed in a single row
5016 * or in several rows should use horizontal orientation. The vertical orientation should only be
5017 * used when the items are displayed in a single column. Defaults to 'vertical'
5018 */
5019 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5020 // Configuration initialization
5021 config = config || {};
5022
5023 // Parent constructor
5024 OO.ui.mixin.GroupElement.call( this, config );
5025
5026 // Properties
5027 this.orientation = config.orientation || 'vertical';
5028 this.dragItem = null;
5029 this.itemDragOver = null;
5030 this.itemKeys = {};
5031 this.sideInsertion = '';
5032
5033 // Events
5034 this.aggregate( {
5035 dragstart: 'itemDragStart',
5036 dragend: 'itemDragEnd',
5037 drop: 'itemDrop'
5038 } );
5039 this.connect( this, {
5040 itemDragStart: 'onItemDragStart',
5041 itemDrop: 'onItemDrop',
5042 itemDragEnd: 'onItemDragEnd'
5043 } );
5044 this.$element.on( {
5045 dragover: this.onDragOver.bind( this ),
5046 dragleave: this.onDragLeave.bind( this )
5047 } );
5048
5049 // Initialize
5050 if ( Array.isArray( config.items ) ) {
5051 this.addItems( config.items );
5052 }
5053 this.$placeholder = $( '<div>' )
5054 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5055 this.$element
5056 .addClass( 'oo-ui-draggableGroupElement' )
5057 .append( this.$status )
5058 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5059 .prepend( this.$placeholder );
5060 };
5061
5062 /* Setup */
5063 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5064
5065 /* Events */
5066
5067 /**
5068 * A 'reorder' event is emitted when the order of items in the group changes.
5069 *
5070 * @event reorder
5071 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5072 * @param {number} [newIndex] New index for the item
5073 */
5074
5075 /* Methods */
5076
5077 /**
5078 * Respond to item drag start event
5079 *
5080 * @private
5081 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5082 */
5083 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5084 var i, len;
5085
5086 // Map the index of each object
5087 for ( i = 0, len = this.items.length; i < len; i++ ) {
5088 this.items[ i ].setIndex( i );
5089 }
5090
5091 if ( this.orientation === 'horizontal' ) {
5092 // Set the height of the indicator
5093 this.$placeholder.css( {
5094 height: item.$element.outerHeight(),
5095 width: 2
5096 } );
5097 } else {
5098 // Set the width of the indicator
5099 this.$placeholder.css( {
5100 height: 2,
5101 width: item.$element.outerWidth()
5102 } );
5103 }
5104 this.setDragItem( item );
5105 };
5106
5107 /**
5108 * Respond to item drag end event
5109 *
5110 * @private
5111 */
5112 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5113 this.unsetDragItem();
5114 return false;
5115 };
5116
5117 /**
5118 * Handle drop event and switch the order of the items accordingly
5119 *
5120 * @private
5121 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5122 * @fires reorder
5123 */
5124 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5125 var toIndex = item.getIndex();
5126 // Check if the dropped item is from the current group
5127 // TODO: Figure out a way to configure a list of legally droppable
5128 // elements even if they are not yet in the list
5129 if ( this.getDragItem() ) {
5130 // If the insertion point is 'after', the insertion index
5131 // is shifted to the right (or to the left in RTL, hence 'after')
5132 if ( this.sideInsertion === 'after' ) {
5133 toIndex++;
5134 }
5135 // Emit change event
5136 this.emit( 'reorder', this.getDragItem(), toIndex );
5137 }
5138 this.unsetDragItem();
5139 // Return false to prevent propogation
5140 return false;
5141 };
5142
5143 /**
5144 * Handle dragleave event.
5145 *
5146 * @private
5147 */
5148 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5149 // This means the item was dragged outside the widget
5150 this.$placeholder
5151 .css( 'left', 0 )
5152 .addClass( 'oo-ui-element-hidden' );
5153 };
5154
5155 /**
5156 * Respond to dragover event
5157 *
5158 * @private
5159 * @param {jQuery.Event} event Event details
5160 */
5161 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5162 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5163 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5164 clientX = e.originalEvent.clientX,
5165 clientY = e.originalEvent.clientY;
5166
5167 // Get the OptionWidget item we are dragging over
5168 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5169 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5170 if ( $optionWidget[ 0 ] ) {
5171 itemOffset = $optionWidget.offset();
5172 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5173 itemPosition = $optionWidget.position();
5174 itemIndex = $optionWidget.data( 'index' );
5175 }
5176
5177 if (
5178 itemOffset &&
5179 this.isDragging() &&
5180 itemIndex !== this.getDragItem().getIndex()
5181 ) {
5182 if ( this.orientation === 'horizontal' ) {
5183 // Calculate where the mouse is relative to the item width
5184 itemSize = itemBoundingRect.width;
5185 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5186 dragPosition = clientX;
5187 // Which side of the item we hover over will dictate
5188 // where the placeholder will appear, on the left or
5189 // on the right
5190 cssOutput = {
5191 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5192 top: itemPosition.top
5193 };
5194 } else {
5195 // Calculate where the mouse is relative to the item height
5196 itemSize = itemBoundingRect.height;
5197 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5198 dragPosition = clientY;
5199 // Which side of the item we hover over will dictate
5200 // where the placeholder will appear, on the top or
5201 // on the bottom
5202 cssOutput = {
5203 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5204 left: itemPosition.left
5205 };
5206 }
5207 // Store whether we are before or after an item to rearrange
5208 // For horizontal layout, we need to account for RTL, as this is flipped
5209 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5210 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5211 } else {
5212 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5213 }
5214 // Add drop indicator between objects
5215 this.$placeholder
5216 .css( cssOutput )
5217 .removeClass( 'oo-ui-element-hidden' );
5218 } else {
5219 // This means the item was dragged outside the widget
5220 this.$placeholder
5221 .css( 'left', 0 )
5222 .addClass( 'oo-ui-element-hidden' );
5223 }
5224 // Prevent default
5225 e.preventDefault();
5226 };
5227
5228 /**
5229 * Set a dragged item
5230 *
5231 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5232 */
5233 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5234 this.dragItem = item;
5235 };
5236
5237 /**
5238 * Unset the current dragged item
5239 */
5240 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5241 this.dragItem = null;
5242 this.itemDragOver = null;
5243 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5244 this.sideInsertion = '';
5245 };
5246
5247 /**
5248 * Get the item that is currently being dragged.
5249 *
5250 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5251 */
5252 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5253 return this.dragItem;
5254 };
5255
5256 /**
5257 * Check if an item in the group is currently being dragged.
5258 *
5259 * @return {Boolean} Item is being dragged
5260 */
5261 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5262 return this.getDragItem() !== null;
5263 };
5264
5265 /**
5266 * IconElement is often mixed into other classes to generate an icon.
5267 * Icons are graphics, about the size of normal text. They are used to aid the user
5268 * in locating a control or to convey information in a space-efficient way. See the
5269 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5270 * included in the library.
5271 *
5272 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5273 *
5274 * @abstract
5275 * @class
5276 *
5277 * @constructor
5278 * @param {Object} [config] Configuration options
5279 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5280 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5281 * the icon element be set to an existing icon instead of the one generated by this class, set a
5282 * value using a jQuery selection. For example:
5283 *
5284 * // Use a <div> tag instead of a <span>
5285 * $icon: $("<div>")
5286 * // Use an existing icon element instead of the one generated by the class
5287 * $icon: this.$element
5288 * // Use an icon element from a child widget
5289 * $icon: this.childwidget.$element
5290 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5291 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5292 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5293 * by the user's language.
5294 *
5295 * Example of an i18n map:
5296 *
5297 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5298 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5299 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5300 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5301 * text. The icon title is displayed when users move the mouse over the icon.
5302 */
5303 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5304 // Configuration initialization
5305 config = config || {};
5306
5307 // Properties
5308 this.$icon = null;
5309 this.icon = null;
5310 this.iconTitle = null;
5311
5312 // Initialization
5313 this.setIcon( config.icon || this.constructor.static.icon );
5314 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5315 this.setIconElement( config.$icon || $( '<span>' ) );
5316 };
5317
5318 /* Setup */
5319
5320 OO.initClass( OO.ui.mixin.IconElement );
5321
5322 /* Static Properties */
5323
5324 /**
5325 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5326 * for i18n purposes and contains a `default` icon name and additional names keyed by
5327 * language code. The `default` name is used when no icon is keyed by the user's language.
5328 *
5329 * Example of an i18n map:
5330 *
5331 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5332 *
5333 * Note: the static property will be overridden if the #icon configuration is used.
5334 *
5335 * @static
5336 * @inheritable
5337 * @property {Object|string}
5338 */
5339 OO.ui.mixin.IconElement.static.icon = null;
5340
5341 /**
5342 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5343 * function that returns title text, or `null` for no title.
5344 *
5345 * The static property will be overridden if the #iconTitle configuration is used.
5346 *
5347 * @static
5348 * @inheritable
5349 * @property {string|Function|null}
5350 */
5351 OO.ui.mixin.IconElement.static.iconTitle = null;
5352
5353 /* Methods */
5354
5355 /**
5356 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5357 * applies to the specified icon element instead of the one created by the class. If an icon
5358 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5359 * and mixin methods will no longer affect the element.
5360 *
5361 * @param {jQuery} $icon Element to use as icon
5362 */
5363 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5364 if ( this.$icon ) {
5365 this.$icon
5366 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5367 .removeAttr( 'title' );
5368 }
5369
5370 this.$icon = $icon
5371 .addClass( 'oo-ui-iconElement-icon' )
5372 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5373 if ( this.iconTitle !== null ) {
5374 this.$icon.attr( 'title', this.iconTitle );
5375 }
5376
5377 this.updateThemeClasses();
5378 };
5379
5380 /**
5381 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5382 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5383 * for an example.
5384 *
5385 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5386 * by language code, or `null` to remove the icon.
5387 * @chainable
5388 */
5389 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5390 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5391 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5392
5393 if ( this.icon !== icon ) {
5394 if ( this.$icon ) {
5395 if ( this.icon !== null ) {
5396 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5397 }
5398 if ( icon !== null ) {
5399 this.$icon.addClass( 'oo-ui-icon-' + icon );
5400 }
5401 }
5402 this.icon = icon;
5403 }
5404
5405 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5406 this.updateThemeClasses();
5407
5408 return this;
5409 };
5410
5411 /**
5412 * Set the icon title. Use `null` to remove the title.
5413 *
5414 * @param {string|Function|null} iconTitle A text string used as the icon title,
5415 * a function that returns title text, or `null` for no title.
5416 * @chainable
5417 */
5418 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5419 iconTitle = typeof iconTitle === 'function' ||
5420 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5421 OO.ui.resolveMsg( iconTitle ) : null;
5422
5423 if ( this.iconTitle !== iconTitle ) {
5424 this.iconTitle = iconTitle;
5425 if ( this.$icon ) {
5426 if ( this.iconTitle !== null ) {
5427 this.$icon.attr( 'title', iconTitle );
5428 } else {
5429 this.$icon.removeAttr( 'title' );
5430 }
5431 }
5432 }
5433
5434 return this;
5435 };
5436
5437 /**
5438 * Get the symbolic name of the icon.
5439 *
5440 * @return {string} Icon name
5441 */
5442 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5443 return this.icon;
5444 };
5445
5446 /**
5447 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5448 *
5449 * @return {string} Icon title text
5450 */
5451 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5452 return this.iconTitle;
5453 };
5454
5455 /**
5456 * IndicatorElement is often mixed into other classes to generate an indicator.
5457 * Indicators are small graphics that are generally used in two ways:
5458 *
5459 * - To draw attention to the status of an item. For example, an indicator might be
5460 * used to show that an item in a list has errors that need to be resolved.
5461 * - To clarify the function of a control that acts in an exceptional way (a button
5462 * that opens a menu instead of performing an action directly, for example).
5463 *
5464 * For a list of indicators included in the library, please see the
5465 * [OOjs UI documentation on MediaWiki] [1].
5466 *
5467 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5468 *
5469 * @abstract
5470 * @class
5471 *
5472 * @constructor
5473 * @param {Object} [config] Configuration options
5474 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5475 * configuration is omitted, the indicator element will use a generated `<span>`.
5476 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5477 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5478 * in the library.
5479 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5480 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5481 * or a function that returns title text. The indicator title is displayed when users move
5482 * the mouse over the indicator.
5483 */
5484 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5485 // Configuration initialization
5486 config = config || {};
5487
5488 // Properties
5489 this.$indicator = null;
5490 this.indicator = null;
5491 this.indicatorTitle = null;
5492
5493 // Initialization
5494 this.setIndicator( config.indicator || this.constructor.static.indicator );
5495 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5496 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5497 };
5498
5499 /* Setup */
5500
5501 OO.initClass( OO.ui.mixin.IndicatorElement );
5502
5503 /* Static Properties */
5504
5505 /**
5506 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5507 * The static property will be overridden if the #indicator configuration is used.
5508 *
5509 * @static
5510 * @inheritable
5511 * @property {string|null}
5512 */
5513 OO.ui.mixin.IndicatorElement.static.indicator = null;
5514
5515 /**
5516 * A text string used as the indicator title, a function that returns title text, or `null`
5517 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5518 *
5519 * @static
5520 * @inheritable
5521 * @property {string|Function|null}
5522 */
5523 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5524
5525 /* Methods */
5526
5527 /**
5528 * Set the indicator element.
5529 *
5530 * If an element is already set, it will be cleaned up before setting up the new element.
5531 *
5532 * @param {jQuery} $indicator Element to use as indicator
5533 */
5534 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5535 if ( this.$indicator ) {
5536 this.$indicator
5537 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5538 .removeAttr( 'title' );
5539 }
5540
5541 this.$indicator = $indicator
5542 .addClass( 'oo-ui-indicatorElement-indicator' )
5543 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5544 if ( this.indicatorTitle !== null ) {
5545 this.$indicator.attr( 'title', this.indicatorTitle );
5546 }
5547
5548 this.updateThemeClasses();
5549 };
5550
5551 /**
5552 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5553 *
5554 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5555 * @chainable
5556 */
5557 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5558 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5559
5560 if ( this.indicator !== indicator ) {
5561 if ( this.$indicator ) {
5562 if ( this.indicator !== null ) {
5563 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5564 }
5565 if ( indicator !== null ) {
5566 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5567 }
5568 }
5569 this.indicator = indicator;
5570 }
5571
5572 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5573 this.updateThemeClasses();
5574
5575 return this;
5576 };
5577
5578 /**
5579 * Set the indicator title.
5580 *
5581 * The title is displayed when a user moves the mouse over the indicator.
5582 *
5583 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5584 * `null` for no indicator title
5585 * @chainable
5586 */
5587 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5588 indicatorTitle = typeof indicatorTitle === 'function' ||
5589 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5590 OO.ui.resolveMsg( indicatorTitle ) : null;
5591
5592 if ( this.indicatorTitle !== indicatorTitle ) {
5593 this.indicatorTitle = indicatorTitle;
5594 if ( this.$indicator ) {
5595 if ( this.indicatorTitle !== null ) {
5596 this.$indicator.attr( 'title', indicatorTitle );
5597 } else {
5598 this.$indicator.removeAttr( 'title' );
5599 }
5600 }
5601 }
5602
5603 return this;
5604 };
5605
5606 /**
5607 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5608 *
5609 * @return {string} Symbolic name of indicator
5610 */
5611 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5612 return this.indicator;
5613 };
5614
5615 /**
5616 * Get the indicator title.
5617 *
5618 * The title is displayed when a user moves the mouse over the indicator.
5619 *
5620 * @return {string} Indicator title text
5621 */
5622 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5623 return this.indicatorTitle;
5624 };
5625
5626 /**
5627 * LabelElement is often mixed into other classes to generate a label, which
5628 * helps identify the function of an interface element.
5629 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5630 *
5631 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5632 *
5633 * @abstract
5634 * @class
5635 *
5636 * @constructor
5637 * @param {Object} [config] Configuration options
5638 * @cfg {jQuery} [$label] The label element created by the class. If this
5639 * configuration is omitted, the label element will use a generated `<span>`.
5640 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5641 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5642 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5643 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5644 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5645 * The label will be truncated to fit if necessary.
5646 */
5647 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5648 // Configuration initialization
5649 config = config || {};
5650
5651 // Properties
5652 this.$label = null;
5653 this.label = null;
5654 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5655
5656 // Initialization
5657 this.setLabel( config.label || this.constructor.static.label );
5658 this.setLabelElement( config.$label || $( '<span>' ) );
5659 };
5660
5661 /* Setup */
5662
5663 OO.initClass( OO.ui.mixin.LabelElement );
5664
5665 /* Events */
5666
5667 /**
5668 * @event labelChange
5669 * @param {string} value
5670 */
5671
5672 /* Static Properties */
5673
5674 /**
5675 * The label text. The label can be specified as a plaintext string, a function that will
5676 * produce a string in the future, or `null` for no label. The static value will
5677 * be overridden if a label is specified with the #label config option.
5678 *
5679 * @static
5680 * @inheritable
5681 * @property {string|Function|null}
5682 */
5683 OO.ui.mixin.LabelElement.static.label = null;
5684
5685 /* Methods */
5686
5687 /**
5688 * Set the label element.
5689 *
5690 * If an element is already set, it will be cleaned up before setting up the new element.
5691 *
5692 * @param {jQuery} $label Element to use as label
5693 */
5694 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5695 if ( this.$label ) {
5696 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5697 }
5698
5699 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5700 this.setLabelContent( this.label );
5701 };
5702
5703 /**
5704 * Set the label.
5705 *
5706 * An empty string will result in the label being hidden. A string containing only whitespace will
5707 * be converted to a single `&nbsp;`.
5708 *
5709 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5710 * text; or null for no label
5711 * @chainable
5712 */
5713 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5714 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5715 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5716
5717 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5718
5719 if ( this.label !== label ) {
5720 if ( this.$label ) {
5721 this.setLabelContent( label );
5722 }
5723 this.label = label;
5724 this.emit( 'labelChange' );
5725 }
5726
5727 return this;
5728 };
5729
5730 /**
5731 * Get the label.
5732 *
5733 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5734 * text; or null for no label
5735 */
5736 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5737 return this.label;
5738 };
5739
5740 /**
5741 * Fit the label.
5742 *
5743 * @chainable
5744 */
5745 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5746 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5747 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5748 }
5749
5750 return this;
5751 };
5752
5753 /**
5754 * Set the content of the label.
5755 *
5756 * Do not call this method until after the label element has been set by #setLabelElement.
5757 *
5758 * @private
5759 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5760 * text; or null for no label
5761 */
5762 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5763 if ( typeof label === 'string' ) {
5764 if ( label.match( /^\s*$/ ) ) {
5765 // Convert whitespace only string to a single non-breaking space
5766 this.$label.html( '&nbsp;' );
5767 } else {
5768 this.$label.text( label );
5769 }
5770 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5771 this.$label.html( label.toString() );
5772 } else if ( label instanceof jQuery ) {
5773 this.$label.empty().append( label );
5774 } else {
5775 this.$label.empty();
5776 }
5777 };
5778
5779 /**
5780 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5781 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5782 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5783 * from the lookup menu, that value becomes the value of the input field.
5784 *
5785 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5786 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5787 * re-enable lookups.
5788 *
5789 * See the [OOjs UI demos][1] for an example.
5790 *
5791 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5792 *
5793 * @class
5794 * @abstract
5795 *
5796 * @constructor
5797 * @param {Object} [config] Configuration options
5798 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5799 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5800 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5801 * By default, the lookup menu is not generated and displayed until the user begins to type.
5802 */
5803 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5804 // Configuration initialization
5805 config = config || {};
5806
5807 // Properties
5808 this.$overlay = config.$overlay || this.$element;
5809 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5810 widget: this,
5811 input: this,
5812 $container: config.$container || this.$element
5813 } );
5814
5815 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5816
5817 this.lookupCache = {};
5818 this.lookupQuery = null;
5819 this.lookupRequest = null;
5820 this.lookupsDisabled = false;
5821 this.lookupInputFocused = false;
5822
5823 // Events
5824 this.$input.on( {
5825 focus: this.onLookupInputFocus.bind( this ),
5826 blur: this.onLookupInputBlur.bind( this ),
5827 mousedown: this.onLookupInputMouseDown.bind( this )
5828 } );
5829 this.connect( this, { change: 'onLookupInputChange' } );
5830 this.lookupMenu.connect( this, {
5831 toggle: 'onLookupMenuToggle',
5832 choose: 'onLookupMenuItemChoose'
5833 } );
5834
5835 // Initialization
5836 this.$element.addClass( 'oo-ui-lookupElement' );
5837 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5838 this.$overlay.append( this.lookupMenu.$element );
5839 };
5840
5841 /* Methods */
5842
5843 /**
5844 * Handle input focus event.
5845 *
5846 * @protected
5847 * @param {jQuery.Event} e Input focus event
5848 */
5849 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5850 this.lookupInputFocused = true;
5851 this.populateLookupMenu();
5852 };
5853
5854 /**
5855 * Handle input blur event.
5856 *
5857 * @protected
5858 * @param {jQuery.Event} e Input blur event
5859 */
5860 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5861 this.closeLookupMenu();
5862 this.lookupInputFocused = false;
5863 };
5864
5865 /**
5866 * Handle input mouse down event.
5867 *
5868 * @protected
5869 * @param {jQuery.Event} e Input mouse down event
5870 */
5871 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5872 // Only open the menu if the input was already focused.
5873 // This way we allow the user to open the menu again after closing it with Esc
5874 // by clicking in the input. Opening (and populating) the menu when initially
5875 // clicking into the input is handled by the focus handler.
5876 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5877 this.populateLookupMenu();
5878 }
5879 };
5880
5881 /**
5882 * Handle input change event.
5883 *
5884 * @protected
5885 * @param {string} value New input value
5886 */
5887 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5888 if ( this.lookupInputFocused ) {
5889 this.populateLookupMenu();
5890 }
5891 };
5892
5893 /**
5894 * Handle the lookup menu being shown/hidden.
5895 *
5896 * @protected
5897 * @param {boolean} visible Whether the lookup menu is now visible.
5898 */
5899 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5900 if ( !visible ) {
5901 // When the menu is hidden, abort any active request and clear the menu.
5902 // This has to be done here in addition to closeLookupMenu(), because
5903 // MenuSelectWidget will close itself when the user presses Esc.
5904 this.abortLookupRequest();
5905 this.lookupMenu.clearItems();
5906 }
5907 };
5908
5909 /**
5910 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5911 *
5912 * @protected
5913 * @param {OO.ui.MenuOptionWidget} item Selected item
5914 */
5915 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5916 this.setValue( item.getData() );
5917 };
5918
5919 /**
5920 * Get lookup menu.
5921 *
5922 * @private
5923 * @return {OO.ui.FloatingMenuSelectWidget}
5924 */
5925 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
5926 return this.lookupMenu;
5927 };
5928
5929 /**
5930 * Disable or re-enable lookups.
5931 *
5932 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5933 *
5934 * @param {boolean} disabled Disable lookups
5935 */
5936 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5937 this.lookupsDisabled = !!disabled;
5938 };
5939
5940 /**
5941 * Open the menu. If there are no entries in the menu, this does nothing.
5942 *
5943 * @private
5944 * @chainable
5945 */
5946 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
5947 if ( !this.lookupMenu.isEmpty() ) {
5948 this.lookupMenu.toggle( true );
5949 }
5950 return this;
5951 };
5952
5953 /**
5954 * Close the menu, empty it, and abort any pending request.
5955 *
5956 * @private
5957 * @chainable
5958 */
5959 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
5960 this.lookupMenu.toggle( false );
5961 this.abortLookupRequest();
5962 this.lookupMenu.clearItems();
5963 return this;
5964 };
5965
5966 /**
5967 * Request menu items based on the input's current value, and when they arrive,
5968 * populate the menu with these items and show the menu.
5969 *
5970 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5971 *
5972 * @private
5973 * @chainable
5974 */
5975 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
5976 var widget = this,
5977 value = this.getValue();
5978
5979 if ( this.lookupsDisabled ) {
5980 return;
5981 }
5982
5983 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5984 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5985 this.closeLookupMenu();
5986 // Skip population if there is already a request pending for the current value
5987 } else if ( value !== this.lookupQuery ) {
5988 this.getLookupMenuItems()
5989 .done( function ( items ) {
5990 widget.lookupMenu.clearItems();
5991 if ( items.length ) {
5992 widget.lookupMenu
5993 .addItems( items )
5994 .toggle( true );
5995 widget.initializeLookupMenuSelection();
5996 } else {
5997 widget.lookupMenu.toggle( false );
5998 }
5999 } )
6000 .fail( function () {
6001 widget.lookupMenu.clearItems();
6002 } );
6003 }
6004
6005 return this;
6006 };
6007
6008 /**
6009 * Highlight the first selectable item in the menu.
6010 *
6011 * @private
6012 * @chainable
6013 */
6014 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6015 if ( !this.lookupMenu.getSelectedItem() ) {
6016 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6017 }
6018 };
6019
6020 /**
6021 * Get lookup menu items for the current query.
6022 *
6023 * @private
6024 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6025 * the done event. If the request was aborted to make way for a subsequent request, this promise
6026 * will not be rejected: it will remain pending forever.
6027 */
6028 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6029 var widget = this,
6030 value = this.getValue(),
6031 deferred = $.Deferred(),
6032 ourRequest;
6033
6034 this.abortLookupRequest();
6035 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6036 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6037 } else {
6038 this.pushPending();
6039 this.lookupQuery = value;
6040 ourRequest = this.lookupRequest = this.getLookupRequest();
6041 ourRequest
6042 .always( function () {
6043 // We need to pop pending even if this is an old request, otherwise
6044 // the widget will remain pending forever.
6045 // TODO: this assumes that an aborted request will fail or succeed soon after
6046 // being aborted, or at least eventually. It would be nice if we could popPending()
6047 // at abort time, but only if we knew that we hadn't already called popPending()
6048 // for that request.
6049 widget.popPending();
6050 } )
6051 .done( function ( response ) {
6052 // If this is an old request (and aborting it somehow caused it to still succeed),
6053 // ignore its success completely
6054 if ( ourRequest === widget.lookupRequest ) {
6055 widget.lookupQuery = null;
6056 widget.lookupRequest = null;
6057 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6058 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6059 }
6060 } )
6061 .fail( function () {
6062 // If this is an old request (or a request failing because it's being aborted),
6063 // ignore its failure completely
6064 if ( ourRequest === widget.lookupRequest ) {
6065 widget.lookupQuery = null;
6066 widget.lookupRequest = null;
6067 deferred.reject();
6068 }
6069 } );
6070 }
6071 return deferred.promise();
6072 };
6073
6074 /**
6075 * Abort the currently pending lookup request, if any.
6076 *
6077 * @private
6078 */
6079 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6080 var oldRequest = this.lookupRequest;
6081 if ( oldRequest ) {
6082 // First unset this.lookupRequest to the fail handler will notice
6083 // that the request is no longer current
6084 this.lookupRequest = null;
6085 this.lookupQuery = null;
6086 oldRequest.abort();
6087 }
6088 };
6089
6090 /**
6091 * Get a new request object of the current lookup query value.
6092 *
6093 * @protected
6094 * @abstract
6095 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6096 */
6097 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6098 // Stub, implemented in subclass
6099 return null;
6100 };
6101
6102 /**
6103 * Pre-process data returned by the request from #getLookupRequest.
6104 *
6105 * The return value of this function will be cached, and any further queries for the given value
6106 * will use the cache rather than doing API requests.
6107 *
6108 * @protected
6109 * @abstract
6110 * @param {Mixed} response Response from server
6111 * @return {Mixed} Cached result data
6112 */
6113 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6114 // Stub, implemented in subclass
6115 return [];
6116 };
6117
6118 /**
6119 * Get a list of menu option widgets from the (possibly cached) data returned by
6120 * #getLookupCacheDataFromResponse.
6121 *
6122 * @protected
6123 * @abstract
6124 * @param {Mixed} data Cached result data, usually an array
6125 * @return {OO.ui.MenuOptionWidget[]} Menu items
6126 */
6127 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6128 // Stub, implemented in subclass
6129 return [];
6130 };
6131
6132 /**
6133 * Set the read-only state of the widget.
6134 *
6135 * This will also disable/enable the lookups functionality.
6136 *
6137 * @param {boolean} readOnly Make input read-only
6138 * @chainable
6139 */
6140 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6141 // Parent method
6142 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6143 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6144
6145 this.setLookupsDisabled( readOnly );
6146 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6147 if ( readOnly && this.lookupMenu ) {
6148 this.closeLookupMenu();
6149 }
6150
6151 return this;
6152 };
6153
6154 /**
6155 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6156 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6157 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6158 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6159 *
6160 * @abstract
6161 * @class
6162 *
6163 * @constructor
6164 * @param {Object} [config] Configuration options
6165 * @cfg {Object} [popup] Configuration to pass to popup
6166 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6167 */
6168 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6169 // Configuration initialization
6170 config = config || {};
6171
6172 // Properties
6173 this.popup = new OO.ui.PopupWidget( $.extend(
6174 { autoClose: true },
6175 config.popup,
6176 { $autoCloseIgnore: this.$element }
6177 ) );
6178 };
6179
6180 /* Methods */
6181
6182 /**
6183 * Get popup.
6184 *
6185 * @return {OO.ui.PopupWidget} Popup widget
6186 */
6187 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6188 return this.popup;
6189 };
6190
6191 /**
6192 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6193 * additional functionality to an element created by another class. The class provides
6194 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6195 * which are used to customize the look and feel of a widget to better describe its
6196 * importance and functionality.
6197 *
6198 * The library currently contains the following styling flags for general use:
6199 *
6200 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6201 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6202 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6203 *
6204 * The flags affect the appearance of the buttons:
6205 *
6206 * @example
6207 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6208 * var button1 = new OO.ui.ButtonWidget( {
6209 * label: 'Constructive',
6210 * flags: 'constructive'
6211 * } );
6212 * var button2 = new OO.ui.ButtonWidget( {
6213 * label: 'Destructive',
6214 * flags: 'destructive'
6215 * } );
6216 * var button3 = new OO.ui.ButtonWidget( {
6217 * label: 'Progressive',
6218 * flags: 'progressive'
6219 * } );
6220 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6221 *
6222 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6223 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6224 *
6225 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6226 *
6227 * @abstract
6228 * @class
6229 *
6230 * @constructor
6231 * @param {Object} [config] Configuration options
6232 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6233 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6234 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6235 * @cfg {jQuery} [$flagged] The flagged element. By default,
6236 * the flagged functionality is applied to the element created by the class ($element).
6237 * If a different element is specified, the flagged functionality will be applied to it instead.
6238 */
6239 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6240 // Configuration initialization
6241 config = config || {};
6242
6243 // Properties
6244 this.flags = {};
6245 this.$flagged = null;
6246
6247 // Initialization
6248 this.setFlags( config.flags );
6249 this.setFlaggedElement( config.$flagged || this.$element );
6250 };
6251
6252 /* Events */
6253
6254 /**
6255 * @event flag
6256 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6257 * parameter contains the name of each modified flag and indicates whether it was
6258 * added or removed.
6259 *
6260 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6261 * that the flag was added, `false` that the flag was removed.
6262 */
6263
6264 /* Methods */
6265
6266 /**
6267 * Set the flagged element.
6268 *
6269 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6270 * If an element is already set, the method will remove the mixin’s effect on that element.
6271 *
6272 * @param {jQuery} $flagged Element that should be flagged
6273 */
6274 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6275 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6276 return 'oo-ui-flaggedElement-' + flag;
6277 } ).join( ' ' );
6278
6279 if ( this.$flagged ) {
6280 this.$flagged.removeClass( classNames );
6281 }
6282
6283 this.$flagged = $flagged.addClass( classNames );
6284 };
6285
6286 /**
6287 * Check if the specified flag is set.
6288 *
6289 * @param {string} flag Name of flag
6290 * @return {boolean} The flag is set
6291 */
6292 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6293 // This may be called before the constructor, thus before this.flags is set
6294 return this.flags && ( flag in this.flags );
6295 };
6296
6297 /**
6298 * Get the names of all flags set.
6299 *
6300 * @return {string[]} Flag names
6301 */
6302 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6303 // This may be called before the constructor, thus before this.flags is set
6304 return Object.keys( this.flags || {} );
6305 };
6306
6307 /**
6308 * Clear all flags.
6309 *
6310 * @chainable
6311 * @fires flag
6312 */
6313 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6314 var flag, className,
6315 changes = {},
6316 remove = [],
6317 classPrefix = 'oo-ui-flaggedElement-';
6318
6319 for ( flag in this.flags ) {
6320 className = classPrefix + flag;
6321 changes[ flag ] = false;
6322 delete this.flags[ flag ];
6323 remove.push( className );
6324 }
6325
6326 if ( this.$flagged ) {
6327 this.$flagged.removeClass( remove.join( ' ' ) );
6328 }
6329
6330 this.updateThemeClasses();
6331 this.emit( 'flag', changes );
6332
6333 return this;
6334 };
6335
6336 /**
6337 * Add one or more flags.
6338 *
6339 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6340 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6341 * be added (`true`) or removed (`false`).
6342 * @chainable
6343 * @fires flag
6344 */
6345 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6346 var i, len, flag, className,
6347 changes = {},
6348 add = [],
6349 remove = [],
6350 classPrefix = 'oo-ui-flaggedElement-';
6351
6352 if ( typeof flags === 'string' ) {
6353 className = classPrefix + flags;
6354 // Set
6355 if ( !this.flags[ flags ] ) {
6356 this.flags[ flags ] = true;
6357 add.push( className );
6358 }
6359 } else if ( Array.isArray( flags ) ) {
6360 for ( i = 0, len = flags.length; i < len; i++ ) {
6361 flag = flags[ i ];
6362 className = classPrefix + flag;
6363 // Set
6364 if ( !this.flags[ flag ] ) {
6365 changes[ flag ] = true;
6366 this.flags[ flag ] = true;
6367 add.push( className );
6368 }
6369 }
6370 } else if ( OO.isPlainObject( flags ) ) {
6371 for ( flag in flags ) {
6372 className = classPrefix + flag;
6373 if ( flags[ flag ] ) {
6374 // Set
6375 if ( !this.flags[ flag ] ) {
6376 changes[ flag ] = true;
6377 this.flags[ flag ] = true;
6378 add.push( className );
6379 }
6380 } else {
6381 // Remove
6382 if ( this.flags[ flag ] ) {
6383 changes[ flag ] = false;
6384 delete this.flags[ flag ];
6385 remove.push( className );
6386 }
6387 }
6388 }
6389 }
6390
6391 if ( this.$flagged ) {
6392 this.$flagged
6393 .addClass( add.join( ' ' ) )
6394 .removeClass( remove.join( ' ' ) );
6395 }
6396
6397 this.updateThemeClasses();
6398 this.emit( 'flag', changes );
6399
6400 return this;
6401 };
6402
6403 /**
6404 * TitledElement is mixed into other classes to provide a `title` attribute.
6405 * Titles are rendered by the browser and are made visible when the user moves
6406 * the mouse over the element. Titles are not visible on touch devices.
6407 *
6408 * @example
6409 * // TitledElement provides a 'title' attribute to the
6410 * // ButtonWidget class
6411 * var button = new OO.ui.ButtonWidget( {
6412 * label: 'Button with Title',
6413 * title: 'I am a button'
6414 * } );
6415 * $( 'body' ).append( button.$element );
6416 *
6417 * @abstract
6418 * @class
6419 *
6420 * @constructor
6421 * @param {Object} [config] Configuration options
6422 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6423 * If this config is omitted, the title functionality is applied to $element, the
6424 * element created by the class.
6425 * @cfg {string|Function} [title] The title text or a function that returns text. If
6426 * this config is omitted, the value of the {@link #static-title static title} property is used.
6427 */
6428 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6429 // Configuration initialization
6430 config = config || {};
6431
6432 // Properties
6433 this.$titled = null;
6434 this.title = null;
6435
6436 // Initialization
6437 this.setTitle( config.title || this.constructor.static.title );
6438 this.setTitledElement( config.$titled || this.$element );
6439 };
6440
6441 /* Setup */
6442
6443 OO.initClass( OO.ui.mixin.TitledElement );
6444
6445 /* Static Properties */
6446
6447 /**
6448 * The title text, a function that returns text, or `null` for no title. The value of the static property
6449 * is overridden if the #title config option is used.
6450 *
6451 * @static
6452 * @inheritable
6453 * @property {string|Function|null}
6454 */
6455 OO.ui.mixin.TitledElement.static.title = null;
6456
6457 /* Methods */
6458
6459 /**
6460 * Set the titled element.
6461 *
6462 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6463 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6464 *
6465 * @param {jQuery} $titled Element that should use the 'titled' functionality
6466 */
6467 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6468 if ( this.$titled ) {
6469 this.$titled.removeAttr( 'title' );
6470 }
6471
6472 this.$titled = $titled;
6473 if ( this.title ) {
6474 this.$titled.attr( 'title', this.title );
6475 }
6476 };
6477
6478 /**
6479 * Set title.
6480 *
6481 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6482 * @chainable
6483 */
6484 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6485 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6486
6487 if ( this.title !== title ) {
6488 if ( this.$titled ) {
6489 if ( title !== null ) {
6490 this.$titled.attr( 'title', title );
6491 } else {
6492 this.$titled.removeAttr( 'title' );
6493 }
6494 }
6495 this.title = title;
6496 }
6497
6498 return this;
6499 };
6500
6501 /**
6502 * Get title.
6503 *
6504 * @return {string} Title string
6505 */
6506 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6507 return this.title;
6508 };
6509
6510 /**
6511 * Element that can be automatically clipped to visible boundaries.
6512 *
6513 * Whenever the element's natural height changes, you have to call
6514 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6515 * clipping correctly.
6516 *
6517 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6518 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6519 * then #$clippable will be given a fixed reduced height and/or width and will be made
6520 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6521 * but you can build a static footer by setting #$clippableContainer to an element that contains
6522 * #$clippable and the footer.
6523 *
6524 * @abstract
6525 * @class
6526 *
6527 * @constructor
6528 * @param {Object} [config] Configuration options
6529 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6530 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6531 * omit to use #$clippable
6532 */
6533 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6534 // Configuration initialization
6535 config = config || {};
6536
6537 // Properties
6538 this.$clippable = null;
6539 this.$clippableContainer = null;
6540 this.clipping = false;
6541 this.clippedHorizontally = false;
6542 this.clippedVertically = false;
6543 this.$clippableScrollableContainer = null;
6544 this.$clippableScroller = null;
6545 this.$clippableWindow = null;
6546 this.idealWidth = null;
6547 this.idealHeight = null;
6548 this.onClippableScrollHandler = this.clip.bind( this );
6549 this.onClippableWindowResizeHandler = this.clip.bind( this );
6550
6551 // Initialization
6552 if ( config.$clippableContainer ) {
6553 this.setClippableContainer( config.$clippableContainer );
6554 }
6555 this.setClippableElement( config.$clippable || this.$element );
6556 };
6557
6558 /* Methods */
6559
6560 /**
6561 * Set clippable element.
6562 *
6563 * If an element is already set, it will be cleaned up before setting up the new element.
6564 *
6565 * @param {jQuery} $clippable Element to make clippable
6566 */
6567 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6568 if ( this.$clippable ) {
6569 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6570 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6571 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6572 }
6573
6574 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6575 this.clip();
6576 };
6577
6578 /**
6579 * Set clippable container.
6580 *
6581 * This is the container that will be measured when deciding whether to clip. When clipping,
6582 * #$clippable will be resized in order to keep the clippable container fully visible.
6583 *
6584 * If the clippable container is unset, #$clippable will be used.
6585 *
6586 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6587 */
6588 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6589 this.$clippableContainer = $clippableContainer;
6590 if ( this.$clippable ) {
6591 this.clip();
6592 }
6593 };
6594
6595 /**
6596 * Toggle clipping.
6597 *
6598 * Do not turn clipping on until after the element is attached to the DOM and visible.
6599 *
6600 * @param {boolean} [clipping] Enable clipping, omit to toggle
6601 * @chainable
6602 */
6603 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6604 clipping = clipping === undefined ? !this.clipping : !!clipping;
6605
6606 if ( this.clipping !== clipping ) {
6607 this.clipping = clipping;
6608 if ( clipping ) {
6609 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6610 // If the clippable container is the root, we have to listen to scroll events and check
6611 // jQuery.scrollTop on the window because of browser inconsistencies
6612 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6613 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6614 this.$clippableScrollableContainer;
6615 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6616 this.$clippableWindow = $( this.getElementWindow() )
6617 .on( 'resize', this.onClippableWindowResizeHandler );
6618 // Initial clip after visible
6619 this.clip();
6620 } else {
6621 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6622 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6623
6624 this.$clippableScrollableContainer = null;
6625 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6626 this.$clippableScroller = null;
6627 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6628 this.$clippableWindow = null;
6629 }
6630 }
6631
6632 return this;
6633 };
6634
6635 /**
6636 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6637 *
6638 * @return {boolean} Element will be clipped to the visible area
6639 */
6640 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6641 return this.clipping;
6642 };
6643
6644 /**
6645 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6646 *
6647 * @return {boolean} Part of the element is being clipped
6648 */
6649 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6650 return this.clippedHorizontally || this.clippedVertically;
6651 };
6652
6653 /**
6654 * Check if the right of the element is being clipped by the nearest scrollable container.
6655 *
6656 * @return {boolean} Part of the element is being clipped
6657 */
6658 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6659 return this.clippedHorizontally;
6660 };
6661
6662 /**
6663 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6664 *
6665 * @return {boolean} Part of the element is being clipped
6666 */
6667 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6668 return this.clippedVertically;
6669 };
6670
6671 /**
6672 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6673 *
6674 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6675 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6676 */
6677 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6678 this.idealWidth = width;
6679 this.idealHeight = height;
6680
6681 if ( !this.clipping ) {
6682 // Update dimensions
6683 this.$clippable.css( { width: width, height: height } );
6684 }
6685 // While clipping, idealWidth and idealHeight are not considered
6686 };
6687
6688 /**
6689 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6690 * the element's natural height changes.
6691 *
6692 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6693 * overlapped by, the visible area of the nearest scrollable container.
6694 *
6695 * @chainable
6696 */
6697 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6698 var $container, extraHeight, extraWidth, ccOffset,
6699 $scrollableContainer, scOffset, scHeight, scWidth,
6700 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6701 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6702 naturalWidth, naturalHeight, clipWidth, clipHeight,
6703 buffer = 7; // Chosen by fair dice roll
6704
6705 if ( !this.clipping ) {
6706 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6707 return this;
6708 }
6709
6710 $container = this.$clippableContainer || this.$clippable;
6711 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6712 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6713 ccOffset = $container.offset();
6714 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6715 this.$clippableWindow : this.$clippableScrollableContainer;
6716 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6717 scHeight = $scrollableContainer.innerHeight() - buffer;
6718 scWidth = $scrollableContainer.innerWidth() - buffer;
6719 ccWidth = $container.outerWidth() + buffer;
6720 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6721 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6722 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6723 desiredWidth = ccOffset.left < 0 ?
6724 ccWidth + ccOffset.left :
6725 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6726 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6727 allotedWidth = desiredWidth - extraWidth;
6728 allotedHeight = desiredHeight - extraHeight;
6729 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6730 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6731 clipWidth = allotedWidth < naturalWidth;
6732 clipHeight = allotedHeight < naturalHeight;
6733
6734 if ( clipWidth ) {
6735 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6736 } else {
6737 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6738 }
6739 if ( clipHeight ) {
6740 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6741 } else {
6742 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6743 }
6744
6745 // If we stopped clipping in at least one of the dimensions
6746 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6747 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6748 }
6749
6750 this.clippedHorizontally = clipWidth;
6751 this.clippedVertically = clipHeight;
6752
6753 return this;
6754 };
6755
6756 /**
6757 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6758 * Accesskeys allow an user to go to a specific element by using
6759 * a shortcut combination of a browser specific keys + the key
6760 * set to the field.
6761 *
6762 * @example
6763 * // AccessKeyedElement provides an 'accesskey' attribute to the
6764 * // ButtonWidget class
6765 * var button = new OO.ui.ButtonWidget( {
6766 * label: 'Button with Accesskey',
6767 * accessKey: 'k'
6768 * } );
6769 * $( 'body' ).append( button.$element );
6770 *
6771 * @abstract
6772 * @class
6773 *
6774 * @constructor
6775 * @param {Object} [config] Configuration options
6776 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
6777 * If this config is omitted, the accesskey functionality is applied to $element, the
6778 * element created by the class.
6779 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
6780 * this config is omitted, no accesskey will be added.
6781 */
6782 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
6783 // Configuration initialization
6784 config = config || {};
6785
6786 // Properties
6787 this.$accessKeyed = null;
6788 this.accessKey = null;
6789
6790 // Initialization
6791 this.setAccessKey( config.accessKey || null );
6792 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
6793 };
6794
6795 /* Setup */
6796
6797 OO.initClass( OO.ui.mixin.AccessKeyedElement );
6798
6799 /* Static Properties */
6800
6801 /**
6802 * The access key, a function that returns a key, or `null` for no accesskey.
6803 *
6804 * @static
6805 * @inheritable
6806 * @property {string|Function|null}
6807 */
6808 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
6809
6810 /* Methods */
6811
6812 /**
6813 * Set the accesskeyed element.
6814 *
6815 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
6816 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
6817 *
6818 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
6819 */
6820 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
6821 if ( this.$accessKeyed ) {
6822 this.$accessKeyed.removeAttr( 'accesskey' );
6823 }
6824
6825 this.$accessKeyed = $accessKeyed;
6826 if ( this.accessKey ) {
6827 this.$accessKeyed.attr( 'accesskey', this.accessKey );
6828 }
6829 };
6830
6831 /**
6832 * Set accesskey.
6833 *
6834 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
6835 * @chainable
6836 */
6837 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
6838 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
6839
6840 if ( this.accessKey !== accessKey ) {
6841 if ( this.$accessKeyed ) {
6842 if ( accessKey !== null ) {
6843 this.$accessKeyed.attr( 'accesskey', accessKey );
6844 } else {
6845 this.$accessKeyed.removeAttr( 'accesskey' );
6846 }
6847 }
6848 this.accessKey = accessKey;
6849 }
6850
6851 return this;
6852 };
6853
6854 /**
6855 * Get accesskey.
6856 *
6857 * @return {string} accessKey string
6858 */
6859 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
6860 return this.accessKey;
6861 };
6862
6863 /**
6864 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6865 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6866 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6867 * which creates the tools on demand.
6868 *
6869 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6870 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6871 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6872 *
6873 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6874 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6875 *
6876 * @abstract
6877 * @class
6878 * @extends OO.ui.Widget
6879 * @mixins OO.ui.mixin.IconElement
6880 * @mixins OO.ui.mixin.FlaggedElement
6881 * @mixins OO.ui.mixin.TabIndexedElement
6882 *
6883 * @constructor
6884 * @param {OO.ui.ToolGroup} toolGroup
6885 * @param {Object} [config] Configuration options
6886 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6887 * the {@link #static-title static title} property is used.
6888 *
6889 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6890 * 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
6891 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6892 *
6893 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6894 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6895 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6896 */
6897 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6898 // Allow passing positional parameters inside the config object
6899 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6900 config = toolGroup;
6901 toolGroup = config.toolGroup;
6902 }
6903
6904 // Configuration initialization
6905 config = config || {};
6906
6907 // Parent constructor
6908 OO.ui.Tool.parent.call( this, config );
6909
6910 // Properties
6911 this.toolGroup = toolGroup;
6912 this.toolbar = this.toolGroup.getToolbar();
6913 this.active = false;
6914 this.$title = $( '<span>' );
6915 this.$accel = $( '<span>' );
6916 this.$link = $( '<a>' );
6917 this.title = null;
6918
6919 // Mixin constructors
6920 OO.ui.mixin.IconElement.call( this, config );
6921 OO.ui.mixin.FlaggedElement.call( this, config );
6922 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
6923
6924 // Events
6925 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6926
6927 // Initialization
6928 this.$title.addClass( 'oo-ui-tool-title' );
6929 this.$accel
6930 .addClass( 'oo-ui-tool-accel' )
6931 .prop( {
6932 // This may need to be changed if the key names are ever localized,
6933 // but for now they are essentially written in English
6934 dir: 'ltr',
6935 lang: 'en'
6936 } );
6937 this.$link
6938 .addClass( 'oo-ui-tool-link' )
6939 .append( this.$icon, this.$title, this.$accel )
6940 .attr( 'role', 'button' );
6941 this.$element
6942 .data( 'oo-ui-tool', this )
6943 .addClass(
6944 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6945 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6946 )
6947 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
6948 .append( this.$link );
6949 this.setTitle( config.title || this.constructor.static.title );
6950 };
6951
6952 /* Setup */
6953
6954 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6955 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
6956 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
6957 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
6958
6959 /* Static Properties */
6960
6961 /**
6962 * @static
6963 * @inheritdoc
6964 */
6965 OO.ui.Tool.static.tagName = 'span';
6966
6967 /**
6968 * Symbolic name of tool.
6969 *
6970 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6971 * also be used when adding tools to toolgroups.
6972 *
6973 * @abstract
6974 * @static
6975 * @inheritable
6976 * @property {string}
6977 */
6978 OO.ui.Tool.static.name = '';
6979
6980 /**
6981 * Symbolic name of the group.
6982 *
6983 * The group name is used to associate tools with each other so that they can be selected later by
6984 * a {@link OO.ui.ToolGroup toolgroup}.
6985 *
6986 * @abstract
6987 * @static
6988 * @inheritable
6989 * @property {string}
6990 */
6991 OO.ui.Tool.static.group = '';
6992
6993 /**
6994 * 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.
6995 *
6996 * @abstract
6997 * @static
6998 * @inheritable
6999 * @property {string|Function}
7000 */
7001 OO.ui.Tool.static.title = '';
7002
7003 /**
7004 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7005 * Normally only the icon is displayed, or only the label if no icon is given.
7006 *
7007 * @static
7008 * @inheritable
7009 * @property {boolean}
7010 */
7011 OO.ui.Tool.static.displayBothIconAndLabel = false;
7012
7013 /**
7014 * Add tool to catch-all groups automatically.
7015 *
7016 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7017 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7018 *
7019 * @static
7020 * @inheritable
7021 * @property {boolean}
7022 */
7023 OO.ui.Tool.static.autoAddToCatchall = true;
7024
7025 /**
7026 * Add tool to named groups automatically.
7027 *
7028 * By default, tools that are configured with a static ‘group’ property are added
7029 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7030 * toolgroups include tools by group name).
7031 *
7032 * @static
7033 * @property {boolean}
7034 * @inheritable
7035 */
7036 OO.ui.Tool.static.autoAddToGroup = true;
7037
7038 /**
7039 * Check if this tool is compatible with given data.
7040 *
7041 * This is a stub that can be overriden to provide support for filtering tools based on an
7042 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7043 * must also call this method so that the compatibility check can be performed.
7044 *
7045 * @static
7046 * @inheritable
7047 * @param {Mixed} data Data to check
7048 * @return {boolean} Tool can be used with data
7049 */
7050 OO.ui.Tool.static.isCompatibleWith = function () {
7051 return false;
7052 };
7053
7054 /* Methods */
7055
7056 /**
7057 * Handle the toolbar state being updated.
7058 *
7059 * This is an abstract method that must be overridden in a concrete subclass.
7060 *
7061 * @protected
7062 * @abstract
7063 */
7064 OO.ui.Tool.prototype.onUpdateState = function () {
7065 throw new Error(
7066 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7067 );
7068 };
7069
7070 /**
7071 * Handle the tool being selected.
7072 *
7073 * This is an abstract method that must be overridden in a concrete subclass.
7074 *
7075 * @protected
7076 * @abstract
7077 */
7078 OO.ui.Tool.prototype.onSelect = function () {
7079 throw new Error(
7080 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7081 );
7082 };
7083
7084 /**
7085 * Check if the tool is active.
7086 *
7087 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7088 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7089 *
7090 * @return {boolean} Tool is active
7091 */
7092 OO.ui.Tool.prototype.isActive = function () {
7093 return this.active;
7094 };
7095
7096 /**
7097 * Make the tool appear active or inactive.
7098 *
7099 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7100 * appear pressed or not.
7101 *
7102 * @param {boolean} state Make tool appear active
7103 */
7104 OO.ui.Tool.prototype.setActive = function ( state ) {
7105 this.active = !!state;
7106 if ( this.active ) {
7107 this.$element.addClass( 'oo-ui-tool-active' );
7108 } else {
7109 this.$element.removeClass( 'oo-ui-tool-active' );
7110 }
7111 };
7112
7113 /**
7114 * Set the tool #title.
7115 *
7116 * @param {string|Function} title Title text or a function that returns text
7117 * @chainable
7118 */
7119 OO.ui.Tool.prototype.setTitle = function ( title ) {
7120 this.title = OO.ui.resolveMsg( title );
7121 this.updateTitle();
7122 return this;
7123 };
7124
7125 /**
7126 * Get the tool #title.
7127 *
7128 * @return {string} Title text
7129 */
7130 OO.ui.Tool.prototype.getTitle = function () {
7131 return this.title;
7132 };
7133
7134 /**
7135 * Get the tool's symbolic name.
7136 *
7137 * @return {string} Symbolic name of tool
7138 */
7139 OO.ui.Tool.prototype.getName = function () {
7140 return this.constructor.static.name;
7141 };
7142
7143 /**
7144 * Update the title.
7145 */
7146 OO.ui.Tool.prototype.updateTitle = function () {
7147 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7148 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7149 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7150 tooltipParts = [];
7151
7152 this.$title.text( this.title );
7153 this.$accel.text( accel );
7154
7155 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7156 tooltipParts.push( this.title );
7157 }
7158 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7159 tooltipParts.push( accel );
7160 }
7161 if ( tooltipParts.length ) {
7162 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7163 } else {
7164 this.$link.removeAttr( 'title' );
7165 }
7166 };
7167
7168 /**
7169 * Destroy tool.
7170 *
7171 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7172 * Call this method whenever you are done using a tool.
7173 */
7174 OO.ui.Tool.prototype.destroy = function () {
7175 this.toolbar.disconnect( this );
7176 this.$element.remove();
7177 };
7178
7179 /**
7180 * Toolbars are complex interface components that permit users to easily access a variety
7181 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7182 * part of the toolbar, but not configured as tools.
7183 *
7184 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7185 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7186 * picture’), and an icon.
7187 *
7188 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7189 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7190 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7191 * any order, but each can only appear once in the toolbar.
7192 *
7193 * The following is an example of a basic toolbar.
7194 *
7195 * @example
7196 * // Example of a toolbar
7197 * // Create the toolbar
7198 * var toolFactory = new OO.ui.ToolFactory();
7199 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7200 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7201 *
7202 * // We will be placing status text in this element when tools are used
7203 * var $area = $( '<p>' ).text( 'Toolbar example' );
7204 *
7205 * // Define the tools that we're going to place in our toolbar
7206 *
7207 * // Create a class inheriting from OO.ui.Tool
7208 * function PictureTool() {
7209 * PictureTool.parent.apply( this, arguments );
7210 * }
7211 * OO.inheritClass( PictureTool, OO.ui.Tool );
7212 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7213 * // of 'icon' and 'title' (displayed icon and text).
7214 * PictureTool.static.name = 'picture';
7215 * PictureTool.static.icon = 'picture';
7216 * PictureTool.static.title = 'Insert picture';
7217 * // Defines the action that will happen when this tool is selected (clicked).
7218 * PictureTool.prototype.onSelect = function () {
7219 * $area.text( 'Picture tool clicked!' );
7220 * // Never display this tool as "active" (selected).
7221 * this.setActive( false );
7222 * };
7223 * // Make this tool available in our toolFactory and thus our toolbar
7224 * toolFactory.register( PictureTool );
7225 *
7226 * // Register two more tools, nothing interesting here
7227 * function SettingsTool() {
7228 * SettingsTool.parent.apply( this, arguments );
7229 * }
7230 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7231 * SettingsTool.static.name = 'settings';
7232 * SettingsTool.static.icon = 'settings';
7233 * SettingsTool.static.title = 'Change settings';
7234 * SettingsTool.prototype.onSelect = function () {
7235 * $area.text( 'Settings tool clicked!' );
7236 * this.setActive( false );
7237 * };
7238 * toolFactory.register( SettingsTool );
7239 *
7240 * // Register two more tools, nothing interesting here
7241 * function StuffTool() {
7242 * StuffTool.parent.apply( this, arguments );
7243 * }
7244 * OO.inheritClass( StuffTool, OO.ui.Tool );
7245 * StuffTool.static.name = 'stuff';
7246 * StuffTool.static.icon = 'ellipsis';
7247 * StuffTool.static.title = 'More stuff';
7248 * StuffTool.prototype.onSelect = function () {
7249 * $area.text( 'More stuff tool clicked!' );
7250 * this.setActive( false );
7251 * };
7252 * toolFactory.register( StuffTool );
7253 *
7254 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7255 * // little popup window (a PopupWidget).
7256 * function HelpTool( toolGroup, config ) {
7257 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7258 * padded: true,
7259 * label: 'Help',
7260 * head: true
7261 * } }, config ) );
7262 * this.popup.$body.append( '<p>I am helpful!</p>' );
7263 * }
7264 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7265 * HelpTool.static.name = 'help';
7266 * HelpTool.static.icon = 'help';
7267 * HelpTool.static.title = 'Help';
7268 * toolFactory.register( HelpTool );
7269 *
7270 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7271 * // used once (but not all defined tools must be used).
7272 * toolbar.setup( [
7273 * {
7274 * // 'bar' tool groups display tools' icons only, side-by-side.
7275 * type: 'bar',
7276 * include: [ 'picture', 'help' ]
7277 * },
7278 * {
7279 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7280 * type: 'list',
7281 * indicator: 'down',
7282 * label: 'More',
7283 * include: [ 'settings', 'stuff' ]
7284 * }
7285 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7286 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7287 * // since it's more complicated to use. (See the next example snippet on this page.)
7288 * ] );
7289 *
7290 * // Create some UI around the toolbar and place it in the document
7291 * var frame = new OO.ui.PanelLayout( {
7292 * expanded: false,
7293 * framed: true
7294 * } );
7295 * var contentFrame = new OO.ui.PanelLayout( {
7296 * expanded: false,
7297 * padded: true
7298 * } );
7299 * frame.$element.append(
7300 * toolbar.$element,
7301 * contentFrame.$element.append( $area )
7302 * );
7303 * $( 'body' ).append( frame.$element );
7304 *
7305 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7306 * // document.
7307 * toolbar.initialize();
7308 *
7309 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7310 * 'updateState' event.
7311 *
7312 * @example
7313 * // Create the toolbar
7314 * var toolFactory = new OO.ui.ToolFactory();
7315 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7316 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7317 *
7318 * // We will be placing status text in this element when tools are used
7319 * var $area = $( '<p>' ).text( 'Toolbar example' );
7320 *
7321 * // Define the tools that we're going to place in our toolbar
7322 *
7323 * // Create a class inheriting from OO.ui.Tool
7324 * function PictureTool() {
7325 * PictureTool.parent.apply( this, arguments );
7326 * }
7327 * OO.inheritClass( PictureTool, OO.ui.Tool );
7328 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7329 * // of 'icon' and 'title' (displayed icon and text).
7330 * PictureTool.static.name = 'picture';
7331 * PictureTool.static.icon = 'picture';
7332 * PictureTool.static.title = 'Insert picture';
7333 * // Defines the action that will happen when this tool is selected (clicked).
7334 * PictureTool.prototype.onSelect = function () {
7335 * $area.text( 'Picture tool clicked!' );
7336 * // Never display this tool as "active" (selected).
7337 * this.setActive( false );
7338 * };
7339 * // The toolbar can be synchronized with the state of some external stuff, like a text
7340 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7341 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7342 * PictureTool.prototype.onUpdateState = function () {
7343 * };
7344 * // Make this tool available in our toolFactory and thus our toolbar
7345 * toolFactory.register( PictureTool );
7346 *
7347 * // Register two more tools, nothing interesting here
7348 * function SettingsTool() {
7349 * SettingsTool.parent.apply( this, arguments );
7350 * this.reallyActive = false;
7351 * }
7352 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7353 * SettingsTool.static.name = 'settings';
7354 * SettingsTool.static.icon = 'settings';
7355 * SettingsTool.static.title = 'Change settings';
7356 * SettingsTool.prototype.onSelect = function () {
7357 * $area.text( 'Settings tool clicked!' );
7358 * // Toggle the active state on each click
7359 * this.reallyActive = !this.reallyActive;
7360 * this.setActive( this.reallyActive );
7361 * // To update the menu label
7362 * this.toolbar.emit( 'updateState' );
7363 * };
7364 * SettingsTool.prototype.onUpdateState = function () {
7365 * };
7366 * toolFactory.register( SettingsTool );
7367 *
7368 * // Register two more tools, nothing interesting here
7369 * function StuffTool() {
7370 * StuffTool.parent.apply( this, arguments );
7371 * this.reallyActive = false;
7372 * }
7373 * OO.inheritClass( StuffTool, OO.ui.Tool );
7374 * StuffTool.static.name = 'stuff';
7375 * StuffTool.static.icon = 'ellipsis';
7376 * StuffTool.static.title = 'More stuff';
7377 * StuffTool.prototype.onSelect = function () {
7378 * $area.text( 'More stuff tool clicked!' );
7379 * // Toggle the active state on each click
7380 * this.reallyActive = !this.reallyActive;
7381 * this.setActive( this.reallyActive );
7382 * // To update the menu label
7383 * this.toolbar.emit( 'updateState' );
7384 * };
7385 * StuffTool.prototype.onUpdateState = function () {
7386 * };
7387 * toolFactory.register( StuffTool );
7388 *
7389 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7390 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7391 * function HelpTool( toolGroup, config ) {
7392 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7393 * padded: true,
7394 * label: 'Help',
7395 * head: true
7396 * } }, config ) );
7397 * this.popup.$body.append( '<p>I am helpful!</p>' );
7398 * }
7399 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7400 * HelpTool.static.name = 'help';
7401 * HelpTool.static.icon = 'help';
7402 * HelpTool.static.title = 'Help';
7403 * toolFactory.register( HelpTool );
7404 *
7405 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7406 * // used once (but not all defined tools must be used).
7407 * toolbar.setup( [
7408 * {
7409 * // 'bar' tool groups display tools' icons only, side-by-side.
7410 * type: 'bar',
7411 * include: [ 'picture', 'help' ]
7412 * },
7413 * {
7414 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7415 * // Menu label indicates which items are selected.
7416 * type: 'menu',
7417 * indicator: 'down',
7418 * include: [ 'settings', 'stuff' ]
7419 * }
7420 * ] );
7421 *
7422 * // Create some UI around the toolbar and place it in the document
7423 * var frame = new OO.ui.PanelLayout( {
7424 * expanded: false,
7425 * framed: true
7426 * } );
7427 * var contentFrame = new OO.ui.PanelLayout( {
7428 * expanded: false,
7429 * padded: true
7430 * } );
7431 * frame.$element.append(
7432 * toolbar.$element,
7433 * contentFrame.$element.append( $area )
7434 * );
7435 * $( 'body' ).append( frame.$element );
7436 *
7437 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7438 * // document.
7439 * toolbar.initialize();
7440 * toolbar.emit( 'updateState' );
7441 *
7442 * @class
7443 * @extends OO.ui.Element
7444 * @mixins OO.EventEmitter
7445 * @mixins OO.ui.mixin.GroupElement
7446 *
7447 * @constructor
7448 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7449 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7450 * @param {Object} [config] Configuration options
7451 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7452 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7453 * the toolbar.
7454 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7455 */
7456 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7457 // Allow passing positional parameters inside the config object
7458 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7459 config = toolFactory;
7460 toolFactory = config.toolFactory;
7461 toolGroupFactory = config.toolGroupFactory;
7462 }
7463
7464 // Configuration initialization
7465 config = config || {};
7466
7467 // Parent constructor
7468 OO.ui.Toolbar.parent.call( this, config );
7469
7470 // Mixin constructors
7471 OO.EventEmitter.call( this );
7472 OO.ui.mixin.GroupElement.call( this, config );
7473
7474 // Properties
7475 this.toolFactory = toolFactory;
7476 this.toolGroupFactory = toolGroupFactory;
7477 this.groups = [];
7478 this.tools = {};
7479 this.$bar = $( '<div>' );
7480 this.$actions = $( '<div>' );
7481 this.initialized = false;
7482 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7483
7484 // Events
7485 this.$element
7486 .add( this.$bar ).add( this.$group ).add( this.$actions )
7487 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7488
7489 // Initialization
7490 this.$group.addClass( 'oo-ui-toolbar-tools' );
7491 if ( config.actions ) {
7492 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7493 }
7494 this.$bar
7495 .addClass( 'oo-ui-toolbar-bar' )
7496 .append( this.$group, '<div style="clear:both"></div>' );
7497 if ( config.shadow ) {
7498 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7499 }
7500 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7501 };
7502
7503 /* Setup */
7504
7505 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7506 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7507 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7508
7509 /* Methods */
7510
7511 /**
7512 * Get the tool factory.
7513 *
7514 * @return {OO.ui.ToolFactory} Tool factory
7515 */
7516 OO.ui.Toolbar.prototype.getToolFactory = function () {
7517 return this.toolFactory;
7518 };
7519
7520 /**
7521 * Get the toolgroup factory.
7522 *
7523 * @return {OO.Factory} Toolgroup factory
7524 */
7525 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7526 return this.toolGroupFactory;
7527 };
7528
7529 /**
7530 * Handles mouse down events.
7531 *
7532 * @private
7533 * @param {jQuery.Event} e Mouse down event
7534 */
7535 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7536 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7537 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7538 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7539 return false;
7540 }
7541 };
7542
7543 /**
7544 * Handle window resize event.
7545 *
7546 * @private
7547 * @param {jQuery.Event} e Window resize event
7548 */
7549 OO.ui.Toolbar.prototype.onWindowResize = function () {
7550 this.$element.toggleClass(
7551 'oo-ui-toolbar-narrow',
7552 this.$bar.width() <= this.narrowThreshold
7553 );
7554 };
7555
7556 /**
7557 * Sets up handles and preloads required information for the toolbar to work.
7558 * This must be called after it is attached to a visible document and before doing anything else.
7559 */
7560 OO.ui.Toolbar.prototype.initialize = function () {
7561 this.initialized = true;
7562 this.narrowThreshold = this.$group.width() + this.$actions.width();
7563 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7564 this.onWindowResize();
7565 };
7566
7567 /**
7568 * Set up the toolbar.
7569 *
7570 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7571 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7572 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7573 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7574 *
7575 * @param {Object.<string,Array>} groups List of toolgroup configurations
7576 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7577 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7578 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7579 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7580 */
7581 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7582 var i, len, type, group,
7583 items = [],
7584 defaultType = 'bar';
7585
7586 // Cleanup previous groups
7587 this.reset();
7588
7589 // Build out new groups
7590 for ( i = 0, len = groups.length; i < len; i++ ) {
7591 group = groups[ i ];
7592 if ( group.include === '*' ) {
7593 // Apply defaults to catch-all groups
7594 if ( group.type === undefined ) {
7595 group.type = 'list';
7596 }
7597 if ( group.label === undefined ) {
7598 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7599 }
7600 }
7601 // Check type has been registered
7602 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7603 items.push(
7604 this.getToolGroupFactory().create( type, this, group )
7605 );
7606 }
7607 this.addItems( items );
7608 };
7609
7610 /**
7611 * Remove all tools and toolgroups from the toolbar.
7612 */
7613 OO.ui.Toolbar.prototype.reset = function () {
7614 var i, len;
7615
7616 this.groups = [];
7617 this.tools = {};
7618 for ( i = 0, len = this.items.length; i < len; i++ ) {
7619 this.items[ i ].destroy();
7620 }
7621 this.clearItems();
7622 };
7623
7624 /**
7625 * Destroy the toolbar.
7626 *
7627 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7628 * this method whenever you are done using a toolbar.
7629 */
7630 OO.ui.Toolbar.prototype.destroy = function () {
7631 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7632 this.reset();
7633 this.$element.remove();
7634 };
7635
7636 /**
7637 * Check if the tool is available.
7638 *
7639 * Available tools are ones that have not yet been added to the toolbar.
7640 *
7641 * @param {string} name Symbolic name of tool
7642 * @return {boolean} Tool is available
7643 */
7644 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7645 return !this.tools[ name ];
7646 };
7647
7648 /**
7649 * Prevent tool from being used again.
7650 *
7651 * @param {OO.ui.Tool} tool Tool to reserve
7652 */
7653 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7654 this.tools[ tool.getName() ] = tool;
7655 };
7656
7657 /**
7658 * Allow tool to be used again.
7659 *
7660 * @param {OO.ui.Tool} tool Tool to release
7661 */
7662 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7663 delete this.tools[ tool.getName() ];
7664 };
7665
7666 /**
7667 * Get accelerator label for tool.
7668 *
7669 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7670 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7671 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7672 *
7673 * @param {string} name Symbolic name of tool
7674 * @return {string|undefined} Tool accelerator label if available
7675 */
7676 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7677 return undefined;
7678 };
7679
7680 /**
7681 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7682 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7683 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7684 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7685 *
7686 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7687 *
7688 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7689 *
7690 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7691 *
7692 * 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.)
7693 *
7694 * include: [ { group: 'group-name' } ]
7695 *
7696 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7697 *
7698 * include: '*'
7699 *
7700 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7701 * please see the [OOjs UI documentation on MediaWiki][1].
7702 *
7703 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7704 *
7705 * @abstract
7706 * @class
7707 * @extends OO.ui.Widget
7708 * @mixins OO.ui.mixin.GroupElement
7709 *
7710 * @constructor
7711 * @param {OO.ui.Toolbar} toolbar
7712 * @param {Object} [config] Configuration options
7713 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7714 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7715 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7716 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7717 * This setting is particularly useful when tools have been added to the toolgroup
7718 * en masse (e.g., via the catch-all selector).
7719 */
7720 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7721 // Allow passing positional parameters inside the config object
7722 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7723 config = toolbar;
7724 toolbar = config.toolbar;
7725 }
7726
7727 // Configuration initialization
7728 config = config || {};
7729
7730 // Parent constructor
7731 OO.ui.ToolGroup.parent.call( this, config );
7732
7733 // Mixin constructors
7734 OO.ui.mixin.GroupElement.call( this, config );
7735
7736 // Properties
7737 this.toolbar = toolbar;
7738 this.tools = {};
7739 this.pressed = null;
7740 this.autoDisabled = false;
7741 this.include = config.include || [];
7742 this.exclude = config.exclude || [];
7743 this.promote = config.promote || [];
7744 this.demote = config.demote || [];
7745 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7746
7747 // Events
7748 this.$element.on( {
7749 mousedown: this.onMouseKeyDown.bind( this ),
7750 mouseup: this.onMouseKeyUp.bind( this ),
7751 keydown: this.onMouseKeyDown.bind( this ),
7752 keyup: this.onMouseKeyUp.bind( this ),
7753 focus: this.onMouseOverFocus.bind( this ),
7754 blur: this.onMouseOutBlur.bind( this ),
7755 mouseover: this.onMouseOverFocus.bind( this ),
7756 mouseout: this.onMouseOutBlur.bind( this )
7757 } );
7758 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7759 this.aggregate( { disable: 'itemDisable' } );
7760 this.connect( this, { itemDisable: 'updateDisabled' } );
7761
7762 // Initialization
7763 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7764 this.$element
7765 .addClass( 'oo-ui-toolGroup' )
7766 .append( this.$group );
7767 this.populate();
7768 };
7769
7770 /* Setup */
7771
7772 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7773 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
7774
7775 /* Events */
7776
7777 /**
7778 * @event update
7779 */
7780
7781 /* Static Properties */
7782
7783 /**
7784 * Show labels in tooltips.
7785 *
7786 * @static
7787 * @inheritable
7788 * @property {boolean}
7789 */
7790 OO.ui.ToolGroup.static.titleTooltips = false;
7791
7792 /**
7793 * Show acceleration labels in tooltips.
7794 *
7795 * Note: The OOjs UI library does not include an accelerator system, but does contain
7796 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7797 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7798 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7799 *
7800 * @static
7801 * @inheritable
7802 * @property {boolean}
7803 */
7804 OO.ui.ToolGroup.static.accelTooltips = false;
7805
7806 /**
7807 * Automatically disable the toolgroup when all tools are disabled
7808 *
7809 * @static
7810 * @inheritable
7811 * @property {boolean}
7812 */
7813 OO.ui.ToolGroup.static.autoDisable = true;
7814
7815 /* Methods */
7816
7817 /**
7818 * @inheritdoc
7819 */
7820 OO.ui.ToolGroup.prototype.isDisabled = function () {
7821 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
7822 };
7823
7824 /**
7825 * @inheritdoc
7826 */
7827 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7828 var i, item, allDisabled = true;
7829
7830 if ( this.constructor.static.autoDisable ) {
7831 for ( i = this.items.length - 1; i >= 0; i-- ) {
7832 item = this.items[ i ];
7833 if ( !item.isDisabled() ) {
7834 allDisabled = false;
7835 break;
7836 }
7837 }
7838 this.autoDisabled = allDisabled;
7839 }
7840 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
7841 };
7842
7843 /**
7844 * Handle mouse down and key down events.
7845 *
7846 * @protected
7847 * @param {jQuery.Event} e Mouse down or key down event
7848 */
7849 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7850 if (
7851 !this.isDisabled() &&
7852 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7853 ) {
7854 this.pressed = this.getTargetTool( e );
7855 if ( this.pressed ) {
7856 this.pressed.setActive( true );
7857 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7858 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7859 }
7860 return false;
7861 }
7862 };
7863
7864 /**
7865 * Handle captured mouse up and key up events.
7866 *
7867 * @protected
7868 * @param {Event} e Mouse up or key up event
7869 */
7870 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7871 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7872 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7873 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7874 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7875 this.onMouseKeyUp( e );
7876 };
7877
7878 /**
7879 * Handle mouse up and key up events.
7880 *
7881 * @protected
7882 * @param {jQuery.Event} e Mouse up or key up event
7883 */
7884 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7885 var tool = this.getTargetTool( e );
7886
7887 if (
7888 !this.isDisabled() && this.pressed && this.pressed === tool &&
7889 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7890 ) {
7891 this.pressed.onSelect();
7892 this.pressed = null;
7893 return false;
7894 }
7895
7896 this.pressed = null;
7897 };
7898
7899 /**
7900 * Handle mouse over and focus events.
7901 *
7902 * @protected
7903 * @param {jQuery.Event} e Mouse over or focus event
7904 */
7905 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7906 var tool = this.getTargetTool( e );
7907
7908 if ( this.pressed && this.pressed === tool ) {
7909 this.pressed.setActive( true );
7910 }
7911 };
7912
7913 /**
7914 * Handle mouse out and blur events.
7915 *
7916 * @protected
7917 * @param {jQuery.Event} e Mouse out or blur event
7918 */
7919 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7920 var tool = this.getTargetTool( e );
7921
7922 if ( this.pressed && this.pressed === tool ) {
7923 this.pressed.setActive( false );
7924 }
7925 };
7926
7927 /**
7928 * Get the closest tool to a jQuery.Event.
7929 *
7930 * Only tool links are considered, which prevents other elements in the tool such as popups from
7931 * triggering tool group interactions.
7932 *
7933 * @private
7934 * @param {jQuery.Event} e
7935 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7936 */
7937 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7938 var tool,
7939 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7940
7941 if ( $item.length ) {
7942 tool = $item.parent().data( 'oo-ui-tool' );
7943 }
7944
7945 return tool && !tool.isDisabled() ? tool : null;
7946 };
7947
7948 /**
7949 * Handle tool registry register events.
7950 *
7951 * If a tool is registered after the group is created, we must repopulate the list to account for:
7952 *
7953 * - a tool being added that may be included
7954 * - a tool already included being overridden
7955 *
7956 * @protected
7957 * @param {string} name Symbolic name of tool
7958 */
7959 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7960 this.populate();
7961 };
7962
7963 /**
7964 * Get the toolbar that contains the toolgroup.
7965 *
7966 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7967 */
7968 OO.ui.ToolGroup.prototype.getToolbar = function () {
7969 return this.toolbar;
7970 };
7971
7972 /**
7973 * Add and remove tools based on configuration.
7974 */
7975 OO.ui.ToolGroup.prototype.populate = function () {
7976 var i, len, name, tool,
7977 toolFactory = this.toolbar.getToolFactory(),
7978 names = {},
7979 add = [],
7980 remove = [],
7981 list = this.toolbar.getToolFactory().getTools(
7982 this.include, this.exclude, this.promote, this.demote
7983 );
7984
7985 // Build a list of needed tools
7986 for ( i = 0, len = list.length; i < len; i++ ) {
7987 name = list[ i ];
7988 if (
7989 // Tool exists
7990 toolFactory.lookup( name ) &&
7991 // Tool is available or is already in this group
7992 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7993 ) {
7994 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7995 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7996 this.toolbar.tools[ name ] = true;
7997 tool = this.tools[ name ];
7998 if ( !tool ) {
7999 // Auto-initialize tools on first use
8000 this.tools[ name ] = tool = toolFactory.create( name, this );
8001 tool.updateTitle();
8002 }
8003 this.toolbar.reserveTool( tool );
8004 add.push( tool );
8005 names[ name ] = true;
8006 }
8007 }
8008 // Remove tools that are no longer needed
8009 for ( name in this.tools ) {
8010 if ( !names[ name ] ) {
8011 this.tools[ name ].destroy();
8012 this.toolbar.releaseTool( this.tools[ name ] );
8013 remove.push( this.tools[ name ] );
8014 delete this.tools[ name ];
8015 }
8016 }
8017 if ( remove.length ) {
8018 this.removeItems( remove );
8019 }
8020 // Update emptiness state
8021 if ( add.length ) {
8022 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8023 } else {
8024 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8025 }
8026 // Re-add tools (moving existing ones to new locations)
8027 this.addItems( add );
8028 // Disabled state may depend on items
8029 this.updateDisabled();
8030 };
8031
8032 /**
8033 * Destroy toolgroup.
8034 */
8035 OO.ui.ToolGroup.prototype.destroy = function () {
8036 var name;
8037
8038 this.clearItems();
8039 this.toolbar.getToolFactory().disconnect( this );
8040 for ( name in this.tools ) {
8041 this.toolbar.releaseTool( this.tools[ name ] );
8042 this.tools[ name ].disconnect( this ).destroy();
8043 delete this.tools[ name ];
8044 }
8045 this.$element.remove();
8046 };
8047
8048 /**
8049 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8050 * consists of a header that contains the dialog title, a body with the message, and a footer that
8051 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8052 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8053 *
8054 * There are two basic types of message dialogs, confirmation and alert:
8055 *
8056 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8057 * more details about the consequences.
8058 * - **alert**: the dialog title describes which event occurred and the message provides more information
8059 * about why the event occurred.
8060 *
8061 * The MessageDialog class specifies two actions: ‘accept’, the primary
8062 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8063 * passing along the selected action.
8064 *
8065 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8066 *
8067 * @example
8068 * // Example: Creating and opening a message dialog window.
8069 * var messageDialog = new OO.ui.MessageDialog();
8070 *
8071 * // Create and append a window manager.
8072 * var windowManager = new OO.ui.WindowManager();
8073 * $( 'body' ).append( windowManager.$element );
8074 * windowManager.addWindows( [ messageDialog ] );
8075 * // Open the window.
8076 * windowManager.openWindow( messageDialog, {
8077 * title: 'Basic message dialog',
8078 * message: 'This is the message'
8079 * } );
8080 *
8081 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8082 *
8083 * @class
8084 * @extends OO.ui.Dialog
8085 *
8086 * @constructor
8087 * @param {Object} [config] Configuration options
8088 */
8089 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8090 // Parent constructor
8091 OO.ui.MessageDialog.parent.call( this, config );
8092
8093 // Properties
8094 this.verticalActionLayout = null;
8095
8096 // Initialization
8097 this.$element.addClass( 'oo-ui-messageDialog' );
8098 };
8099
8100 /* Setup */
8101
8102 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8103
8104 /* Static Properties */
8105
8106 OO.ui.MessageDialog.static.name = 'message';
8107
8108 OO.ui.MessageDialog.static.size = 'small';
8109
8110 OO.ui.MessageDialog.static.verbose = false;
8111
8112 /**
8113 * Dialog title.
8114 *
8115 * The title of a confirmation dialog describes what a progressive action will do. The
8116 * title of an alert dialog describes which event occurred.
8117 *
8118 * @static
8119 * @inheritable
8120 * @property {jQuery|string|Function|null}
8121 */
8122 OO.ui.MessageDialog.static.title = null;
8123
8124 /**
8125 * The message displayed in the dialog body.
8126 *
8127 * A confirmation message describes the consequences of a progressive action. An alert
8128 * message describes why an event occurred.
8129 *
8130 * @static
8131 * @inheritable
8132 * @property {jQuery|string|Function|null}
8133 */
8134 OO.ui.MessageDialog.static.message = null;
8135
8136 OO.ui.MessageDialog.static.actions = [
8137 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8138 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8139 ];
8140
8141 /* Methods */
8142
8143 /**
8144 * @inheritdoc
8145 */
8146 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8147 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8148
8149 // Events
8150 this.manager.connect( this, {
8151 resize: 'onResize'
8152 } );
8153
8154 return this;
8155 };
8156
8157 /**
8158 * @inheritdoc
8159 */
8160 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8161 this.fitActions();
8162 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8163 };
8164
8165 /**
8166 * Handle window resized events.
8167 *
8168 * @private
8169 */
8170 OO.ui.MessageDialog.prototype.onResize = function () {
8171 var dialog = this;
8172 dialog.fitActions();
8173 // Wait for CSS transition to finish and do it again :(
8174 setTimeout( function () {
8175 dialog.fitActions();
8176 }, 300 );
8177 };
8178
8179 /**
8180 * Toggle action layout between vertical and horizontal.
8181 *
8182 *
8183 * @private
8184 * @param {boolean} [value] Layout actions vertically, omit to toggle
8185 * @chainable
8186 */
8187 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8188 value = value === undefined ? !this.verticalActionLayout : !!value;
8189
8190 if ( value !== this.verticalActionLayout ) {
8191 this.verticalActionLayout = value;
8192 this.$actions
8193 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8194 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8195 }
8196
8197 return this;
8198 };
8199
8200 /**
8201 * @inheritdoc
8202 */
8203 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8204 if ( action ) {
8205 return new OO.ui.Process( function () {
8206 this.close( { action: action } );
8207 }, this );
8208 }
8209 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8210 };
8211
8212 /**
8213 * @inheritdoc
8214 *
8215 * @param {Object} [data] Dialog opening data
8216 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8217 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8218 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8219 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8220 * action item
8221 */
8222 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8223 data = data || {};
8224
8225 // Parent method
8226 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8227 .next( function () {
8228 this.title.setLabel(
8229 data.title !== undefined ? data.title : this.constructor.static.title
8230 );
8231 this.message.setLabel(
8232 data.message !== undefined ? data.message : this.constructor.static.message
8233 );
8234 this.message.$element.toggleClass(
8235 'oo-ui-messageDialog-message-verbose',
8236 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8237 );
8238 }, this );
8239 };
8240
8241 /**
8242 * @inheritdoc
8243 */
8244 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8245 data = data || {};
8246
8247 // Parent method
8248 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8249 .next( function () {
8250 // Focus the primary action button
8251 var actions = this.actions.get();
8252 actions = actions.filter( function ( action ) {
8253 return action.getFlags().indexOf( 'primary' ) > -1;
8254 } );
8255 if ( actions.length > 0 ) {
8256 actions[ 0 ].$button.focus();
8257 }
8258 }, this );
8259 };
8260
8261 /**
8262 * @inheritdoc
8263 */
8264 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8265 var bodyHeight, oldOverflow,
8266 $scrollable = this.container.$element;
8267
8268 oldOverflow = $scrollable[ 0 ].style.overflow;
8269 $scrollable[ 0 ].style.overflow = 'hidden';
8270
8271 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8272
8273 bodyHeight = this.text.$element.outerHeight( true );
8274 $scrollable[ 0 ].style.overflow = oldOverflow;
8275
8276 return bodyHeight;
8277 };
8278
8279 /**
8280 * @inheritdoc
8281 */
8282 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8283 var $scrollable = this.container.$element;
8284 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8285
8286 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8287 // Need to do it after transition completes (250ms), add 50ms just in case.
8288 setTimeout( function () {
8289 var oldOverflow = $scrollable[ 0 ].style.overflow;
8290 $scrollable[ 0 ].style.overflow = 'hidden';
8291
8292 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8293
8294 $scrollable[ 0 ].style.overflow = oldOverflow;
8295 }, 300 );
8296
8297 return this;
8298 };
8299
8300 /**
8301 * @inheritdoc
8302 */
8303 OO.ui.MessageDialog.prototype.initialize = function () {
8304 // Parent method
8305 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8306
8307 // Properties
8308 this.$actions = $( '<div>' );
8309 this.container = new OO.ui.PanelLayout( {
8310 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8311 } );
8312 this.text = new OO.ui.PanelLayout( {
8313 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8314 } );
8315 this.message = new OO.ui.LabelWidget( {
8316 classes: [ 'oo-ui-messageDialog-message' ]
8317 } );
8318
8319 // Initialization
8320 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8321 this.$content.addClass( 'oo-ui-messageDialog-content' );
8322 this.container.$element.append( this.text.$element );
8323 this.text.$element.append( this.title.$element, this.message.$element );
8324 this.$body.append( this.container.$element );
8325 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8326 this.$foot.append( this.$actions );
8327 };
8328
8329 /**
8330 * @inheritdoc
8331 */
8332 OO.ui.MessageDialog.prototype.attachActions = function () {
8333 var i, len, other, special, others;
8334
8335 // Parent method
8336 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8337
8338 special = this.actions.getSpecial();
8339 others = this.actions.getOthers();
8340
8341 if ( special.safe ) {
8342 this.$actions.append( special.safe.$element );
8343 special.safe.toggleFramed( false );
8344 }
8345 if ( others.length ) {
8346 for ( i = 0, len = others.length; i < len; i++ ) {
8347 other = others[ i ];
8348 this.$actions.append( other.$element );
8349 other.toggleFramed( false );
8350 }
8351 }
8352 if ( special.primary ) {
8353 this.$actions.append( special.primary.$element );
8354 special.primary.toggleFramed( false );
8355 }
8356
8357 if ( !this.isOpening() ) {
8358 // If the dialog is currently opening, this will be called automatically soon.
8359 // This also calls #fitActions.
8360 this.updateSize();
8361 }
8362 };
8363
8364 /**
8365 * Fit action actions into columns or rows.
8366 *
8367 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8368 *
8369 * @private
8370 */
8371 OO.ui.MessageDialog.prototype.fitActions = function () {
8372 var i, len, action,
8373 previous = this.verticalActionLayout,
8374 actions = this.actions.get();
8375
8376 // Detect clipping
8377 this.toggleVerticalActionLayout( false );
8378 for ( i = 0, len = actions.length; i < len; i++ ) {
8379 action = actions[ i ];
8380 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8381 this.toggleVerticalActionLayout( true );
8382 break;
8383 }
8384 }
8385
8386 // Move the body out of the way of the foot
8387 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8388
8389 if ( this.verticalActionLayout !== previous ) {
8390 // We changed the layout, window height might need to be updated.
8391 this.updateSize();
8392 }
8393 };
8394
8395 /**
8396 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8397 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8398 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8399 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8400 * required for each process.
8401 *
8402 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8403 * processes with an animation. The header contains the dialog title as well as
8404 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8405 * a ‘primary’ action on the right (e.g., ‘Done’).
8406 *
8407 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8408 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8409 *
8410 * @example
8411 * // Example: Creating and opening a process dialog window.
8412 * function MyProcessDialog( config ) {
8413 * MyProcessDialog.parent.call( this, config );
8414 * }
8415 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8416 *
8417 * MyProcessDialog.static.title = 'Process dialog';
8418 * MyProcessDialog.static.actions = [
8419 * { action: 'save', label: 'Done', flags: 'primary' },
8420 * { label: 'Cancel', flags: 'safe' }
8421 * ];
8422 *
8423 * MyProcessDialog.prototype.initialize = function () {
8424 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8425 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8426 * 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>' );
8427 * this.$body.append( this.content.$element );
8428 * };
8429 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8430 * var dialog = this;
8431 * if ( action ) {
8432 * return new OO.ui.Process( function () {
8433 * dialog.close( { action: action } );
8434 * } );
8435 * }
8436 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8437 * };
8438 *
8439 * var windowManager = new OO.ui.WindowManager();
8440 * $( 'body' ).append( windowManager.$element );
8441 *
8442 * var dialog = new MyProcessDialog();
8443 * windowManager.addWindows( [ dialog ] );
8444 * windowManager.openWindow( dialog );
8445 *
8446 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8447 *
8448 * @abstract
8449 * @class
8450 * @extends OO.ui.Dialog
8451 *
8452 * @constructor
8453 * @param {Object} [config] Configuration options
8454 */
8455 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8456 // Parent constructor
8457 OO.ui.ProcessDialog.parent.call( this, config );
8458
8459 // Properties
8460 this.fitOnOpen = false;
8461
8462 // Initialization
8463 this.$element.addClass( 'oo-ui-processDialog' );
8464 };
8465
8466 /* Setup */
8467
8468 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8469
8470 /* Methods */
8471
8472 /**
8473 * Handle dismiss button click events.
8474 *
8475 * Hides errors.
8476 *
8477 * @private
8478 */
8479 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8480 this.hideErrors();
8481 };
8482
8483 /**
8484 * Handle retry button click events.
8485 *
8486 * Hides errors and then tries again.
8487 *
8488 * @private
8489 */
8490 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8491 this.hideErrors();
8492 this.executeAction( this.currentAction );
8493 };
8494
8495 /**
8496 * @inheritdoc
8497 */
8498 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8499 if ( this.actions.isSpecial( action ) ) {
8500 this.fitLabel();
8501 }
8502 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8503 };
8504
8505 /**
8506 * @inheritdoc
8507 */
8508 OO.ui.ProcessDialog.prototype.initialize = function () {
8509 // Parent method
8510 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8511
8512 // Properties
8513 this.$navigation = $( '<div>' );
8514 this.$location = $( '<div>' );
8515 this.$safeActions = $( '<div>' );
8516 this.$primaryActions = $( '<div>' );
8517 this.$otherActions = $( '<div>' );
8518 this.dismissButton = new OO.ui.ButtonWidget( {
8519 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8520 } );
8521 this.retryButton = new OO.ui.ButtonWidget();
8522 this.$errors = $( '<div>' );
8523 this.$errorsTitle = $( '<div>' );
8524
8525 // Events
8526 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8527 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8528
8529 // Initialization
8530 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8531 this.$location
8532 .append( this.title.$element )
8533 .addClass( 'oo-ui-processDialog-location' );
8534 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8535 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8536 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8537 this.$errorsTitle
8538 .addClass( 'oo-ui-processDialog-errors-title' )
8539 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8540 this.$errors
8541 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8542 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8543 this.$content
8544 .addClass( 'oo-ui-processDialog-content' )
8545 .append( this.$errors );
8546 this.$navigation
8547 .addClass( 'oo-ui-processDialog-navigation' )
8548 .append( this.$safeActions, this.$location, this.$primaryActions );
8549 this.$head.append( this.$navigation );
8550 this.$foot.append( this.$otherActions );
8551 };
8552
8553 /**
8554 * @inheritdoc
8555 */
8556 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8557 var i, len, widgets = [];
8558 for ( i = 0, len = actions.length; i < len; i++ ) {
8559 widgets.push(
8560 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8561 );
8562 }
8563 return widgets;
8564 };
8565
8566 /**
8567 * @inheritdoc
8568 */
8569 OO.ui.ProcessDialog.prototype.attachActions = function () {
8570 var i, len, other, special, others;
8571
8572 // Parent method
8573 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8574
8575 special = this.actions.getSpecial();
8576 others = this.actions.getOthers();
8577 if ( special.primary ) {
8578 this.$primaryActions.append( special.primary.$element );
8579 }
8580 for ( i = 0, len = others.length; i < len; i++ ) {
8581 other = others[ i ];
8582 this.$otherActions.append( other.$element );
8583 }
8584 if ( special.safe ) {
8585 this.$safeActions.append( special.safe.$element );
8586 }
8587
8588 this.fitLabel();
8589 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8590 };
8591
8592 /**
8593 * @inheritdoc
8594 */
8595 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8596 var process = this;
8597 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8598 .fail( function ( errors ) {
8599 process.showErrors( errors || [] );
8600 } );
8601 };
8602
8603 /**
8604 * @inheritdoc
8605 */
8606 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8607 // Parent method
8608 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8609
8610 this.fitLabel();
8611 };
8612
8613 /**
8614 * Fit label between actions.
8615 *
8616 * @private
8617 * @chainable
8618 */
8619 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8620 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8621 size = this.getSizeProperties();
8622
8623 if ( typeof size.width !== 'number' ) {
8624 if ( this.isOpened() ) {
8625 navigationWidth = this.$head.width() - 20;
8626 } else if ( this.isOpening() ) {
8627 if ( !this.fitOnOpen ) {
8628 // Size is relative and the dialog isn't open yet, so wait.
8629 this.manager.opening.done( this.fitLabel.bind( this ) );
8630 this.fitOnOpen = true;
8631 }
8632 return;
8633 } else {
8634 return;
8635 }
8636 } else {
8637 navigationWidth = size.width - 20;
8638 }
8639
8640 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8641 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8642 biggerWidth = Math.max( safeWidth, primaryWidth );
8643
8644 labelWidth = this.title.$element.width();
8645
8646 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8647 // We have enough space to center the label
8648 leftWidth = rightWidth = biggerWidth;
8649 } else {
8650 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8651 if ( this.getDir() === 'ltr' ) {
8652 leftWidth = safeWidth;
8653 rightWidth = primaryWidth;
8654 } else {
8655 leftWidth = primaryWidth;
8656 rightWidth = safeWidth;
8657 }
8658 }
8659
8660 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8661
8662 return this;
8663 };
8664
8665 /**
8666 * Handle errors that occurred during accept or reject processes.
8667 *
8668 * @private
8669 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8670 */
8671 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8672 var i, len, $item, actions,
8673 items = [],
8674 abilities = {},
8675 recoverable = true,
8676 warning = false;
8677
8678 if ( errors instanceof OO.ui.Error ) {
8679 errors = [ errors ];
8680 }
8681
8682 for ( i = 0, len = errors.length; i < len; i++ ) {
8683 if ( !errors[ i ].isRecoverable() ) {
8684 recoverable = false;
8685 }
8686 if ( errors[ i ].isWarning() ) {
8687 warning = true;
8688 }
8689 $item = $( '<div>' )
8690 .addClass( 'oo-ui-processDialog-error' )
8691 .append( errors[ i ].getMessage() );
8692 items.push( $item[ 0 ] );
8693 }
8694 this.$errorItems = $( items );
8695 if ( recoverable ) {
8696 abilities[ this.currentAction ] = true;
8697 // Copy the flags from the first matching action
8698 actions = this.actions.get( { actions: this.currentAction } );
8699 if ( actions.length ) {
8700 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8701 }
8702 } else {
8703 abilities[ this.currentAction ] = false;
8704 this.actions.setAbilities( abilities );
8705 }
8706 if ( warning ) {
8707 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8708 } else {
8709 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8710 }
8711 this.retryButton.toggle( recoverable );
8712 this.$errorsTitle.after( this.$errorItems );
8713 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8714 };
8715
8716 /**
8717 * Hide errors.
8718 *
8719 * @private
8720 */
8721 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8722 this.$errors.addClass( 'oo-ui-element-hidden' );
8723 if ( this.$errorItems ) {
8724 this.$errorItems.remove();
8725 this.$errorItems = null;
8726 }
8727 };
8728
8729 /**
8730 * @inheritdoc
8731 */
8732 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8733 // Parent method
8734 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8735 .first( function () {
8736 // Make sure to hide errors
8737 this.hideErrors();
8738 this.fitOnOpen = false;
8739 }, this );
8740 };
8741
8742 /**
8743 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8744 * which is a widget that is specified by reference before any optional configuration settings.
8745 *
8746 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8747 *
8748 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8749 * A left-alignment is used for forms with many fields.
8750 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8751 * A right-alignment is used for long but familiar forms which users tab through,
8752 * verifying the current field with a quick glance at the label.
8753 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8754 * that users fill out from top to bottom.
8755 * - **inline**: The label is placed after the field-widget and aligned to the left.
8756 * An inline-alignment is best used with checkboxes or radio buttons.
8757 *
8758 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8759 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8760 *
8761 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8762 * @class
8763 * @extends OO.ui.Layout
8764 * @mixins OO.ui.mixin.LabelElement
8765 * @mixins OO.ui.mixin.TitledElement
8766 *
8767 * @constructor
8768 * @param {OO.ui.Widget} fieldWidget Field widget
8769 * @param {Object} [config] Configuration options
8770 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8771 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8772 * The array may contain strings or OO.ui.HtmlSnippet instances.
8773 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8774 * The array may contain strings or OO.ui.HtmlSnippet instances.
8775 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8776 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8777 * For important messages, you are advised to use `notices`, as they are always shown.
8778 *
8779 * @throws {Error} An error is thrown if no widget is specified
8780 */
8781 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8782 var hasInputWidget, div, i;
8783
8784 // Allow passing positional parameters inside the config object
8785 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8786 config = fieldWidget;
8787 fieldWidget = config.fieldWidget;
8788 }
8789
8790 // Make sure we have required constructor arguments
8791 if ( fieldWidget === undefined ) {
8792 throw new Error( 'Widget not found' );
8793 }
8794
8795 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
8796
8797 // Configuration initialization
8798 config = $.extend( { align: 'left' }, config );
8799
8800 // Parent constructor
8801 OO.ui.FieldLayout.parent.call( this, config );
8802
8803 // Mixin constructors
8804 OO.ui.mixin.LabelElement.call( this, config );
8805 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8806
8807 // Properties
8808 this.fieldWidget = fieldWidget;
8809 this.errors = config.errors || [];
8810 this.notices = config.notices || [];
8811 this.$field = $( '<div>' );
8812 this.$messages = $( '<ul>' );
8813 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8814 this.align = null;
8815 if ( config.help ) {
8816 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8817 classes: [ 'oo-ui-fieldLayout-help' ],
8818 framed: false,
8819 icon: 'info'
8820 } );
8821
8822 div = $( '<div>' );
8823 if ( config.help instanceof OO.ui.HtmlSnippet ) {
8824 div.html( config.help.toString() );
8825 } else {
8826 div.text( config.help );
8827 }
8828 this.popupButtonWidget.getPopup().$body.append(
8829 div.addClass( 'oo-ui-fieldLayout-help-content' )
8830 );
8831 this.$help = this.popupButtonWidget.$element;
8832 } else {
8833 this.$help = $( [] );
8834 }
8835
8836 // Events
8837 if ( hasInputWidget ) {
8838 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8839 }
8840 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8841
8842 // Initialization
8843 this.$element
8844 .addClass( 'oo-ui-fieldLayout' )
8845 .append( this.$help, this.$body );
8846 if ( this.errors.length || this.notices.length ) {
8847 this.$element.append( this.$messages );
8848 }
8849 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8850 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
8851 this.$field
8852 .addClass( 'oo-ui-fieldLayout-field' )
8853 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8854 .append( this.fieldWidget.$element );
8855
8856 for ( i = 0; i < this.notices.length; i++ ) {
8857 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
8858 }
8859 for ( i = 0; i < this.errors.length; i++ ) {
8860 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
8861 }
8862
8863 this.setAlignment( config.align );
8864 };
8865
8866 /* Setup */
8867
8868 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8869 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
8870 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
8871
8872 /* Methods */
8873
8874 /**
8875 * Handle field disable events.
8876 *
8877 * @private
8878 * @param {boolean} value Field is disabled
8879 */
8880 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8881 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8882 };
8883
8884 /**
8885 * Handle label mouse click events.
8886 *
8887 * @private
8888 * @param {jQuery.Event} e Mouse click event
8889 */
8890 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8891 this.fieldWidget.simulateLabelClick();
8892 return false;
8893 };
8894
8895 /**
8896 * Get the widget contained by the field.
8897 *
8898 * @return {OO.ui.Widget} Field widget
8899 */
8900 OO.ui.FieldLayout.prototype.getField = function () {
8901 return this.fieldWidget;
8902 };
8903
8904 /**
8905 * @param {string} kind 'error' or 'notice'
8906 * @param {string|OO.ui.HtmlSnippet} text
8907 * @return {jQuery}
8908 */
8909 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
8910 var $listItem, $icon, message;
8911 $listItem = $( '<li>' );
8912 if ( kind === 'error' ) {
8913 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
8914 } else if ( kind === 'notice' ) {
8915 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
8916 } else {
8917 $icon = '';
8918 }
8919 message = new OO.ui.LabelWidget( { label: text } );
8920 $listItem
8921 .append( $icon, message.$element )
8922 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
8923 return $listItem;
8924 };
8925
8926 /**
8927 * Set the field alignment mode.
8928 *
8929 * @private
8930 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8931 * @chainable
8932 */
8933 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8934 if ( value !== this.align ) {
8935 // Default to 'left'
8936 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8937 value = 'left';
8938 }
8939 // Reorder elements
8940 if ( value === 'inline' ) {
8941 this.$body.append( this.$field, this.$label );
8942 } else {
8943 this.$body.append( this.$label, this.$field );
8944 }
8945 // Set classes. The following classes can be used here:
8946 // * oo-ui-fieldLayout-align-left
8947 // * oo-ui-fieldLayout-align-right
8948 // * oo-ui-fieldLayout-align-top
8949 // * oo-ui-fieldLayout-align-inline
8950 if ( this.align ) {
8951 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8952 }
8953 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8954 this.align = value;
8955 }
8956
8957 return this;
8958 };
8959
8960 /**
8961 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8962 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8963 * is required and is specified before any optional configuration settings.
8964 *
8965 * Labels can be aligned in one of four ways:
8966 *
8967 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8968 * A left-alignment is used for forms with many fields.
8969 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8970 * A right-alignment is used for long but familiar forms which users tab through,
8971 * verifying the current field with a quick glance at the label.
8972 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8973 * that users fill out from top to bottom.
8974 * - **inline**: The label is placed after the field-widget and aligned to the left.
8975 * An inline-alignment is best used with checkboxes or radio buttons.
8976 *
8977 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8978 * text is specified.
8979 *
8980 * @example
8981 * // Example of an ActionFieldLayout
8982 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8983 * new OO.ui.TextInputWidget( {
8984 * placeholder: 'Field widget'
8985 * } ),
8986 * new OO.ui.ButtonWidget( {
8987 * label: 'Button'
8988 * } ),
8989 * {
8990 * label: 'An ActionFieldLayout. This label is aligned top',
8991 * align: 'top',
8992 * help: 'This is help text'
8993 * }
8994 * );
8995 *
8996 * $( 'body' ).append( actionFieldLayout.$element );
8997 *
8998 *
8999 * @class
9000 * @extends OO.ui.FieldLayout
9001 *
9002 * @constructor
9003 * @param {OO.ui.Widget} fieldWidget Field widget
9004 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9005 */
9006 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9007 // Allow passing positional parameters inside the config object
9008 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9009 config = fieldWidget;
9010 fieldWidget = config.fieldWidget;
9011 buttonWidget = config.buttonWidget;
9012 }
9013
9014 // Parent constructor
9015 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9016
9017 // Properties
9018 this.buttonWidget = buttonWidget;
9019 this.$button = $( '<div>' );
9020 this.$input = $( '<div>' );
9021
9022 // Initialization
9023 this.$element
9024 .addClass( 'oo-ui-actionFieldLayout' );
9025 this.$button
9026 .addClass( 'oo-ui-actionFieldLayout-button' )
9027 .append( this.buttonWidget.$element );
9028 this.$input
9029 .addClass( 'oo-ui-actionFieldLayout-input' )
9030 .append( this.fieldWidget.$element );
9031 this.$field
9032 .append( this.$input, this.$button );
9033 };
9034
9035 /* Setup */
9036
9037 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9038
9039 /**
9040 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9041 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9042 * configured with a label as well. For more information and examples,
9043 * please see the [OOjs UI documentation on MediaWiki][1].
9044 *
9045 * @example
9046 * // Example of a fieldset layout
9047 * var input1 = new OO.ui.TextInputWidget( {
9048 * placeholder: 'A text input field'
9049 * } );
9050 *
9051 * var input2 = new OO.ui.TextInputWidget( {
9052 * placeholder: 'A text input field'
9053 * } );
9054 *
9055 * var fieldset = new OO.ui.FieldsetLayout( {
9056 * label: 'Example of a fieldset layout'
9057 * } );
9058 *
9059 * fieldset.addItems( [
9060 * new OO.ui.FieldLayout( input1, {
9061 * label: 'Field One'
9062 * } ),
9063 * new OO.ui.FieldLayout( input2, {
9064 * label: 'Field Two'
9065 * } )
9066 * ] );
9067 * $( 'body' ).append( fieldset.$element );
9068 *
9069 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9070 *
9071 * @class
9072 * @extends OO.ui.Layout
9073 * @mixins OO.ui.mixin.IconElement
9074 * @mixins OO.ui.mixin.LabelElement
9075 * @mixins OO.ui.mixin.GroupElement
9076 *
9077 * @constructor
9078 * @param {Object} [config] Configuration options
9079 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9080 */
9081 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9082 // Configuration initialization
9083 config = config || {};
9084
9085 // Parent constructor
9086 OO.ui.FieldsetLayout.parent.call( this, config );
9087
9088 // Mixin constructors
9089 OO.ui.mixin.IconElement.call( this, config );
9090 OO.ui.mixin.LabelElement.call( this, config );
9091 OO.ui.mixin.GroupElement.call( this, config );
9092
9093 if ( config.help ) {
9094 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9095 classes: [ 'oo-ui-fieldsetLayout-help' ],
9096 framed: false,
9097 icon: 'info'
9098 } );
9099
9100 this.popupButtonWidget.getPopup().$body.append(
9101 $( '<div>' )
9102 .text( config.help )
9103 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9104 );
9105 this.$help = this.popupButtonWidget.$element;
9106 } else {
9107 this.$help = $( [] );
9108 }
9109
9110 // Initialization
9111 this.$element
9112 .addClass( 'oo-ui-fieldsetLayout' )
9113 .prepend( this.$help, this.$icon, this.$label, this.$group );
9114 if ( Array.isArray( config.items ) ) {
9115 this.addItems( config.items );
9116 }
9117 };
9118
9119 /* Setup */
9120
9121 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9122 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9123 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9124 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9125
9126 /**
9127 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9128 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9129 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9130 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9131 *
9132 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9133 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9134 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9135 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9136 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9137 * often have simplified APIs to match the capabilities of HTML forms.
9138 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9139 *
9140 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9141 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9142 *
9143 * @example
9144 * // Example of a form layout that wraps a fieldset layout
9145 * var input1 = new OO.ui.TextInputWidget( {
9146 * placeholder: 'Username'
9147 * } );
9148 * var input2 = new OO.ui.TextInputWidget( {
9149 * placeholder: 'Password',
9150 * type: 'password'
9151 * } );
9152 * var submit = new OO.ui.ButtonInputWidget( {
9153 * label: 'Submit'
9154 * } );
9155 *
9156 * var fieldset = new OO.ui.FieldsetLayout( {
9157 * label: 'A form layout'
9158 * } );
9159 * fieldset.addItems( [
9160 * new OO.ui.FieldLayout( input1, {
9161 * label: 'Username',
9162 * align: 'top'
9163 * } ),
9164 * new OO.ui.FieldLayout( input2, {
9165 * label: 'Password',
9166 * align: 'top'
9167 * } ),
9168 * new OO.ui.FieldLayout( submit )
9169 * ] );
9170 * var form = new OO.ui.FormLayout( {
9171 * items: [ fieldset ],
9172 * action: '/api/formhandler',
9173 * method: 'get'
9174 * } )
9175 * $( 'body' ).append( form.$element );
9176 *
9177 * @class
9178 * @extends OO.ui.Layout
9179 * @mixins OO.ui.mixin.GroupElement
9180 *
9181 * @constructor
9182 * @param {Object} [config] Configuration options
9183 * @cfg {string} [method] HTML form `method` attribute
9184 * @cfg {string} [action] HTML form `action` attribute
9185 * @cfg {string} [enctype] HTML form `enctype` attribute
9186 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9187 */
9188 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9189 // Configuration initialization
9190 config = config || {};
9191
9192 // Parent constructor
9193 OO.ui.FormLayout.parent.call( this, config );
9194
9195 // Mixin constructors
9196 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9197
9198 // Events
9199 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9200
9201 // Make sure the action is safe
9202 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9203 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9204 }
9205
9206 // Initialization
9207 this.$element
9208 .addClass( 'oo-ui-formLayout' )
9209 .attr( {
9210 method: config.method,
9211 action: config.action,
9212 enctype: config.enctype
9213 } );
9214 if ( Array.isArray( config.items ) ) {
9215 this.addItems( config.items );
9216 }
9217 };
9218
9219 /* Setup */
9220
9221 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9222 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9223
9224 /* Events */
9225
9226 /**
9227 * A 'submit' event is emitted when the form is submitted.
9228 *
9229 * @event submit
9230 */
9231
9232 /* Static Properties */
9233
9234 OO.ui.FormLayout.static.tagName = 'form';
9235
9236 /* Methods */
9237
9238 /**
9239 * Handle form submit events.
9240 *
9241 * @private
9242 * @param {jQuery.Event} e Submit event
9243 * @fires submit
9244 */
9245 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9246 if ( this.emit( 'submit' ) ) {
9247 return false;
9248 }
9249 };
9250
9251 /**
9252 * 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)
9253 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9254 *
9255 * @example
9256 * var menuLayout = new OO.ui.MenuLayout( {
9257 * position: 'top'
9258 * } ),
9259 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9260 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9261 * select = new OO.ui.SelectWidget( {
9262 * items: [
9263 * new OO.ui.OptionWidget( {
9264 * data: 'before',
9265 * label: 'Before',
9266 * } ),
9267 * new OO.ui.OptionWidget( {
9268 * data: 'after',
9269 * label: 'After',
9270 * } ),
9271 * new OO.ui.OptionWidget( {
9272 * data: 'top',
9273 * label: 'Top',
9274 * } ),
9275 * new OO.ui.OptionWidget( {
9276 * data: 'bottom',
9277 * label: 'Bottom',
9278 * } )
9279 * ]
9280 * } ).on( 'select', function ( item ) {
9281 * menuLayout.setMenuPosition( item.getData() );
9282 * } );
9283 *
9284 * menuLayout.$menu.append(
9285 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9286 * );
9287 * menuLayout.$content.append(
9288 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9289 * );
9290 * $( 'body' ).append( menuLayout.$element );
9291 *
9292 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9293 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9294 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9295 * may be omitted.
9296 *
9297 * .oo-ui-menuLayout-menu {
9298 * height: 200px;
9299 * width: 200px;
9300 * }
9301 * .oo-ui-menuLayout-content {
9302 * top: 200px;
9303 * left: 200px;
9304 * right: 200px;
9305 * bottom: 200px;
9306 * }
9307 *
9308 * @class
9309 * @extends OO.ui.Layout
9310 *
9311 * @constructor
9312 * @param {Object} [config] Configuration options
9313 * @cfg {boolean} [showMenu=true] Show menu
9314 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9315 */
9316 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9317 // Configuration initialization
9318 config = $.extend( {
9319 showMenu: true,
9320 menuPosition: 'before'
9321 }, config );
9322
9323 // Parent constructor
9324 OO.ui.MenuLayout.parent.call( this, config );
9325
9326 /**
9327 * Menu DOM node
9328 *
9329 * @property {jQuery}
9330 */
9331 this.$menu = $( '<div>' );
9332 /**
9333 * Content DOM node
9334 *
9335 * @property {jQuery}
9336 */
9337 this.$content = $( '<div>' );
9338
9339 // Initialization
9340 this.$menu
9341 .addClass( 'oo-ui-menuLayout-menu' );
9342 this.$content.addClass( 'oo-ui-menuLayout-content' );
9343 this.$element
9344 .addClass( 'oo-ui-menuLayout' )
9345 .append( this.$content, this.$menu );
9346 this.setMenuPosition( config.menuPosition );
9347 this.toggleMenu( config.showMenu );
9348 };
9349
9350 /* Setup */
9351
9352 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9353
9354 /* Methods */
9355
9356 /**
9357 * Toggle menu.
9358 *
9359 * @param {boolean} showMenu Show menu, omit to toggle
9360 * @chainable
9361 */
9362 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9363 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9364
9365 if ( this.showMenu !== showMenu ) {
9366 this.showMenu = showMenu;
9367 this.$element
9368 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9369 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9370 }
9371
9372 return this;
9373 };
9374
9375 /**
9376 * Check if menu is visible
9377 *
9378 * @return {boolean} Menu is visible
9379 */
9380 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9381 return this.showMenu;
9382 };
9383
9384 /**
9385 * Set menu position.
9386 *
9387 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9388 * @throws {Error} If position value is not supported
9389 * @chainable
9390 */
9391 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9392 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9393 this.menuPosition = position;
9394 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9395
9396 return this;
9397 };
9398
9399 /**
9400 * Get menu position.
9401 *
9402 * @return {string} Menu position
9403 */
9404 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9405 return this.menuPosition;
9406 };
9407
9408 /**
9409 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9410 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9411 * through the pages and select which one to display. By default, only one page is
9412 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9413 * the booklet layout automatically focuses on the first focusable element, unless the
9414 * default setting is changed. Optionally, booklets can be configured to show
9415 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9416 *
9417 * @example
9418 * // Example of a BookletLayout that contains two PageLayouts.
9419 *
9420 * function PageOneLayout( name, config ) {
9421 * PageOneLayout.parent.call( this, name, config );
9422 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9423 * }
9424 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9425 * PageOneLayout.prototype.setupOutlineItem = function () {
9426 * this.outlineItem.setLabel( 'Page One' );
9427 * };
9428 *
9429 * function PageTwoLayout( name, config ) {
9430 * PageTwoLayout.parent.call( this, name, config );
9431 * this.$element.append( '<p>Second page</p>' );
9432 * }
9433 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9434 * PageTwoLayout.prototype.setupOutlineItem = function () {
9435 * this.outlineItem.setLabel( 'Page Two' );
9436 * };
9437 *
9438 * var page1 = new PageOneLayout( 'one' ),
9439 * page2 = new PageTwoLayout( 'two' );
9440 *
9441 * var booklet = new OO.ui.BookletLayout( {
9442 * outlined: true
9443 * } );
9444 *
9445 * booklet.addPages ( [ page1, page2 ] );
9446 * $( 'body' ).append( booklet.$element );
9447 *
9448 * @class
9449 * @extends OO.ui.MenuLayout
9450 *
9451 * @constructor
9452 * @param {Object} [config] Configuration options
9453 * @cfg {boolean} [continuous=false] Show all pages, one after another
9454 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9455 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9456 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9457 */
9458 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9459 // Configuration initialization
9460 config = config || {};
9461
9462 // Parent constructor
9463 OO.ui.BookletLayout.parent.call( this, config );
9464
9465 // Properties
9466 this.currentPageName = null;
9467 this.pages = {};
9468 this.ignoreFocus = false;
9469 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9470 this.$content.append( this.stackLayout.$element );
9471 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9472 this.outlineVisible = false;
9473 this.outlined = !!config.outlined;
9474 if ( this.outlined ) {
9475 this.editable = !!config.editable;
9476 this.outlineControlsWidget = null;
9477 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9478 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9479 this.$menu.append( this.outlinePanel.$element );
9480 this.outlineVisible = true;
9481 if ( this.editable ) {
9482 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9483 this.outlineSelectWidget
9484 );
9485 }
9486 }
9487 this.toggleMenu( this.outlined );
9488
9489 // Events
9490 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9491 if ( this.outlined ) {
9492 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9493 }
9494 if ( this.autoFocus ) {
9495 // Event 'focus' does not bubble, but 'focusin' does
9496 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9497 }
9498
9499 // Initialization
9500 this.$element.addClass( 'oo-ui-bookletLayout' );
9501 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9502 if ( this.outlined ) {
9503 this.outlinePanel.$element
9504 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9505 .append( this.outlineSelectWidget.$element );
9506 if ( this.editable ) {
9507 this.outlinePanel.$element
9508 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9509 .append( this.outlineControlsWidget.$element );
9510 }
9511 }
9512 };
9513
9514 /* Setup */
9515
9516 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9517
9518 /* Events */
9519
9520 /**
9521 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9522 * @event set
9523 * @param {OO.ui.PageLayout} page Current page
9524 */
9525
9526 /**
9527 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9528 *
9529 * @event add
9530 * @param {OO.ui.PageLayout[]} page Added pages
9531 * @param {number} index Index pages were added at
9532 */
9533
9534 /**
9535 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9536 * {@link #removePages removed} from the booklet.
9537 *
9538 * @event remove
9539 * @param {OO.ui.PageLayout[]} pages Removed pages
9540 */
9541
9542 /* Methods */
9543
9544 /**
9545 * Handle stack layout focus.
9546 *
9547 * @private
9548 * @param {jQuery.Event} e Focusin event
9549 */
9550 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9551 var name, $target;
9552
9553 // Find the page that an element was focused within
9554 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9555 for ( name in this.pages ) {
9556 // Check for page match, exclude current page to find only page changes
9557 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9558 this.setPage( name );
9559 break;
9560 }
9561 }
9562 };
9563
9564 /**
9565 * Handle stack layout set events.
9566 *
9567 * @private
9568 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9569 */
9570 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9571 var layout = this;
9572 if ( page ) {
9573 page.scrollElementIntoView( { complete: function () {
9574 if ( layout.autoFocus ) {
9575 layout.focus();
9576 }
9577 } } );
9578 }
9579 };
9580
9581 /**
9582 * Focus the first input in the current page.
9583 *
9584 * If no page is selected, the first selectable page will be selected.
9585 * If the focus is already in an element on the current page, nothing will happen.
9586 * @param {number} [itemIndex] A specific item to focus on
9587 */
9588 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9589 var $input, page,
9590 items = this.stackLayout.getItems();
9591
9592 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9593 page = items[ itemIndex ];
9594 } else {
9595 page = this.stackLayout.getCurrentItem();
9596 }
9597
9598 if ( !page && this.outlined ) {
9599 this.selectFirstSelectablePage();
9600 page = this.stackLayout.getCurrentItem();
9601 }
9602 if ( !page ) {
9603 return;
9604 }
9605 // Only change the focus if is not already in the current page
9606 if ( !page.$element.find( ':focus' ).length ) {
9607 $input = page.$element.find( ':input:first' );
9608 if ( $input.length ) {
9609 $input[ 0 ].focus();
9610 }
9611 }
9612 };
9613
9614 /**
9615 * Find the first focusable input in the booklet layout and focus
9616 * on it.
9617 */
9618 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9619 var i, len,
9620 found = false,
9621 items = this.stackLayout.getItems(),
9622 checkAndFocus = function () {
9623 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9624 $( this ).focus();
9625 found = true;
9626 return false;
9627 }
9628 };
9629
9630 for ( i = 0, len = items.length; i < len; i++ ) {
9631 if ( found ) {
9632 break;
9633 }
9634 // Find all potentially focusable elements in the item
9635 // and check if they are focusable
9636 items[ i ].$element
9637 .find( 'input, select, textarea, button, object' )
9638 /* jshint loopfunc:true */
9639 .each( checkAndFocus );
9640 }
9641 };
9642
9643 /**
9644 * Handle outline widget select events.
9645 *
9646 * @private
9647 * @param {OO.ui.OptionWidget|null} item Selected item
9648 */
9649 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9650 if ( item ) {
9651 this.setPage( item.getData() );
9652 }
9653 };
9654
9655 /**
9656 * Check if booklet has an outline.
9657 *
9658 * @return {boolean} Booklet has an outline
9659 */
9660 OO.ui.BookletLayout.prototype.isOutlined = function () {
9661 return this.outlined;
9662 };
9663
9664 /**
9665 * Check if booklet has editing controls.
9666 *
9667 * @return {boolean} Booklet is editable
9668 */
9669 OO.ui.BookletLayout.prototype.isEditable = function () {
9670 return this.editable;
9671 };
9672
9673 /**
9674 * Check if booklet has a visible outline.
9675 *
9676 * @return {boolean} Outline is visible
9677 */
9678 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9679 return this.outlined && this.outlineVisible;
9680 };
9681
9682 /**
9683 * Hide or show the outline.
9684 *
9685 * @param {boolean} [show] Show outline, omit to invert current state
9686 * @chainable
9687 */
9688 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9689 if ( this.outlined ) {
9690 show = show === undefined ? !this.outlineVisible : !!show;
9691 this.outlineVisible = show;
9692 this.toggleMenu( show );
9693 }
9694
9695 return this;
9696 };
9697
9698 /**
9699 * Get the page closest to the specified page.
9700 *
9701 * @param {OO.ui.PageLayout} page Page to use as a reference point
9702 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9703 */
9704 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9705 var next, prev, level,
9706 pages = this.stackLayout.getItems(),
9707 index = pages.indexOf( page );
9708
9709 if ( index !== -1 ) {
9710 next = pages[ index + 1 ];
9711 prev = pages[ index - 1 ];
9712 // Prefer adjacent pages at the same level
9713 if ( this.outlined ) {
9714 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9715 if (
9716 prev &&
9717 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9718 ) {
9719 return prev;
9720 }
9721 if (
9722 next &&
9723 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9724 ) {
9725 return next;
9726 }
9727 }
9728 }
9729 return prev || next || null;
9730 };
9731
9732 /**
9733 * Get the outline widget.
9734 *
9735 * If the booklet is not outlined, the method will return `null`.
9736 *
9737 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9738 */
9739 OO.ui.BookletLayout.prototype.getOutline = function () {
9740 return this.outlineSelectWidget;
9741 };
9742
9743 /**
9744 * Get the outline controls widget.
9745 *
9746 * If the outline is not editable, the method will return `null`.
9747 *
9748 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9749 */
9750 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9751 return this.outlineControlsWidget;
9752 };
9753
9754 /**
9755 * Get a page by its symbolic name.
9756 *
9757 * @param {string} name Symbolic name of page
9758 * @return {OO.ui.PageLayout|undefined} Page, if found
9759 */
9760 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9761 return this.pages[ name ];
9762 };
9763
9764 /**
9765 * Get the current page.
9766 *
9767 * @return {OO.ui.PageLayout|undefined} Current page, if found
9768 */
9769 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9770 var name = this.getCurrentPageName();
9771 return name ? this.getPage( name ) : undefined;
9772 };
9773
9774 /**
9775 * Get the symbolic name of the current page.
9776 *
9777 * @return {string|null} Symbolic name of the current page
9778 */
9779 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9780 return this.currentPageName;
9781 };
9782
9783 /**
9784 * Add pages to the booklet layout
9785 *
9786 * When pages are added with the same names as existing pages, the existing pages will be
9787 * automatically removed before the new pages are added.
9788 *
9789 * @param {OO.ui.PageLayout[]} pages Pages to add
9790 * @param {number} index Index of the insertion point
9791 * @fires add
9792 * @chainable
9793 */
9794 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9795 var i, len, name, page, item, currentIndex,
9796 stackLayoutPages = this.stackLayout.getItems(),
9797 remove = [],
9798 items = [];
9799
9800 // Remove pages with same names
9801 for ( i = 0, len = pages.length; i < len; i++ ) {
9802 page = pages[ i ];
9803 name = page.getName();
9804
9805 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9806 // Correct the insertion index
9807 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
9808 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9809 index--;
9810 }
9811 remove.push( this.pages[ name ] );
9812 }
9813 }
9814 if ( remove.length ) {
9815 this.removePages( remove );
9816 }
9817
9818 // Add new pages
9819 for ( i = 0, len = pages.length; i < len; i++ ) {
9820 page = pages[ i ];
9821 name = page.getName();
9822 this.pages[ page.getName() ] = page;
9823 if ( this.outlined ) {
9824 item = new OO.ui.OutlineOptionWidget( { data: name } );
9825 page.setOutlineItem( item );
9826 items.push( item );
9827 }
9828 }
9829
9830 if ( this.outlined && items.length ) {
9831 this.outlineSelectWidget.addItems( items, index );
9832 this.selectFirstSelectablePage();
9833 }
9834 this.stackLayout.addItems( pages, index );
9835 this.emit( 'add', pages, index );
9836
9837 return this;
9838 };
9839
9840 /**
9841 * Remove the specified pages from the booklet layout.
9842 *
9843 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9844 *
9845 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9846 * @fires remove
9847 * @chainable
9848 */
9849 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9850 var i, len, name, page,
9851 items = [];
9852
9853 for ( i = 0, len = pages.length; i < len; i++ ) {
9854 page = pages[ i ];
9855 name = page.getName();
9856 delete this.pages[ name ];
9857 if ( this.outlined ) {
9858 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9859 page.setOutlineItem( null );
9860 }
9861 }
9862 if ( this.outlined && items.length ) {
9863 this.outlineSelectWidget.removeItems( items );
9864 this.selectFirstSelectablePage();
9865 }
9866 this.stackLayout.removeItems( pages );
9867 this.emit( 'remove', pages );
9868
9869 return this;
9870 };
9871
9872 /**
9873 * Clear all pages from the booklet layout.
9874 *
9875 * To remove only a subset of pages from the booklet, use the #removePages method.
9876 *
9877 * @fires remove
9878 * @chainable
9879 */
9880 OO.ui.BookletLayout.prototype.clearPages = function () {
9881 var i, len,
9882 pages = this.stackLayout.getItems();
9883
9884 this.pages = {};
9885 this.currentPageName = null;
9886 if ( this.outlined ) {
9887 this.outlineSelectWidget.clearItems();
9888 for ( i = 0, len = pages.length; i < len; i++ ) {
9889 pages[ i ].setOutlineItem( null );
9890 }
9891 }
9892 this.stackLayout.clearItems();
9893
9894 this.emit( 'remove', pages );
9895
9896 return this;
9897 };
9898
9899 /**
9900 * Set the current page by symbolic name.
9901 *
9902 * @fires set
9903 * @param {string} name Symbolic name of page
9904 */
9905 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9906 var selectedItem,
9907 $focused,
9908 page = this.pages[ name ];
9909
9910 if ( name !== this.currentPageName ) {
9911 if ( this.outlined ) {
9912 selectedItem = this.outlineSelectWidget.getSelectedItem();
9913 if ( selectedItem && selectedItem.getData() !== name ) {
9914 this.outlineSelectWidget.selectItemByData( name );
9915 }
9916 }
9917 if ( page ) {
9918 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9919 this.pages[ this.currentPageName ].setActive( false );
9920 // Blur anything focused if the next page doesn't have anything focusable - this
9921 // is not needed if the next page has something focusable because once it is focused
9922 // this blur happens automatically
9923 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9924 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9925 if ( $focused.length ) {
9926 $focused[ 0 ].blur();
9927 }
9928 }
9929 }
9930 this.currentPageName = name;
9931 this.stackLayout.setItem( page );
9932 page.setActive( true );
9933 this.emit( 'set', page );
9934 }
9935 }
9936 };
9937
9938 /**
9939 * Select the first selectable page.
9940 *
9941 * @chainable
9942 */
9943 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9944 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9945 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9946 }
9947
9948 return this;
9949 };
9950
9951 /**
9952 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9953 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9954 * select which one to display. By default, only one card is displayed at a time. When a user
9955 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9956 * unless the default setting is changed.
9957 *
9958 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9959 *
9960 * @example
9961 * // Example of a IndexLayout that contains two CardLayouts.
9962 *
9963 * function CardOneLayout( name, config ) {
9964 * CardOneLayout.parent.call( this, name, config );
9965 * this.$element.append( '<p>First card</p>' );
9966 * }
9967 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9968 * CardOneLayout.prototype.setupTabItem = function () {
9969 * this.tabItem.setLabel( 'Card One' );
9970 * };
9971 *
9972 * function CardTwoLayout( name, config ) {
9973 * CardTwoLayout.parent.call( this, name, config );
9974 * this.$element.append( '<p>Second card</p>' );
9975 * }
9976 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9977 * CardTwoLayout.prototype.setupTabItem = function () {
9978 * this.tabItem.setLabel( 'Card Two' );
9979 * };
9980 *
9981 * var card1 = new CardOneLayout( 'one' ),
9982 * card2 = new CardTwoLayout( 'two' );
9983 *
9984 * var index = new OO.ui.IndexLayout();
9985 *
9986 * index.addCards ( [ card1, card2 ] );
9987 * $( 'body' ).append( index.$element );
9988 *
9989 * @class
9990 * @extends OO.ui.MenuLayout
9991 *
9992 * @constructor
9993 * @param {Object} [config] Configuration options
9994 * @cfg {boolean} [continuous=false] Show all cards, one after another
9995 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9996 */
9997 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
9998 // Configuration initialization
9999 config = $.extend( {}, config, { menuPosition: 'top' } );
10000
10001 // Parent constructor
10002 OO.ui.IndexLayout.parent.call( this, config );
10003
10004 // Properties
10005 this.currentCardName = null;
10006 this.cards = {};
10007 this.ignoreFocus = false;
10008 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
10009 this.$content.append( this.stackLayout.$element );
10010 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10011
10012 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10013 this.tabPanel = new OO.ui.PanelLayout();
10014 this.$menu.append( this.tabPanel.$element );
10015
10016 this.toggleMenu( true );
10017
10018 // Events
10019 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10020 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10021 if ( this.autoFocus ) {
10022 // Event 'focus' does not bubble, but 'focusin' does
10023 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10024 }
10025
10026 // Initialization
10027 this.$element.addClass( 'oo-ui-indexLayout' );
10028 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10029 this.tabPanel.$element
10030 .addClass( 'oo-ui-indexLayout-tabPanel' )
10031 .append( this.tabSelectWidget.$element );
10032 };
10033
10034 /* Setup */
10035
10036 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10037
10038 /* Events */
10039
10040 /**
10041 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10042 * @event set
10043 * @param {OO.ui.CardLayout} card Current card
10044 */
10045
10046 /**
10047 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10048 *
10049 * @event add
10050 * @param {OO.ui.CardLayout[]} card Added cards
10051 * @param {number} index Index cards were added at
10052 */
10053
10054 /**
10055 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10056 * {@link #removeCards removed} from the index.
10057 *
10058 * @event remove
10059 * @param {OO.ui.CardLayout[]} cards Removed cards
10060 */
10061
10062 /* Methods */
10063
10064 /**
10065 * Handle stack layout focus.
10066 *
10067 * @private
10068 * @param {jQuery.Event} e Focusin event
10069 */
10070 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10071 var name, $target;
10072
10073 // Find the card that an element was focused within
10074 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10075 for ( name in this.cards ) {
10076 // Check for card match, exclude current card to find only card changes
10077 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10078 this.setCard( name );
10079 break;
10080 }
10081 }
10082 };
10083
10084 /**
10085 * Handle stack layout set events.
10086 *
10087 * @private
10088 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10089 */
10090 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10091 var layout = this;
10092 if ( card ) {
10093 card.scrollElementIntoView( { complete: function () {
10094 if ( layout.autoFocus ) {
10095 layout.focus();
10096 }
10097 } } );
10098 }
10099 };
10100
10101 /**
10102 * Focus the first input in the current card.
10103 *
10104 * If no card is selected, the first selectable card will be selected.
10105 * If the focus is already in an element on the current card, nothing will happen.
10106 * @param {number} [itemIndex] A specific item to focus on
10107 */
10108 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10109 var $input, card,
10110 items = this.stackLayout.getItems();
10111
10112 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10113 card = items[ itemIndex ];
10114 } else {
10115 card = this.stackLayout.getCurrentItem();
10116 }
10117
10118 if ( !card ) {
10119 this.selectFirstSelectableCard();
10120 card = this.stackLayout.getCurrentItem();
10121 }
10122 if ( !card ) {
10123 return;
10124 }
10125 // Only change the focus if is not already in the current card
10126 if ( !card.$element.find( ':focus' ).length ) {
10127 $input = card.$element.find( ':input:first' );
10128 if ( $input.length ) {
10129 $input[ 0 ].focus();
10130 }
10131 }
10132 };
10133
10134 /**
10135 * Find the first focusable input in the index layout and focus
10136 * on it.
10137 */
10138 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10139 var i, len,
10140 found = false,
10141 items = this.stackLayout.getItems(),
10142 checkAndFocus = function () {
10143 if ( OO.ui.isFocusableElement( $( this ) ) ) {
10144 $( this ).focus();
10145 found = true;
10146 return false;
10147 }
10148 };
10149
10150 for ( i = 0, len = items.length; i < len; i++ ) {
10151 if ( found ) {
10152 break;
10153 }
10154 // Find all potentially focusable elements in the item
10155 // and check if they are focusable
10156 items[ i ].$element
10157 .find( 'input, select, textarea, button, object' )
10158 .each( checkAndFocus );
10159 }
10160 };
10161
10162 /**
10163 * Handle tab widget select events.
10164 *
10165 * @private
10166 * @param {OO.ui.OptionWidget|null} item Selected item
10167 */
10168 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10169 if ( item ) {
10170 this.setCard( item.getData() );
10171 }
10172 };
10173
10174 /**
10175 * Get the card closest to the specified card.
10176 *
10177 * @param {OO.ui.CardLayout} card Card to use as a reference point
10178 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10179 */
10180 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10181 var next, prev, level,
10182 cards = this.stackLayout.getItems(),
10183 index = cards.indexOf( card );
10184
10185 if ( index !== -1 ) {
10186 next = cards[ index + 1 ];
10187 prev = cards[ index - 1 ];
10188 // Prefer adjacent cards at the same level
10189 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10190 if (
10191 prev &&
10192 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10193 ) {
10194 return prev;
10195 }
10196 if (
10197 next &&
10198 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10199 ) {
10200 return next;
10201 }
10202 }
10203 return prev || next || null;
10204 };
10205
10206 /**
10207 * Get the tabs widget.
10208 *
10209 * @return {OO.ui.TabSelectWidget} Tabs widget
10210 */
10211 OO.ui.IndexLayout.prototype.getTabs = function () {
10212 return this.tabSelectWidget;
10213 };
10214
10215 /**
10216 * Get a card by its symbolic name.
10217 *
10218 * @param {string} name Symbolic name of card
10219 * @return {OO.ui.CardLayout|undefined} Card, if found
10220 */
10221 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10222 return this.cards[ name ];
10223 };
10224
10225 /**
10226 * Get the current card.
10227 *
10228 * @return {OO.ui.CardLayout|undefined} Current card, if found
10229 */
10230 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10231 var name = this.getCurrentCardName();
10232 return name ? this.getCard( name ) : undefined;
10233 };
10234
10235 /**
10236 * Get the symbolic name of the current card.
10237 *
10238 * @return {string|null} Symbolic name of the current card
10239 */
10240 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10241 return this.currentCardName;
10242 };
10243
10244 /**
10245 * Add cards to the index layout
10246 *
10247 * When cards are added with the same names as existing cards, the existing cards will be
10248 * automatically removed before the new cards are added.
10249 *
10250 * @param {OO.ui.CardLayout[]} cards Cards to add
10251 * @param {number} index Index of the insertion point
10252 * @fires add
10253 * @chainable
10254 */
10255 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10256 var i, len, name, card, item, currentIndex,
10257 stackLayoutCards = this.stackLayout.getItems(),
10258 remove = [],
10259 items = [];
10260
10261 // Remove cards with same names
10262 for ( i = 0, len = cards.length; i < len; i++ ) {
10263 card = cards[ i ];
10264 name = card.getName();
10265
10266 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10267 // Correct the insertion index
10268 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10269 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10270 index--;
10271 }
10272 remove.push( this.cards[ name ] );
10273 }
10274 }
10275 if ( remove.length ) {
10276 this.removeCards( remove );
10277 }
10278
10279 // Add new cards
10280 for ( i = 0, len = cards.length; i < len; i++ ) {
10281 card = cards[ i ];
10282 name = card.getName();
10283 this.cards[ card.getName() ] = card;
10284 item = new OO.ui.TabOptionWidget( { data: name } );
10285 card.setTabItem( item );
10286 items.push( item );
10287 }
10288
10289 if ( items.length ) {
10290 this.tabSelectWidget.addItems( items, index );
10291 this.selectFirstSelectableCard();
10292 }
10293 this.stackLayout.addItems( cards, index );
10294 this.emit( 'add', cards, index );
10295
10296 return this;
10297 };
10298
10299 /**
10300 * Remove the specified cards from the index layout.
10301 *
10302 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10303 *
10304 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10305 * @fires remove
10306 * @chainable
10307 */
10308 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10309 var i, len, name, card,
10310 items = [];
10311
10312 for ( i = 0, len = cards.length; i < len; i++ ) {
10313 card = cards[ i ];
10314 name = card.getName();
10315 delete this.cards[ name ];
10316 items.push( this.tabSelectWidget.getItemFromData( name ) );
10317 card.setTabItem( null );
10318 }
10319 if ( items.length ) {
10320 this.tabSelectWidget.removeItems( items );
10321 this.selectFirstSelectableCard();
10322 }
10323 this.stackLayout.removeItems( cards );
10324 this.emit( 'remove', cards );
10325
10326 return this;
10327 };
10328
10329 /**
10330 * Clear all cards from the index layout.
10331 *
10332 * To remove only a subset of cards from the index, use the #removeCards method.
10333 *
10334 * @fires remove
10335 * @chainable
10336 */
10337 OO.ui.IndexLayout.prototype.clearCards = function () {
10338 var i, len,
10339 cards = this.stackLayout.getItems();
10340
10341 this.cards = {};
10342 this.currentCardName = null;
10343 this.tabSelectWidget.clearItems();
10344 for ( i = 0, len = cards.length; i < len; i++ ) {
10345 cards[ i ].setTabItem( null );
10346 }
10347 this.stackLayout.clearItems();
10348
10349 this.emit( 'remove', cards );
10350
10351 return this;
10352 };
10353
10354 /**
10355 * Set the current card by symbolic name.
10356 *
10357 * @fires set
10358 * @param {string} name Symbolic name of card
10359 */
10360 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10361 var selectedItem,
10362 $focused,
10363 card = this.cards[ name ];
10364
10365 if ( name !== this.currentCardName ) {
10366 selectedItem = this.tabSelectWidget.getSelectedItem();
10367 if ( selectedItem && selectedItem.getData() !== name ) {
10368 this.tabSelectWidget.selectItemByData( name );
10369 }
10370 if ( card ) {
10371 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
10372 this.cards[ this.currentCardName ].setActive( false );
10373 // Blur anything focused if the next card doesn't have anything focusable - this
10374 // is not needed if the next card has something focusable because once it is focused
10375 // this blur happens automatically
10376 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
10377 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
10378 if ( $focused.length ) {
10379 $focused[ 0 ].blur();
10380 }
10381 }
10382 }
10383 this.currentCardName = name;
10384 this.stackLayout.setItem( card );
10385 card.setActive( true );
10386 this.emit( 'set', card );
10387 }
10388 }
10389 };
10390
10391 /**
10392 * Select the first selectable card.
10393 *
10394 * @chainable
10395 */
10396 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10397 if ( !this.tabSelectWidget.getSelectedItem() ) {
10398 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10399 }
10400
10401 return this;
10402 };
10403
10404 /**
10405 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10406 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10407 *
10408 * @example
10409 * // Example of a panel layout
10410 * var panel = new OO.ui.PanelLayout( {
10411 * expanded: false,
10412 * framed: true,
10413 * padded: true,
10414 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10415 * } );
10416 * $( 'body' ).append( panel.$element );
10417 *
10418 * @class
10419 * @extends OO.ui.Layout
10420 *
10421 * @constructor
10422 * @param {Object} [config] Configuration options
10423 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10424 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10425 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10426 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10427 */
10428 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10429 // Configuration initialization
10430 config = $.extend( {
10431 scrollable: false,
10432 padded: false,
10433 expanded: true,
10434 framed: false
10435 }, config );
10436
10437 // Parent constructor
10438 OO.ui.PanelLayout.parent.call( this, config );
10439
10440 // Initialization
10441 this.$element.addClass( 'oo-ui-panelLayout' );
10442 if ( config.scrollable ) {
10443 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10444 }
10445 if ( config.padded ) {
10446 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10447 }
10448 if ( config.expanded ) {
10449 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10450 }
10451 if ( config.framed ) {
10452 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10453 }
10454 };
10455
10456 /* Setup */
10457
10458 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10459
10460 /**
10461 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10462 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10463 * rather extended to include the required content and functionality.
10464 *
10465 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10466 * item is customized (with a label) using the #setupTabItem method. See
10467 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10468 *
10469 * @class
10470 * @extends OO.ui.PanelLayout
10471 *
10472 * @constructor
10473 * @param {string} name Unique symbolic name of card
10474 * @param {Object} [config] Configuration options
10475 */
10476 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10477 // Allow passing positional parameters inside the config object
10478 if ( OO.isPlainObject( name ) && config === undefined ) {
10479 config = name;
10480 name = config.name;
10481 }
10482
10483 // Configuration initialization
10484 config = $.extend( { scrollable: true }, config );
10485
10486 // Parent constructor
10487 OO.ui.CardLayout.parent.call( this, config );
10488
10489 // Properties
10490 this.name = name;
10491 this.tabItem = null;
10492 this.active = false;
10493
10494 // Initialization
10495 this.$element.addClass( 'oo-ui-cardLayout' );
10496 };
10497
10498 /* Setup */
10499
10500 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10501
10502 /* Events */
10503
10504 /**
10505 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10506 * shown in a index layout that is configured to display only one card at a time.
10507 *
10508 * @event active
10509 * @param {boolean} active Card is active
10510 */
10511
10512 /* Methods */
10513
10514 /**
10515 * Get the symbolic name of the card.
10516 *
10517 * @return {string} Symbolic name of card
10518 */
10519 OO.ui.CardLayout.prototype.getName = function () {
10520 return this.name;
10521 };
10522
10523 /**
10524 * Check if card is active.
10525 *
10526 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10527 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10528 *
10529 * @return {boolean} Card is active
10530 */
10531 OO.ui.CardLayout.prototype.isActive = function () {
10532 return this.active;
10533 };
10534
10535 /**
10536 * Get tab item.
10537 *
10538 * The tab item allows users to access the card from the index's tab
10539 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10540 *
10541 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10542 */
10543 OO.ui.CardLayout.prototype.getTabItem = function () {
10544 return this.tabItem;
10545 };
10546
10547 /**
10548 * Set or unset the tab item.
10549 *
10550 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10551 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10552 * level), use #setupTabItem instead of this method.
10553 *
10554 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10555 * @chainable
10556 */
10557 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10558 this.tabItem = tabItem || null;
10559 if ( tabItem ) {
10560 this.setupTabItem();
10561 }
10562 return this;
10563 };
10564
10565 /**
10566 * Set up the tab item.
10567 *
10568 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10569 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10570 * the #setTabItem method instead.
10571 *
10572 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10573 * @chainable
10574 */
10575 OO.ui.CardLayout.prototype.setupTabItem = function () {
10576 return this;
10577 };
10578
10579 /**
10580 * Set the card to its 'active' state.
10581 *
10582 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10583 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10584 * context, setting the active state on a card does nothing.
10585 *
10586 * @param {boolean} value Card is active
10587 * @fires active
10588 */
10589 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10590 active = !!active;
10591
10592 if ( active !== this.active ) {
10593 this.active = active;
10594 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10595 this.emit( 'active', this.active );
10596 }
10597 };
10598
10599 /**
10600 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10601 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10602 * rather extended to include the required content and functionality.
10603 *
10604 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10605 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10606 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10607 *
10608 * @class
10609 * @extends OO.ui.PanelLayout
10610 *
10611 * @constructor
10612 * @param {string} name Unique symbolic name of page
10613 * @param {Object} [config] Configuration options
10614 */
10615 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10616 // Allow passing positional parameters inside the config object
10617 if ( OO.isPlainObject( name ) && config === undefined ) {
10618 config = name;
10619 name = config.name;
10620 }
10621
10622 // Configuration initialization
10623 config = $.extend( { scrollable: true }, config );
10624
10625 // Parent constructor
10626 OO.ui.PageLayout.parent.call( this, config );
10627
10628 // Properties
10629 this.name = name;
10630 this.outlineItem = null;
10631 this.active = false;
10632
10633 // Initialization
10634 this.$element.addClass( 'oo-ui-pageLayout' );
10635 };
10636
10637 /* Setup */
10638
10639 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10640
10641 /* Events */
10642
10643 /**
10644 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10645 * shown in a booklet layout that is configured to display only one page at a time.
10646 *
10647 * @event active
10648 * @param {boolean} active Page is active
10649 */
10650
10651 /* Methods */
10652
10653 /**
10654 * Get the symbolic name of the page.
10655 *
10656 * @return {string} Symbolic name of page
10657 */
10658 OO.ui.PageLayout.prototype.getName = function () {
10659 return this.name;
10660 };
10661
10662 /**
10663 * Check if page is active.
10664 *
10665 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10666 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10667 *
10668 * @return {boolean} Page is active
10669 */
10670 OO.ui.PageLayout.prototype.isActive = function () {
10671 return this.active;
10672 };
10673
10674 /**
10675 * Get outline item.
10676 *
10677 * The outline item allows users to access the page from the booklet's outline
10678 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10679 *
10680 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10681 */
10682 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10683 return this.outlineItem;
10684 };
10685
10686 /**
10687 * Set or unset the outline item.
10688 *
10689 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10690 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10691 * level), use #setupOutlineItem instead of this method.
10692 *
10693 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10694 * @chainable
10695 */
10696 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10697 this.outlineItem = outlineItem || null;
10698 if ( outlineItem ) {
10699 this.setupOutlineItem();
10700 }
10701 return this;
10702 };
10703
10704 /**
10705 * Set up the outline item.
10706 *
10707 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10708 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10709 * the #setOutlineItem method instead.
10710 *
10711 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10712 * @chainable
10713 */
10714 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10715 return this;
10716 };
10717
10718 /**
10719 * Set the page to its 'active' state.
10720 *
10721 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10722 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10723 * context, setting the active state on a page does nothing.
10724 *
10725 * @param {boolean} value Page is active
10726 * @fires active
10727 */
10728 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10729 active = !!active;
10730
10731 if ( active !== this.active ) {
10732 this.active = active;
10733 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10734 this.emit( 'active', this.active );
10735 }
10736 };
10737
10738 /**
10739 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10740 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10741 * by setting the #continuous option to 'true'.
10742 *
10743 * @example
10744 * // A stack layout with two panels, configured to be displayed continously
10745 * var myStack = new OO.ui.StackLayout( {
10746 * items: [
10747 * new OO.ui.PanelLayout( {
10748 * $content: $( '<p>Panel One</p>' ),
10749 * padded: true,
10750 * framed: true
10751 * } ),
10752 * new OO.ui.PanelLayout( {
10753 * $content: $( '<p>Panel Two</p>' ),
10754 * padded: true,
10755 * framed: true
10756 * } )
10757 * ],
10758 * continuous: true
10759 * } );
10760 * $( 'body' ).append( myStack.$element );
10761 *
10762 * @class
10763 * @extends OO.ui.PanelLayout
10764 * @mixins OO.ui.mixin.GroupElement
10765 *
10766 * @constructor
10767 * @param {Object} [config] Configuration options
10768 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10769 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10770 */
10771 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10772 // Configuration initialization
10773 config = $.extend( { scrollable: true }, config );
10774
10775 // Parent constructor
10776 OO.ui.StackLayout.parent.call( this, config );
10777
10778 // Mixin constructors
10779 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10780
10781 // Properties
10782 this.currentItem = null;
10783 this.continuous = !!config.continuous;
10784
10785 // Initialization
10786 this.$element.addClass( 'oo-ui-stackLayout' );
10787 if ( this.continuous ) {
10788 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10789 }
10790 if ( Array.isArray( config.items ) ) {
10791 this.addItems( config.items );
10792 }
10793 };
10794
10795 /* Setup */
10796
10797 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10798 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
10799
10800 /* Events */
10801
10802 /**
10803 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10804 * {@link #clearItems cleared} or {@link #setItem displayed}.
10805 *
10806 * @event set
10807 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10808 */
10809
10810 /* Methods */
10811
10812 /**
10813 * Get the current panel.
10814 *
10815 * @return {OO.ui.Layout|null}
10816 */
10817 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10818 return this.currentItem;
10819 };
10820
10821 /**
10822 * Unset the current item.
10823 *
10824 * @private
10825 * @param {OO.ui.StackLayout} layout
10826 * @fires set
10827 */
10828 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10829 var prevItem = this.currentItem;
10830 if ( prevItem === null ) {
10831 return;
10832 }
10833
10834 this.currentItem = null;
10835 this.emit( 'set', null );
10836 };
10837
10838 /**
10839 * Add panel layouts to the stack layout.
10840 *
10841 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10842 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10843 * by the index.
10844 *
10845 * @param {OO.ui.Layout[]} items Panels to add
10846 * @param {number} [index] Index of the insertion point
10847 * @chainable
10848 */
10849 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10850 // Update the visibility
10851 this.updateHiddenState( items, this.currentItem );
10852
10853 // Mixin method
10854 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
10855
10856 if ( !this.currentItem && items.length ) {
10857 this.setItem( items[ 0 ] );
10858 }
10859
10860 return this;
10861 };
10862
10863 /**
10864 * Remove the specified panels from the stack layout.
10865 *
10866 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10867 * you may wish to use the #clearItems method instead.
10868 *
10869 * @param {OO.ui.Layout[]} items Panels to remove
10870 * @chainable
10871 * @fires set
10872 */
10873 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10874 // Mixin method
10875 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
10876
10877 if ( items.indexOf( this.currentItem ) !== -1 ) {
10878 if ( this.items.length ) {
10879 this.setItem( this.items[ 0 ] );
10880 } else {
10881 this.unsetCurrentItem();
10882 }
10883 }
10884
10885 return this;
10886 };
10887
10888 /**
10889 * Clear all panels from the stack layout.
10890 *
10891 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10892 * a subset of panels, use the #removeItems method.
10893 *
10894 * @chainable
10895 * @fires set
10896 */
10897 OO.ui.StackLayout.prototype.clearItems = function () {
10898 this.unsetCurrentItem();
10899 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
10900
10901 return this;
10902 };
10903
10904 /**
10905 * Show the specified panel.
10906 *
10907 * If another panel is currently displayed, it will be hidden.
10908 *
10909 * @param {OO.ui.Layout} item Panel to show
10910 * @chainable
10911 * @fires set
10912 */
10913 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10914 if ( item !== this.currentItem ) {
10915 this.updateHiddenState( this.items, item );
10916
10917 if ( this.items.indexOf( item ) !== -1 ) {
10918 this.currentItem = item;
10919 this.emit( 'set', item );
10920 } else {
10921 this.unsetCurrentItem();
10922 }
10923 }
10924
10925 return this;
10926 };
10927
10928 /**
10929 * Update the visibility of all items in case of non-continuous view.
10930 *
10931 * Ensure all items are hidden except for the selected one.
10932 * This method does nothing when the stack is continuous.
10933 *
10934 * @private
10935 * @param {OO.ui.Layout[]} items Item list iterate over
10936 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10937 */
10938 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10939 var i, len;
10940
10941 if ( !this.continuous ) {
10942 for ( i = 0, len = items.length; i < len; i++ ) {
10943 if ( !selectedItem || selectedItem !== items[ i ] ) {
10944 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10945 }
10946 }
10947 if ( selectedItem ) {
10948 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10949 }
10950 }
10951 };
10952
10953 /**
10954 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10955 * items), with small margins between them. Convenient when you need to put a number of block-level
10956 * widgets on a single line next to each other.
10957 *
10958 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10959 *
10960 * @example
10961 * // HorizontalLayout with a text input and a label
10962 * var layout = new OO.ui.HorizontalLayout( {
10963 * items: [
10964 * new OO.ui.LabelWidget( { label: 'Label' } ),
10965 * new OO.ui.TextInputWidget( { value: 'Text' } )
10966 * ]
10967 * } );
10968 * $( 'body' ).append( layout.$element );
10969 *
10970 * @class
10971 * @extends OO.ui.Layout
10972 * @mixins OO.ui.mixin.GroupElement
10973 *
10974 * @constructor
10975 * @param {Object} [config] Configuration options
10976 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10977 */
10978 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
10979 // Configuration initialization
10980 config = config || {};
10981
10982 // Parent constructor
10983 OO.ui.HorizontalLayout.parent.call( this, config );
10984
10985 // Mixin constructors
10986 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10987
10988 // Initialization
10989 this.$element.addClass( 'oo-ui-horizontalLayout' );
10990 if ( Array.isArray( config.items ) ) {
10991 this.addItems( config.items );
10992 }
10993 };
10994
10995 /* Setup */
10996
10997 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
10998 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
10999
11000 /**
11001 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11002 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11003 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11004 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11005 * the tool.
11006 *
11007 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11008 * set up.
11009 *
11010 * @example
11011 * // Example of a BarToolGroup with two tools
11012 * var toolFactory = new OO.ui.ToolFactory();
11013 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11014 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11015 *
11016 * // We will be placing status text in this element when tools are used
11017 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11018 *
11019 * // Define the tools that we're going to place in our toolbar
11020 *
11021 * // Create a class inheriting from OO.ui.Tool
11022 * function PictureTool() {
11023 * PictureTool.parent.apply( this, arguments );
11024 * }
11025 * OO.inheritClass( PictureTool, OO.ui.Tool );
11026 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11027 * // of 'icon' and 'title' (displayed icon and text).
11028 * PictureTool.static.name = 'picture';
11029 * PictureTool.static.icon = 'picture';
11030 * PictureTool.static.title = 'Insert picture';
11031 * // Defines the action that will happen when this tool is selected (clicked).
11032 * PictureTool.prototype.onSelect = function () {
11033 * $area.text( 'Picture tool clicked!' );
11034 * // Never display this tool as "active" (selected).
11035 * this.setActive( false );
11036 * };
11037 * // Make this tool available in our toolFactory and thus our toolbar
11038 * toolFactory.register( PictureTool );
11039 *
11040 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11041 * // little popup window (a PopupWidget).
11042 * function HelpTool( toolGroup, config ) {
11043 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11044 * padded: true,
11045 * label: 'Help',
11046 * head: true
11047 * } }, config ) );
11048 * this.popup.$body.append( '<p>I am helpful!</p>' );
11049 * }
11050 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11051 * HelpTool.static.name = 'help';
11052 * HelpTool.static.icon = 'help';
11053 * HelpTool.static.title = 'Help';
11054 * toolFactory.register( HelpTool );
11055 *
11056 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11057 * // used once (but not all defined tools must be used).
11058 * toolbar.setup( [
11059 * {
11060 * // 'bar' tool groups display tools by icon only
11061 * type: 'bar',
11062 * include: [ 'picture', 'help' ]
11063 * }
11064 * ] );
11065 *
11066 * // Create some UI around the toolbar and place it in the document
11067 * var frame = new OO.ui.PanelLayout( {
11068 * expanded: false,
11069 * framed: true
11070 * } );
11071 * var contentFrame = new OO.ui.PanelLayout( {
11072 * expanded: false,
11073 * padded: true
11074 * } );
11075 * frame.$element.append(
11076 * toolbar.$element,
11077 * contentFrame.$element.append( $area )
11078 * );
11079 * $( 'body' ).append( frame.$element );
11080 *
11081 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11082 * // document.
11083 * toolbar.initialize();
11084 *
11085 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11086 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11087 *
11088 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11089 *
11090 * @class
11091 * @extends OO.ui.ToolGroup
11092 *
11093 * @constructor
11094 * @param {OO.ui.Toolbar} toolbar
11095 * @param {Object} [config] Configuration options
11096 */
11097 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11098 // Allow passing positional parameters inside the config object
11099 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11100 config = toolbar;
11101 toolbar = config.toolbar;
11102 }
11103
11104 // Parent constructor
11105 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11106
11107 // Initialization
11108 this.$element.addClass( 'oo-ui-barToolGroup' );
11109 };
11110
11111 /* Setup */
11112
11113 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11114
11115 /* Static Properties */
11116
11117 OO.ui.BarToolGroup.static.titleTooltips = true;
11118
11119 OO.ui.BarToolGroup.static.accelTooltips = true;
11120
11121 OO.ui.BarToolGroup.static.name = 'bar';
11122
11123 /**
11124 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11125 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11126 * optional icon and label. This class can be used for other base classes that also use this functionality.
11127 *
11128 * @abstract
11129 * @class
11130 * @extends OO.ui.ToolGroup
11131 * @mixins OO.ui.mixin.IconElement
11132 * @mixins OO.ui.mixin.IndicatorElement
11133 * @mixins OO.ui.mixin.LabelElement
11134 * @mixins OO.ui.mixin.TitledElement
11135 * @mixins OO.ui.mixin.ClippableElement
11136 * @mixins OO.ui.mixin.TabIndexedElement
11137 *
11138 * @constructor
11139 * @param {OO.ui.Toolbar} toolbar
11140 * @param {Object} [config] Configuration options
11141 * @cfg {string} [header] Text to display at the top of the popup
11142 */
11143 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11144 // Allow passing positional parameters inside the config object
11145 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11146 config = toolbar;
11147 toolbar = config.toolbar;
11148 }
11149
11150 // Configuration initialization
11151 config = config || {};
11152
11153 // Parent constructor
11154 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11155
11156 // Properties
11157 this.active = false;
11158 this.dragging = false;
11159 this.onBlurHandler = this.onBlur.bind( this );
11160 this.$handle = $( '<span>' );
11161
11162 // Mixin constructors
11163 OO.ui.mixin.IconElement.call( this, config );
11164 OO.ui.mixin.IndicatorElement.call( this, config );
11165 OO.ui.mixin.LabelElement.call( this, config );
11166 OO.ui.mixin.TitledElement.call( this, config );
11167 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11168 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11169
11170 // Events
11171 this.$handle.on( {
11172 keydown: this.onHandleMouseKeyDown.bind( this ),
11173 keyup: this.onHandleMouseKeyUp.bind( this ),
11174 mousedown: this.onHandleMouseKeyDown.bind( this ),
11175 mouseup: this.onHandleMouseKeyUp.bind( this )
11176 } );
11177
11178 // Initialization
11179 this.$handle
11180 .addClass( 'oo-ui-popupToolGroup-handle' )
11181 .append( this.$icon, this.$label, this.$indicator );
11182 // If the pop-up should have a header, add it to the top of the toolGroup.
11183 // Note: If this feature is useful for other widgets, we could abstract it into an
11184 // OO.ui.HeaderedElement mixin constructor.
11185 if ( config.header !== undefined ) {
11186 this.$group
11187 .prepend( $( '<span>' )
11188 .addClass( 'oo-ui-popupToolGroup-header' )
11189 .text( config.header )
11190 );
11191 }
11192 this.$element
11193 .addClass( 'oo-ui-popupToolGroup' )
11194 .prepend( this.$handle );
11195 };
11196
11197 /* Setup */
11198
11199 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11200 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11201 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11202 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11203 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11204 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11205 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11206
11207 /* Methods */
11208
11209 /**
11210 * @inheritdoc
11211 */
11212 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11213 // Parent method
11214 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11215
11216 if ( this.isDisabled() && this.isElementAttached() ) {
11217 this.setActive( false );
11218 }
11219 };
11220
11221 /**
11222 * Handle focus being lost.
11223 *
11224 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11225 *
11226 * @protected
11227 * @param {jQuery.Event} e Mouse up or key up event
11228 */
11229 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11230 // Only deactivate when clicking outside the dropdown element
11231 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11232 this.setActive( false );
11233 }
11234 };
11235
11236 /**
11237 * @inheritdoc
11238 */
11239 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11240 // Only close toolgroup when a tool was actually selected
11241 if (
11242 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11243 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11244 ) {
11245 this.setActive( false );
11246 }
11247 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11248 };
11249
11250 /**
11251 * Handle mouse up and key up events.
11252 *
11253 * @protected
11254 * @param {jQuery.Event} e Mouse up or key up event
11255 */
11256 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11257 if (
11258 !this.isDisabled() &&
11259 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11260 ) {
11261 return false;
11262 }
11263 };
11264
11265 /**
11266 * Handle mouse down and key down events.
11267 *
11268 * @protected
11269 * @param {jQuery.Event} e Mouse down or key down event
11270 */
11271 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11272 if (
11273 !this.isDisabled() &&
11274 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11275 ) {
11276 this.setActive( !this.active );
11277 return false;
11278 }
11279 };
11280
11281 /**
11282 * Switch into 'active' mode.
11283 *
11284 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11285 * deactivation.
11286 */
11287 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11288 var containerWidth, containerLeft;
11289 value = !!value;
11290 if ( this.active !== value ) {
11291 this.active = value;
11292 if ( value ) {
11293 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11294 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11295
11296 this.$clippable.css( 'left', '' );
11297 // Try anchoring the popup to the left first
11298 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11299 this.toggleClipping( true );
11300 if ( this.isClippedHorizontally() ) {
11301 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11302 this.toggleClipping( false );
11303 this.$element
11304 .removeClass( 'oo-ui-popupToolGroup-left' )
11305 .addClass( 'oo-ui-popupToolGroup-right' );
11306 this.toggleClipping( true );
11307 }
11308 if ( this.isClippedHorizontally() ) {
11309 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11310 containerWidth = this.$clippableContainer.width();
11311 containerLeft = this.$clippableContainer.offset().left;
11312
11313 this.toggleClipping( false );
11314 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11315
11316 this.$clippable.css( {
11317 left: -( this.$element.offset().left - containerLeft ),
11318 width: containerWidth
11319 } );
11320 }
11321 } else {
11322 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11323 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11324 this.$element.removeClass(
11325 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11326 );
11327 this.toggleClipping( false );
11328 }
11329 }
11330 };
11331
11332 /**
11333 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11334 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11335 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11336 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11337 * with a label, icon, indicator, header, and title.
11338 *
11339 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11340 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11341 * users to collapse the list again.
11342 *
11343 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11344 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11345 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11346 *
11347 * @example
11348 * // Example of a ListToolGroup
11349 * var toolFactory = new OO.ui.ToolFactory();
11350 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11351 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11352 *
11353 * // Configure and register two tools
11354 * function SettingsTool() {
11355 * SettingsTool.parent.apply( this, arguments );
11356 * }
11357 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11358 * SettingsTool.static.name = 'settings';
11359 * SettingsTool.static.icon = 'settings';
11360 * SettingsTool.static.title = 'Change settings';
11361 * SettingsTool.prototype.onSelect = function () {
11362 * this.setActive( false );
11363 * };
11364 * toolFactory.register( SettingsTool );
11365 * // Register two more tools, nothing interesting here
11366 * function StuffTool() {
11367 * StuffTool.parent.apply( this, arguments );
11368 * }
11369 * OO.inheritClass( StuffTool, OO.ui.Tool );
11370 * StuffTool.static.name = 'stuff';
11371 * StuffTool.static.icon = 'ellipsis';
11372 * StuffTool.static.title = 'Change the world';
11373 * StuffTool.prototype.onSelect = function () {
11374 * this.setActive( false );
11375 * };
11376 * toolFactory.register( StuffTool );
11377 * toolbar.setup( [
11378 * {
11379 * // Configurations for list toolgroup.
11380 * type: 'list',
11381 * label: 'ListToolGroup',
11382 * indicator: 'down',
11383 * icon: 'picture',
11384 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11385 * header: 'This is the header',
11386 * include: [ 'settings', 'stuff' ],
11387 * allowCollapse: ['stuff']
11388 * }
11389 * ] );
11390 *
11391 * // Create some UI around the toolbar and place it in the document
11392 * var frame = new OO.ui.PanelLayout( {
11393 * expanded: false,
11394 * framed: true
11395 * } );
11396 * frame.$element.append(
11397 * toolbar.$element
11398 * );
11399 * $( 'body' ).append( frame.$element );
11400 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11401 * toolbar.initialize();
11402 *
11403 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11404 *
11405 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11406 *
11407 * @class
11408 * @extends OO.ui.PopupToolGroup
11409 *
11410 * @constructor
11411 * @param {OO.ui.Toolbar} toolbar
11412 * @param {Object} [config] Configuration options
11413 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11414 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11415 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11416 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11417 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11418 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11419 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11420 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11421 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11422 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11423 */
11424 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11425 // Allow passing positional parameters inside the config object
11426 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11427 config = toolbar;
11428 toolbar = config.toolbar;
11429 }
11430
11431 // Configuration initialization
11432 config = config || {};
11433
11434 // Properties (must be set before parent constructor, which calls #populate)
11435 this.allowCollapse = config.allowCollapse;
11436 this.forceExpand = config.forceExpand;
11437 this.expanded = config.expanded !== undefined ? config.expanded : false;
11438 this.collapsibleTools = [];
11439
11440 // Parent constructor
11441 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11442
11443 // Initialization
11444 this.$element.addClass( 'oo-ui-listToolGroup' );
11445 };
11446
11447 /* Setup */
11448
11449 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11450
11451 /* Static Properties */
11452
11453 OO.ui.ListToolGroup.static.name = 'list';
11454
11455 /* Methods */
11456
11457 /**
11458 * @inheritdoc
11459 */
11460 OO.ui.ListToolGroup.prototype.populate = function () {
11461 var i, len, allowCollapse = [];
11462
11463 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11464
11465 // Update the list of collapsible tools
11466 if ( this.allowCollapse !== undefined ) {
11467 allowCollapse = this.allowCollapse;
11468 } else if ( this.forceExpand !== undefined ) {
11469 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11470 }
11471
11472 this.collapsibleTools = [];
11473 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11474 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11475 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11476 }
11477 }
11478
11479 // Keep at the end, even when tools are added
11480 this.$group.append( this.getExpandCollapseTool().$element );
11481
11482 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11483 this.updateCollapsibleState();
11484 };
11485
11486 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11487 var ExpandCollapseTool;
11488 if ( this.expandCollapseTool === undefined ) {
11489 ExpandCollapseTool = function () {
11490 ExpandCollapseTool.parent.apply( this, arguments );
11491 };
11492
11493 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11494
11495 ExpandCollapseTool.prototype.onSelect = function () {
11496 this.toolGroup.expanded = !this.toolGroup.expanded;
11497 this.toolGroup.updateCollapsibleState();
11498 this.setActive( false );
11499 };
11500 ExpandCollapseTool.prototype.onUpdateState = function () {
11501 // Do nothing. Tool interface requires an implementation of this function.
11502 };
11503
11504 ExpandCollapseTool.static.name = 'more-fewer';
11505
11506 this.expandCollapseTool = new ExpandCollapseTool( this );
11507 }
11508 return this.expandCollapseTool;
11509 };
11510
11511 /**
11512 * @inheritdoc
11513 */
11514 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11515 // Do not close the popup when the user wants to show more/fewer tools
11516 if (
11517 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11518 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11519 ) {
11520 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11521 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11522 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11523 } else {
11524 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11525 }
11526 };
11527
11528 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11529 var i, len;
11530
11531 this.getExpandCollapseTool()
11532 .setIcon( this.expanded ? 'collapse' : 'expand' )
11533 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11534
11535 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11536 this.collapsibleTools[ i ].toggle( this.expanded );
11537 }
11538 };
11539
11540 /**
11541 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11542 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11543 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11544 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11545 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11546 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11547 *
11548 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11549 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11550 * a MenuToolGroup is used.
11551 *
11552 * @example
11553 * // Example of a MenuToolGroup
11554 * var toolFactory = new OO.ui.ToolFactory();
11555 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11556 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11557 *
11558 * // We will be placing status text in this element when tools are used
11559 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11560 *
11561 * // Define the tools that we're going to place in our toolbar
11562 *
11563 * function SettingsTool() {
11564 * SettingsTool.parent.apply( this, arguments );
11565 * this.reallyActive = false;
11566 * }
11567 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11568 * SettingsTool.static.name = 'settings';
11569 * SettingsTool.static.icon = 'settings';
11570 * SettingsTool.static.title = 'Change settings';
11571 * SettingsTool.prototype.onSelect = function () {
11572 * $area.text( 'Settings tool clicked!' );
11573 * // Toggle the active state on each click
11574 * this.reallyActive = !this.reallyActive;
11575 * this.setActive( this.reallyActive );
11576 * // To update the menu label
11577 * this.toolbar.emit( 'updateState' );
11578 * };
11579 * SettingsTool.prototype.onUpdateState = function () {
11580 * };
11581 * toolFactory.register( SettingsTool );
11582 *
11583 * function StuffTool() {
11584 * StuffTool.parent.apply( this, arguments );
11585 * this.reallyActive = false;
11586 * }
11587 * OO.inheritClass( StuffTool, OO.ui.Tool );
11588 * StuffTool.static.name = 'stuff';
11589 * StuffTool.static.icon = 'ellipsis';
11590 * StuffTool.static.title = 'More stuff';
11591 * StuffTool.prototype.onSelect = function () {
11592 * $area.text( 'More stuff tool clicked!' );
11593 * // Toggle the active state on each click
11594 * this.reallyActive = !this.reallyActive;
11595 * this.setActive( this.reallyActive );
11596 * // To update the menu label
11597 * this.toolbar.emit( 'updateState' );
11598 * };
11599 * StuffTool.prototype.onUpdateState = function () {
11600 * };
11601 * toolFactory.register( StuffTool );
11602 *
11603 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11604 * // used once (but not all defined tools must be used).
11605 * toolbar.setup( [
11606 * {
11607 * type: 'menu',
11608 * header: 'This is the (optional) header',
11609 * title: 'This is the (optional) title',
11610 * indicator: 'down',
11611 * include: [ 'settings', 'stuff' ]
11612 * }
11613 * ] );
11614 *
11615 * // Create some UI around the toolbar and place it in the document
11616 * var frame = new OO.ui.PanelLayout( {
11617 * expanded: false,
11618 * framed: true
11619 * } );
11620 * var contentFrame = new OO.ui.PanelLayout( {
11621 * expanded: false,
11622 * padded: true
11623 * } );
11624 * frame.$element.append(
11625 * toolbar.$element,
11626 * contentFrame.$element.append( $area )
11627 * );
11628 * $( 'body' ).append( frame.$element );
11629 *
11630 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11631 * // document.
11632 * toolbar.initialize();
11633 * toolbar.emit( 'updateState' );
11634 *
11635 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11636 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11637 *
11638 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11639 *
11640 * @class
11641 * @extends OO.ui.PopupToolGroup
11642 *
11643 * @constructor
11644 * @param {OO.ui.Toolbar} toolbar
11645 * @param {Object} [config] Configuration options
11646 */
11647 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11648 // Allow passing positional parameters inside the config object
11649 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11650 config = toolbar;
11651 toolbar = config.toolbar;
11652 }
11653
11654 // Configuration initialization
11655 config = config || {};
11656
11657 // Parent constructor
11658 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11659
11660 // Events
11661 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11662
11663 // Initialization
11664 this.$element.addClass( 'oo-ui-menuToolGroup' );
11665 };
11666
11667 /* Setup */
11668
11669 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11670
11671 /* Static Properties */
11672
11673 OO.ui.MenuToolGroup.static.name = 'menu';
11674
11675 /* Methods */
11676
11677 /**
11678 * Handle the toolbar state being updated.
11679 *
11680 * When the state changes, the title of each active item in the menu will be joined together and
11681 * used as a label for the group. The label will be empty if none of the items are active.
11682 *
11683 * @private
11684 */
11685 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11686 var name,
11687 labelTexts = [];
11688
11689 for ( name in this.tools ) {
11690 if ( this.tools[ name ].isActive() ) {
11691 labelTexts.push( this.tools[ name ].getTitle() );
11692 }
11693 }
11694
11695 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11696 };
11697
11698 /**
11699 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11700 * 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
11701 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11702 *
11703 * // Example of a popup tool. When selected, a popup tool displays
11704 * // a popup window.
11705 * function HelpTool( toolGroup, config ) {
11706 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11707 * padded: true,
11708 * label: 'Help',
11709 * head: true
11710 * } }, config ) );
11711 * this.popup.$body.append( '<p>I am helpful!</p>' );
11712 * };
11713 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11714 * HelpTool.static.name = 'help';
11715 * HelpTool.static.icon = 'help';
11716 * HelpTool.static.title = 'Help';
11717 * toolFactory.register( HelpTool );
11718 *
11719 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11720 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11721 *
11722 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11723 *
11724 * @abstract
11725 * @class
11726 * @extends OO.ui.Tool
11727 * @mixins OO.ui.mixin.PopupElement
11728 *
11729 * @constructor
11730 * @param {OO.ui.ToolGroup} toolGroup
11731 * @param {Object} [config] Configuration options
11732 */
11733 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11734 // Allow passing positional parameters inside the config object
11735 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11736 config = toolGroup;
11737 toolGroup = config.toolGroup;
11738 }
11739
11740 // Parent constructor
11741 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11742
11743 // Mixin constructors
11744 OO.ui.mixin.PopupElement.call( this, config );
11745
11746 // Initialization
11747 this.$element
11748 .addClass( 'oo-ui-popupTool' )
11749 .append( this.popup.$element );
11750 };
11751
11752 /* Setup */
11753
11754 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11755 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11756
11757 /* Methods */
11758
11759 /**
11760 * Handle the tool being selected.
11761 *
11762 * @inheritdoc
11763 */
11764 OO.ui.PopupTool.prototype.onSelect = function () {
11765 if ( !this.isDisabled() ) {
11766 this.popup.toggle();
11767 }
11768 this.setActive( false );
11769 return false;
11770 };
11771
11772 /**
11773 * Handle the toolbar state being updated.
11774 *
11775 * @inheritdoc
11776 */
11777 OO.ui.PopupTool.prototype.onUpdateState = function () {
11778 this.setActive( false );
11779 };
11780
11781 /**
11782 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11783 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11784 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11785 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11786 * when the ToolGroupTool is selected.
11787 *
11788 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11789 *
11790 * function SettingsTool() {
11791 * SettingsTool.parent.apply( this, arguments );
11792 * };
11793 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11794 * SettingsTool.static.name = 'settings';
11795 * SettingsTool.static.title = 'Change settings';
11796 * SettingsTool.static.groupConfig = {
11797 * icon: 'settings',
11798 * label: 'ToolGroupTool',
11799 * include: [ 'setting1', 'setting2' ]
11800 * };
11801 * toolFactory.register( SettingsTool );
11802 *
11803 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11804 *
11805 * Please note that this implementation is subject to change per [T74159] [2].
11806 *
11807 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11808 * [2]: https://phabricator.wikimedia.org/T74159
11809 *
11810 * @abstract
11811 * @class
11812 * @extends OO.ui.Tool
11813 *
11814 * @constructor
11815 * @param {OO.ui.ToolGroup} toolGroup
11816 * @param {Object} [config] Configuration options
11817 */
11818 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
11819 // Allow passing positional parameters inside the config object
11820 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11821 config = toolGroup;
11822 toolGroup = config.toolGroup;
11823 }
11824
11825 // Parent constructor
11826 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
11827
11828 // Properties
11829 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
11830
11831 // Events
11832 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
11833
11834 // Initialization
11835 this.$link.remove();
11836 this.$element
11837 .addClass( 'oo-ui-toolGroupTool' )
11838 .append( this.innerToolGroup.$element );
11839 };
11840
11841 /* Setup */
11842
11843 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
11844
11845 /* Static Properties */
11846
11847 /**
11848 * Toolgroup configuration.
11849 *
11850 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11851 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11852 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11853 *
11854 * @property {Object.<string,Array>}
11855 */
11856 OO.ui.ToolGroupTool.static.groupConfig = {};
11857
11858 /* Methods */
11859
11860 /**
11861 * Handle the tool being selected.
11862 *
11863 * @inheritdoc
11864 */
11865 OO.ui.ToolGroupTool.prototype.onSelect = function () {
11866 this.innerToolGroup.setActive( !this.innerToolGroup.active );
11867 return false;
11868 };
11869
11870 /**
11871 * Synchronize disabledness state of the tool with the inner toolgroup.
11872 *
11873 * @private
11874 * @param {boolean} disabled Element is disabled
11875 */
11876 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
11877 this.setDisabled( disabled );
11878 };
11879
11880 /**
11881 * Handle the toolbar state being updated.
11882 *
11883 * @inheritdoc
11884 */
11885 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
11886 this.setActive( false );
11887 };
11888
11889 /**
11890 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11891 *
11892 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11893 * more information.
11894 * @return {OO.ui.ListToolGroup}
11895 */
11896 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
11897 if ( group.include === '*' ) {
11898 // Apply defaults to catch-all groups
11899 if ( group.label === undefined ) {
11900 group.label = OO.ui.msg( 'ooui-toolbar-more' );
11901 }
11902 }
11903
11904 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
11905 };
11906
11907 /**
11908 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11909 *
11910 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11911 *
11912 * @private
11913 * @abstract
11914 * @class
11915 * @extends OO.ui.mixin.GroupElement
11916 *
11917 * @constructor
11918 * @param {Object} [config] Configuration options
11919 */
11920 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
11921 // Parent constructor
11922 OO.ui.mixin.GroupWidget.parent.call( this, config );
11923 };
11924
11925 /* Setup */
11926
11927 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
11928
11929 /* Methods */
11930
11931 /**
11932 * Set the disabled state of the widget.
11933 *
11934 * This will also update the disabled state of child widgets.
11935 *
11936 * @param {boolean} disabled Disable widget
11937 * @chainable
11938 */
11939 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
11940 var i, len;
11941
11942 // Parent method
11943 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11944 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
11945
11946 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11947 if ( this.items ) {
11948 for ( i = 0, len = this.items.length; i < len; i++ ) {
11949 this.items[ i ].updateDisabled();
11950 }
11951 }
11952
11953 return this;
11954 };
11955
11956 /**
11957 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11958 *
11959 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11960 * allows bidirectional communication.
11961 *
11962 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11963 *
11964 * @private
11965 * @abstract
11966 * @class
11967 *
11968 * @constructor
11969 */
11970 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
11971 //
11972 };
11973
11974 /* Methods */
11975
11976 /**
11977 * Check if widget is disabled.
11978 *
11979 * Checks parent if present, making disabled state inheritable.
11980 *
11981 * @return {boolean} Widget is disabled
11982 */
11983 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
11984 return this.disabled ||
11985 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
11986 };
11987
11988 /**
11989 * Set group element is in.
11990 *
11991 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11992 * @chainable
11993 */
11994 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
11995 // Parent method
11996 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11997 OO.ui.Element.prototype.setElementGroup.call( this, group );
11998
11999 // Initialize item disabled states
12000 this.updateDisabled();
12001
12002 return this;
12003 };
12004
12005 /**
12006 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12007 * Controls include moving items up and down, removing items, and adding different kinds of items.
12008 *
12009 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12010 *
12011 * @class
12012 * @extends OO.ui.Widget
12013 * @mixins OO.ui.mixin.GroupElement
12014 * @mixins OO.ui.mixin.IconElement
12015 *
12016 * @constructor
12017 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12018 * @param {Object} [config] Configuration options
12019 * @cfg {Object} [abilities] List of abilties
12020 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12021 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12022 */
12023 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12024 // Allow passing positional parameters inside the config object
12025 if ( OO.isPlainObject( outline ) && config === undefined ) {
12026 config = outline;
12027 outline = config.outline;
12028 }
12029
12030 // Configuration initialization
12031 config = $.extend( { icon: 'add' }, config );
12032
12033 // Parent constructor
12034 OO.ui.OutlineControlsWidget.parent.call( this, config );
12035
12036 // Mixin constructors
12037 OO.ui.mixin.GroupElement.call( this, config );
12038 OO.ui.mixin.IconElement.call( this, config );
12039
12040 // Properties
12041 this.outline = outline;
12042 this.$movers = $( '<div>' );
12043 this.upButton = new OO.ui.ButtonWidget( {
12044 framed: false,
12045 icon: 'collapse',
12046 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12047 } );
12048 this.downButton = new OO.ui.ButtonWidget( {
12049 framed: false,
12050 icon: 'expand',
12051 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12052 } );
12053 this.removeButton = new OO.ui.ButtonWidget( {
12054 framed: false,
12055 icon: 'remove',
12056 title: OO.ui.msg( 'ooui-outline-control-remove' )
12057 } );
12058 this.abilities = { move: true, remove: true };
12059
12060 // Events
12061 outline.connect( this, {
12062 select: 'onOutlineChange',
12063 add: 'onOutlineChange',
12064 remove: 'onOutlineChange'
12065 } );
12066 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12067 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12068 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12069
12070 // Initialization
12071 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12072 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12073 this.$movers
12074 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12075 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12076 this.$element.append( this.$icon, this.$group, this.$movers );
12077 this.setAbilities( config.abilities || {} );
12078 };
12079
12080 /* Setup */
12081
12082 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12083 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12084 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12085
12086 /* Events */
12087
12088 /**
12089 * @event move
12090 * @param {number} places Number of places to move
12091 */
12092
12093 /**
12094 * @event remove
12095 */
12096
12097 /* Methods */
12098
12099 /**
12100 * Set abilities.
12101 *
12102 * @param {Object} abilities List of abilties
12103 * @param {boolean} [abilities.move] Allow moving movable items
12104 * @param {boolean} [abilities.remove] Allow removing removable items
12105 */
12106 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12107 var ability;
12108
12109 for ( ability in this.abilities ) {
12110 if ( abilities[ ability ] !== undefined ) {
12111 this.abilities[ ability ] = !!abilities[ ability ];
12112 }
12113 }
12114
12115 this.onOutlineChange();
12116 };
12117
12118 /**
12119 *
12120 * @private
12121 * Handle outline change events.
12122 */
12123 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12124 var i, len, firstMovable, lastMovable,
12125 items = this.outline.getItems(),
12126 selectedItem = this.outline.getSelectedItem(),
12127 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12128 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12129
12130 if ( movable ) {
12131 i = -1;
12132 len = items.length;
12133 while ( ++i < len ) {
12134 if ( items[ i ].isMovable() ) {
12135 firstMovable = items[ i ];
12136 break;
12137 }
12138 }
12139 i = len;
12140 while ( i-- ) {
12141 if ( items[ i ].isMovable() ) {
12142 lastMovable = items[ i ];
12143 break;
12144 }
12145 }
12146 }
12147 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12148 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12149 this.removeButton.setDisabled( !removable );
12150 };
12151
12152 /**
12153 * ToggleWidget implements basic behavior of widgets with an on/off state.
12154 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12155 *
12156 * @abstract
12157 * @class
12158 * @extends OO.ui.Widget
12159 *
12160 * @constructor
12161 * @param {Object} [config] Configuration options
12162 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12163 * By default, the toggle is in the 'off' state.
12164 */
12165 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12166 // Configuration initialization
12167 config = config || {};
12168
12169 // Parent constructor
12170 OO.ui.ToggleWidget.parent.call( this, config );
12171
12172 // Properties
12173 this.value = null;
12174
12175 // Initialization
12176 this.$element.addClass( 'oo-ui-toggleWidget' );
12177 this.setValue( !!config.value );
12178 };
12179
12180 /* Setup */
12181
12182 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12183
12184 /* Events */
12185
12186 /**
12187 * @event change
12188 *
12189 * A change event is emitted when the on/off state of the toggle changes.
12190 *
12191 * @param {boolean} value Value representing the new state of the toggle
12192 */
12193
12194 /* Methods */
12195
12196 /**
12197 * Get the value representing the toggle’s state.
12198 *
12199 * @return {boolean} The on/off state of the toggle
12200 */
12201 OO.ui.ToggleWidget.prototype.getValue = function () {
12202 return this.value;
12203 };
12204
12205 /**
12206 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12207 *
12208 * @param {boolean} value The state of the toggle
12209 * @fires change
12210 * @chainable
12211 */
12212 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12213 value = !!value;
12214 if ( this.value !== value ) {
12215 this.value = value;
12216 this.emit( 'change', value );
12217 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12218 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12219 this.$element.attr( 'aria-checked', value.toString() );
12220 }
12221 return this;
12222 };
12223
12224 /**
12225 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12226 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12227 * removed, and cleared from the group.
12228 *
12229 * @example
12230 * // Example: A ButtonGroupWidget with two buttons
12231 * var button1 = new OO.ui.PopupButtonWidget( {
12232 * label: 'Select a category',
12233 * icon: 'menu',
12234 * popup: {
12235 * $content: $( '<p>List of categories...</p>' ),
12236 * padded: true,
12237 * align: 'left'
12238 * }
12239 * } );
12240 * var button2 = new OO.ui.ButtonWidget( {
12241 * label: 'Add item'
12242 * });
12243 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12244 * items: [button1, button2]
12245 * } );
12246 * $( 'body' ).append( buttonGroup.$element );
12247 *
12248 * @class
12249 * @extends OO.ui.Widget
12250 * @mixins OO.ui.mixin.GroupElement
12251 *
12252 * @constructor
12253 * @param {Object} [config] Configuration options
12254 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12255 */
12256 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12257 // Configuration initialization
12258 config = config || {};
12259
12260 // Parent constructor
12261 OO.ui.ButtonGroupWidget.parent.call( this, config );
12262
12263 // Mixin constructors
12264 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12265
12266 // Initialization
12267 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12268 if ( Array.isArray( config.items ) ) {
12269 this.addItems( config.items );
12270 }
12271 };
12272
12273 /* Setup */
12274
12275 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12276 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12277
12278 /**
12279 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12280 * feels, and functionality can be customized via the class’s configuration options
12281 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12282 * and examples.
12283 *
12284 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12285 *
12286 * @example
12287 * // A button widget
12288 * var button = new OO.ui.ButtonWidget( {
12289 * label: 'Button with Icon',
12290 * icon: 'remove',
12291 * iconTitle: 'Remove'
12292 * } );
12293 * $( 'body' ).append( button.$element );
12294 *
12295 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12296 *
12297 * @class
12298 * @extends OO.ui.Widget
12299 * @mixins OO.ui.mixin.ButtonElement
12300 * @mixins OO.ui.mixin.IconElement
12301 * @mixins OO.ui.mixin.IndicatorElement
12302 * @mixins OO.ui.mixin.LabelElement
12303 * @mixins OO.ui.mixin.TitledElement
12304 * @mixins OO.ui.mixin.FlaggedElement
12305 * @mixins OO.ui.mixin.TabIndexedElement
12306 * @mixins OO.ui.mixin.AccessKeyedElement
12307 *
12308 * @constructor
12309 * @param {Object} [config] Configuration options
12310 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12311 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12312 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12313 */
12314 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12315 // Configuration initialization
12316 config = config || {};
12317
12318 // Parent constructor
12319 OO.ui.ButtonWidget.parent.call( this, config );
12320
12321 // Mixin constructors
12322 OO.ui.mixin.ButtonElement.call( this, config );
12323 OO.ui.mixin.IconElement.call( this, config );
12324 OO.ui.mixin.IndicatorElement.call( this, config );
12325 OO.ui.mixin.LabelElement.call( this, config );
12326 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12327 OO.ui.mixin.FlaggedElement.call( this, config );
12328 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12329 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12330
12331 // Properties
12332 this.href = null;
12333 this.target = null;
12334 this.noFollow = false;
12335
12336 // Events
12337 this.connect( this, { disable: 'onDisable' } );
12338
12339 // Initialization
12340 this.$button.append( this.$icon, this.$label, this.$indicator );
12341 this.$element
12342 .addClass( 'oo-ui-buttonWidget' )
12343 .append( this.$button );
12344 this.setHref( config.href );
12345 this.setTarget( config.target );
12346 this.setNoFollow( config.noFollow );
12347 };
12348
12349 /* Setup */
12350
12351 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12352 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12353 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12354 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12355 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12356 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12357 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12358 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12359 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12360
12361 /* Methods */
12362
12363 /**
12364 * @inheritdoc
12365 */
12366 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12367 if ( !this.isDisabled() ) {
12368 // Remove the tab-index while the button is down to prevent the button from stealing focus
12369 this.$button.removeAttr( 'tabindex' );
12370 }
12371
12372 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12373 };
12374
12375 /**
12376 * @inheritdoc
12377 */
12378 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12379 if ( !this.isDisabled() ) {
12380 // Restore the tab-index after the button is up to restore the button's accessibility
12381 this.$button.attr( 'tabindex', this.tabIndex );
12382 }
12383
12384 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12385 };
12386
12387 /**
12388 * Get hyperlink location.
12389 *
12390 * @return {string} Hyperlink location
12391 */
12392 OO.ui.ButtonWidget.prototype.getHref = function () {
12393 return this.href;
12394 };
12395
12396 /**
12397 * Get hyperlink target.
12398 *
12399 * @return {string} Hyperlink target
12400 */
12401 OO.ui.ButtonWidget.prototype.getTarget = function () {
12402 return this.target;
12403 };
12404
12405 /**
12406 * Get search engine traversal hint.
12407 *
12408 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12409 */
12410 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12411 return this.noFollow;
12412 };
12413
12414 /**
12415 * Set hyperlink location.
12416 *
12417 * @param {string|null} href Hyperlink location, null to remove
12418 */
12419 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12420 href = typeof href === 'string' ? href : null;
12421 if ( href !== null ) {
12422 if ( !OO.ui.isSafeUrl( href ) ) {
12423 throw new Error( 'Potentially unsafe href provided: ' + href );
12424 }
12425
12426 }
12427
12428 if ( href !== this.href ) {
12429 this.href = href;
12430 this.updateHref();
12431 }
12432
12433 return this;
12434 };
12435
12436 /**
12437 * Update the `href` attribute, in case of changes to href or
12438 * disabled state.
12439 *
12440 * @private
12441 * @chainable
12442 */
12443 OO.ui.ButtonWidget.prototype.updateHref = function () {
12444 if ( this.href !== null && !this.isDisabled() ) {
12445 this.$button.attr( 'href', this.href );
12446 } else {
12447 this.$button.removeAttr( 'href' );
12448 }
12449
12450 return this;
12451 };
12452
12453 /**
12454 * Handle disable events.
12455 *
12456 * @private
12457 * @param {boolean} disabled Element is disabled
12458 */
12459 OO.ui.ButtonWidget.prototype.onDisable = function () {
12460 this.updateHref();
12461 };
12462
12463 /**
12464 * Set hyperlink target.
12465 *
12466 * @param {string|null} target Hyperlink target, null to remove
12467 */
12468 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12469 target = typeof target === 'string' ? target : null;
12470
12471 if ( target !== this.target ) {
12472 this.target = target;
12473 if ( target !== null ) {
12474 this.$button.attr( 'target', target );
12475 } else {
12476 this.$button.removeAttr( 'target' );
12477 }
12478 }
12479
12480 return this;
12481 };
12482
12483 /**
12484 * Set search engine traversal hint.
12485 *
12486 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12487 */
12488 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12489 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12490
12491 if ( noFollow !== this.noFollow ) {
12492 this.noFollow = noFollow;
12493 if ( noFollow ) {
12494 this.$button.attr( 'rel', 'nofollow' );
12495 } else {
12496 this.$button.removeAttr( 'rel' );
12497 }
12498 }
12499
12500 return this;
12501 };
12502
12503 /**
12504 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12505 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12506 * of the actions.
12507 *
12508 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12509 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12510 * and examples.
12511 *
12512 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12513 *
12514 * @class
12515 * @extends OO.ui.ButtonWidget
12516 * @mixins OO.ui.mixin.PendingElement
12517 *
12518 * @constructor
12519 * @param {Object} [config] Configuration options
12520 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12521 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12522 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12523 * for more information about setting modes.
12524 * @cfg {boolean} [framed=false] Render the action button with a frame
12525 */
12526 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12527 // Configuration initialization
12528 config = $.extend( { framed: false }, config );
12529
12530 // Parent constructor
12531 OO.ui.ActionWidget.parent.call( this, config );
12532
12533 // Mixin constructors
12534 OO.ui.mixin.PendingElement.call( this, config );
12535
12536 // Properties
12537 this.action = config.action || '';
12538 this.modes = config.modes || [];
12539 this.width = 0;
12540 this.height = 0;
12541
12542 // Initialization
12543 this.$element.addClass( 'oo-ui-actionWidget' );
12544 };
12545
12546 /* Setup */
12547
12548 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12549 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12550
12551 /* Events */
12552
12553 /**
12554 * A resize event is emitted when the size of the widget changes.
12555 *
12556 * @event resize
12557 */
12558
12559 /* Methods */
12560
12561 /**
12562 * Check if the action is configured to be available in the specified `mode`.
12563 *
12564 * @param {string} mode Name of mode
12565 * @return {boolean} The action is configured with the mode
12566 */
12567 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12568 return this.modes.indexOf( mode ) !== -1;
12569 };
12570
12571 /**
12572 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12573 *
12574 * @return {string}
12575 */
12576 OO.ui.ActionWidget.prototype.getAction = function () {
12577 return this.action;
12578 };
12579
12580 /**
12581 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12582 *
12583 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12584 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12585 * are hidden.
12586 *
12587 * @return {string[]}
12588 */
12589 OO.ui.ActionWidget.prototype.getModes = function () {
12590 return this.modes.slice();
12591 };
12592
12593 /**
12594 * Emit a resize event if the size has changed.
12595 *
12596 * @private
12597 * @chainable
12598 */
12599 OO.ui.ActionWidget.prototype.propagateResize = function () {
12600 var width, height;
12601
12602 if ( this.isElementAttached() ) {
12603 width = this.$element.width();
12604 height = this.$element.height();
12605
12606 if ( width !== this.width || height !== this.height ) {
12607 this.width = width;
12608 this.height = height;
12609 this.emit( 'resize' );
12610 }
12611 }
12612
12613 return this;
12614 };
12615
12616 /**
12617 * @inheritdoc
12618 */
12619 OO.ui.ActionWidget.prototype.setIcon = function () {
12620 // Mixin method
12621 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12622 this.propagateResize();
12623
12624 return this;
12625 };
12626
12627 /**
12628 * @inheritdoc
12629 */
12630 OO.ui.ActionWidget.prototype.setLabel = function () {
12631 // Mixin method
12632 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12633 this.propagateResize();
12634
12635 return this;
12636 };
12637
12638 /**
12639 * @inheritdoc
12640 */
12641 OO.ui.ActionWidget.prototype.setFlags = function () {
12642 // Mixin method
12643 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12644 this.propagateResize();
12645
12646 return this;
12647 };
12648
12649 /**
12650 * @inheritdoc
12651 */
12652 OO.ui.ActionWidget.prototype.clearFlags = function () {
12653 // Mixin method
12654 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12655 this.propagateResize();
12656
12657 return this;
12658 };
12659
12660 /**
12661 * Toggle the visibility of the action button.
12662 *
12663 * @param {boolean} [show] Show button, omit to toggle visibility
12664 * @chainable
12665 */
12666 OO.ui.ActionWidget.prototype.toggle = function () {
12667 // Parent method
12668 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12669 this.propagateResize();
12670
12671 return this;
12672 };
12673
12674 /**
12675 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12676 * which is used to display additional information or options.
12677 *
12678 * @example
12679 * // Example of a popup button.
12680 * var popupButton = new OO.ui.PopupButtonWidget( {
12681 * label: 'Popup button with options',
12682 * icon: 'menu',
12683 * popup: {
12684 * $content: $( '<p>Additional options here.</p>' ),
12685 * padded: true,
12686 * align: 'force-left'
12687 * }
12688 * } );
12689 * // Append the button to the DOM.
12690 * $( 'body' ).append( popupButton.$element );
12691 *
12692 * @class
12693 * @extends OO.ui.ButtonWidget
12694 * @mixins OO.ui.mixin.PopupElement
12695 *
12696 * @constructor
12697 * @param {Object} [config] Configuration options
12698 */
12699 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12700 // Parent constructor
12701 OO.ui.PopupButtonWidget.parent.call( this, config );
12702
12703 // Mixin constructors
12704 OO.ui.mixin.PopupElement.call( this, config );
12705
12706 // Events
12707 this.connect( this, { click: 'onAction' } );
12708
12709 // Initialization
12710 this.$element
12711 .addClass( 'oo-ui-popupButtonWidget' )
12712 .attr( 'aria-haspopup', 'true' )
12713 .append( this.popup.$element );
12714 };
12715
12716 /* Setup */
12717
12718 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12719 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12720
12721 /* Methods */
12722
12723 /**
12724 * Handle the button action being triggered.
12725 *
12726 * @private
12727 */
12728 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12729 this.popup.toggle();
12730 };
12731
12732 /**
12733 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12734 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12735 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12736 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12737 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12738 * the [OOjs UI documentation][1] on MediaWiki for more information.
12739 *
12740 * @example
12741 * // Toggle buttons in the 'off' and 'on' state.
12742 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12743 * label: 'Toggle Button off'
12744 * } );
12745 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12746 * label: 'Toggle Button on',
12747 * value: true
12748 * } );
12749 * // Append the buttons to the DOM.
12750 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12751 *
12752 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12753 *
12754 * @class
12755 * @extends OO.ui.ToggleWidget
12756 * @mixins OO.ui.mixin.ButtonElement
12757 * @mixins OO.ui.mixin.IconElement
12758 * @mixins OO.ui.mixin.IndicatorElement
12759 * @mixins OO.ui.mixin.LabelElement
12760 * @mixins OO.ui.mixin.TitledElement
12761 * @mixins OO.ui.mixin.FlaggedElement
12762 * @mixins OO.ui.mixin.TabIndexedElement
12763 *
12764 * @constructor
12765 * @param {Object} [config] Configuration options
12766 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12767 * state. By default, the button is in the 'off' state.
12768 */
12769 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12770 // Configuration initialization
12771 config = config || {};
12772
12773 // Parent constructor
12774 OO.ui.ToggleButtonWidget.parent.call( this, config );
12775
12776 // Mixin constructors
12777 OO.ui.mixin.ButtonElement.call( this, config );
12778 OO.ui.mixin.IconElement.call( this, config );
12779 OO.ui.mixin.IndicatorElement.call( this, config );
12780 OO.ui.mixin.LabelElement.call( this, config );
12781 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12782 OO.ui.mixin.FlaggedElement.call( this, config );
12783 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12784
12785 // Events
12786 this.connect( this, { click: 'onAction' } );
12787
12788 // Initialization
12789 this.$button.append( this.$icon, this.$label, this.$indicator );
12790 this.$element
12791 .addClass( 'oo-ui-toggleButtonWidget' )
12792 .append( this.$button );
12793 };
12794
12795 /* Setup */
12796
12797 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
12798 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
12799 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
12800 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
12801 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
12802 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
12803 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
12804 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
12805
12806 /* Methods */
12807
12808 /**
12809 * Handle the button action being triggered.
12810 *
12811 * @private
12812 */
12813 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
12814 this.setValue( !this.value );
12815 };
12816
12817 /**
12818 * @inheritdoc
12819 */
12820 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
12821 value = !!value;
12822 if ( value !== this.value ) {
12823 // Might be called from parent constructor before ButtonElement constructor
12824 if ( this.$button ) {
12825 this.$button.attr( 'aria-pressed', value.toString() );
12826 }
12827 this.setActive( value );
12828 }
12829
12830 // Parent method
12831 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
12832
12833 return this;
12834 };
12835
12836 /**
12837 * @inheritdoc
12838 */
12839 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
12840 if ( this.$button ) {
12841 this.$button.removeAttr( 'aria-pressed' );
12842 }
12843 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
12844 this.$button.attr( 'aria-pressed', this.value.toString() );
12845 };
12846
12847 /**
12848 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12849 * that allows for selecting multiple values.
12850 *
12851 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12852 *
12853 * @example
12854 * // Example: A CapsuleMultiSelectWidget.
12855 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12856 * label: 'CapsuleMultiSelectWidget',
12857 * selected: [ 'Option 1', 'Option 3' ],
12858 * menu: {
12859 * items: [
12860 * new OO.ui.MenuOptionWidget( {
12861 * data: 'Option 1',
12862 * label: 'Option One'
12863 * } ),
12864 * new OO.ui.MenuOptionWidget( {
12865 * data: 'Option 2',
12866 * label: 'Option Two'
12867 * } ),
12868 * new OO.ui.MenuOptionWidget( {
12869 * data: 'Option 3',
12870 * label: 'Option Three'
12871 * } ),
12872 * new OO.ui.MenuOptionWidget( {
12873 * data: 'Option 4',
12874 * label: 'Option Four'
12875 * } ),
12876 * new OO.ui.MenuOptionWidget( {
12877 * data: 'Option 5',
12878 * label: 'Option Five'
12879 * } )
12880 * ]
12881 * }
12882 * } );
12883 * $( 'body' ).append( capsule.$element );
12884 *
12885 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12886 *
12887 * @class
12888 * @extends OO.ui.Widget
12889 * @mixins OO.ui.mixin.TabIndexedElement
12890 * @mixins OO.ui.mixin.GroupElement
12891 *
12892 * @constructor
12893 * @param {Object} [config] Configuration options
12894 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12895 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12896 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12897 * If specified, this popup will be shown instead of the menu (but the menu
12898 * will still be used for item labels and allowArbitrary=false). The widgets
12899 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12900 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12901 * This configuration is useful in cases where the expanded menu is larger than
12902 * its containing `<div>`. The specified overlay layer is usually on top of
12903 * the containing `<div>` and has a larger area. By default, the menu uses
12904 * relative positioning.
12905 */
12906 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
12907 var $tabFocus;
12908
12909 // Configuration initialization
12910 config = config || {};
12911
12912 // Parent constructor
12913 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
12914
12915 // Properties (must be set before mixin constructor calls)
12916 this.$input = config.popup ? null : $( '<input>' );
12917 this.$handle = $( '<div>' );
12918
12919 // Mixin constructors
12920 OO.ui.mixin.GroupElement.call( this, config );
12921 if ( config.popup ) {
12922 config.popup = $.extend( {}, config.popup, {
12923 align: 'forwards',
12924 anchor: false
12925 } );
12926 OO.ui.mixin.PopupElement.call( this, config );
12927 $tabFocus = $( '<span>' );
12928 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
12929 } else {
12930 this.popup = null;
12931 $tabFocus = null;
12932 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
12933 }
12934 OO.ui.mixin.IndicatorElement.call( this, config );
12935 OO.ui.mixin.IconElement.call( this, config );
12936
12937 // Properties
12938 this.allowArbitrary = !!config.allowArbitrary;
12939 this.$overlay = config.$overlay || this.$element;
12940 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
12941 {
12942 widget: this,
12943 $input: this.$input,
12944 $container: this.$element,
12945 filterFromInput: true,
12946 disabled: this.isDisabled()
12947 },
12948 config.menu
12949 ) );
12950
12951 // Events
12952 if ( this.popup ) {
12953 $tabFocus.on( {
12954 focus: this.onFocusForPopup.bind( this )
12955 } );
12956 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12957 if ( this.popup.$autoCloseIgnore ) {
12958 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12959 }
12960 this.popup.connect( this, {
12961 toggle: function ( visible ) {
12962 $tabFocus.toggle( !visible );
12963 }
12964 } );
12965 } else {
12966 this.$input.on( {
12967 focus: this.onInputFocus.bind( this ),
12968 blur: this.onInputBlur.bind( this ),
12969 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
12970 keydown: this.onKeyDown.bind( this ),
12971 keypress: this.onKeyPress.bind( this )
12972 } );
12973 }
12974 this.menu.connect( this, {
12975 choose: 'onMenuChoose',
12976 add: 'onMenuItemsChange',
12977 remove: 'onMenuItemsChange'
12978 } );
12979 this.$handle.on( {
12980 click: this.onClick.bind( this )
12981 } );
12982
12983 // Initialization
12984 if ( this.$input ) {
12985 this.$input.prop( 'disabled', this.isDisabled() );
12986 this.$input.attr( {
12987 role: 'combobox',
12988 'aria-autocomplete': 'list'
12989 } );
12990 this.$input.width( '1em' );
12991 }
12992 if ( config.data ) {
12993 this.setItemsFromData( config.data );
12994 }
12995 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12996 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12997 .append( this.$indicator, this.$icon, this.$group );
12998 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
12999 .append( this.$handle );
13000 if ( this.popup ) {
13001 this.$handle.append( $tabFocus );
13002 this.$overlay.append( this.popup.$element );
13003 } else {
13004 this.$handle.append( this.$input );
13005 this.$overlay.append( this.menu.$element );
13006 }
13007 this.onMenuItemsChange();
13008 };
13009
13010 /* Setup */
13011
13012 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13013 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13014 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13015 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13016 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13017 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13018
13019 /* Events */
13020
13021 /**
13022 * @event change
13023 *
13024 * A change event is emitted when the set of selected items changes.
13025 *
13026 * @param {Mixed[]} datas Data of the now-selected items
13027 */
13028
13029 /* Methods */
13030
13031 /**
13032 * Get the data of the items in the capsule
13033 * @return {Mixed[]}
13034 */
13035 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13036 return $.map( this.getItems(), function ( e ) { return e.data; } );
13037 };
13038
13039 /**
13040 * Set the items in the capsule by providing data
13041 * @chainable
13042 * @param {Mixed[]} datas
13043 * @return {OO.ui.CapsuleMultiSelectWidget}
13044 */
13045 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13046 var widget = this,
13047 menu = this.menu,
13048 items = this.getItems();
13049
13050 $.each( datas, function ( i, data ) {
13051 var j, label,
13052 item = menu.getItemFromData( data );
13053
13054 if ( item ) {
13055 label = item.label;
13056 } else if ( widget.allowArbitrary ) {
13057 label = String( data );
13058 } else {
13059 return;
13060 }
13061
13062 item = null;
13063 for ( j = 0; j < items.length; j++ ) {
13064 if ( items[ j ].data === data && items[ j ].label === label ) {
13065 item = items[ j ];
13066 items.splice( j, 1 );
13067 break;
13068 }
13069 }
13070 if ( !item ) {
13071 item = new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13072 }
13073 widget.addItems( [ item ], i );
13074 } );
13075
13076 if ( items.length ) {
13077 widget.removeItems( items );
13078 }
13079
13080 return this;
13081 };
13082
13083 /**
13084 * Add items to the capsule by providing their data
13085 * @chainable
13086 * @param {Mixed[]} datas
13087 * @return {OO.ui.CapsuleMultiSelectWidget}
13088 */
13089 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13090 var widget = this,
13091 menu = this.menu,
13092 items = [];
13093
13094 $.each( datas, function ( i, data ) {
13095 var item;
13096
13097 if ( !widget.getItemFromData( data ) ) {
13098 item = menu.getItemFromData( data );
13099 if ( item ) {
13100 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: item.label } ) );
13101 } else if ( widget.allowArbitrary ) {
13102 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: String( data ) } ) );
13103 }
13104 }
13105 } );
13106
13107 if ( items.length ) {
13108 this.addItems( items );
13109 }
13110
13111 return this;
13112 };
13113
13114 /**
13115 * Remove items by data
13116 * @chainable
13117 * @param {Mixed[]} datas
13118 * @return {OO.ui.CapsuleMultiSelectWidget}
13119 */
13120 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13121 var widget = this,
13122 items = [];
13123
13124 $.each( datas, function ( i, data ) {
13125 var item = widget.getItemFromData( data );
13126 if ( item ) {
13127 items.push( item );
13128 }
13129 } );
13130
13131 if ( items.length ) {
13132 this.removeItems( items );
13133 }
13134
13135 return this;
13136 };
13137
13138 /**
13139 * @inheritdoc
13140 */
13141 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13142 var same, i, l,
13143 oldItems = this.items.slice();
13144
13145 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13146
13147 if ( this.items.length !== oldItems.length ) {
13148 same = false;
13149 } else {
13150 same = true;
13151 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13152 same = same && this.items[ i ] === oldItems[ i ];
13153 }
13154 }
13155 if ( !same ) {
13156 this.emit( 'change', this.getItemsData() );
13157 }
13158
13159 return this;
13160 };
13161
13162 /**
13163 * @inheritdoc
13164 */
13165 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13166 var same, i, l,
13167 oldItems = this.items.slice();
13168
13169 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13170
13171 if ( this.items.length !== oldItems.length ) {
13172 same = false;
13173 } else {
13174 same = true;
13175 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13176 same = same && this.items[ i ] === oldItems[ i ];
13177 }
13178 }
13179 if ( !same ) {
13180 this.emit( 'change', this.getItemsData() );
13181 }
13182
13183 return this;
13184 };
13185
13186 /**
13187 * @inheritdoc
13188 */
13189 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13190 if ( this.items.length ) {
13191 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13192 this.emit( 'change', this.getItemsData() );
13193 }
13194 return this;
13195 };
13196
13197 /**
13198 * Get the capsule widget's menu.
13199 * @return {OO.ui.MenuSelectWidget} Menu widget
13200 */
13201 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13202 return this.menu;
13203 };
13204
13205 /**
13206 * Handle focus events
13207 *
13208 * @private
13209 * @param {jQuery.Event} event
13210 */
13211 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13212 if ( !this.isDisabled() ) {
13213 this.menu.toggle( true );
13214 }
13215 };
13216
13217 /**
13218 * Handle blur events
13219 *
13220 * @private
13221 * @param {jQuery.Event} event
13222 */
13223 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13224 this.clearInput();
13225 };
13226
13227 /**
13228 * Handle focus events
13229 *
13230 * @private
13231 * @param {jQuery.Event} event
13232 */
13233 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13234 if ( !this.isDisabled() ) {
13235 this.popup.setSize( this.$handle.width() );
13236 this.popup.toggle( true );
13237 this.popup.$element.find( '*' )
13238 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13239 .first()
13240 .focus();
13241 }
13242 };
13243
13244 /**
13245 * Handles popup focus out events.
13246 *
13247 * @private
13248 * @param {Event} e Focus out event
13249 */
13250 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13251 var widget = this.popup;
13252
13253 setTimeout( function () {
13254 if (
13255 widget.isVisible() &&
13256 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13257 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13258 ) {
13259 widget.toggle( false );
13260 }
13261 } );
13262 };
13263
13264 /**
13265 * Handle mouse click events.
13266 *
13267 * @private
13268 * @param {jQuery.Event} e Mouse click event
13269 */
13270 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13271 if ( e.which === 1 ) {
13272 this.focus();
13273 return false;
13274 }
13275 };
13276
13277 /**
13278 * Handle key press events.
13279 *
13280 * @private
13281 * @param {jQuery.Event} e Key press event
13282 */
13283 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13284 var item;
13285
13286 if ( !this.isDisabled() ) {
13287 if ( e.which === OO.ui.Keys.ESCAPE ) {
13288 this.clearInput();
13289 return false;
13290 }
13291
13292 if ( !this.popup ) {
13293 this.menu.toggle( true );
13294 if ( e.which === OO.ui.Keys.ENTER ) {
13295 item = this.menu.getItemFromLabel( this.$input.val(), true );
13296 if ( item ) {
13297 this.addItemsFromData( [ item.data ] );
13298 this.clearInput();
13299 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13300 this.addItemsFromData( [ this.$input.val() ] );
13301 this.clearInput();
13302 }
13303 return false;
13304 }
13305
13306 // Make sure the input gets resized.
13307 setTimeout( this.onInputChange.bind( this ), 0 );
13308 }
13309 }
13310 };
13311
13312 /**
13313 * Handle key down events.
13314 *
13315 * @private
13316 * @param {jQuery.Event} e Key down event
13317 */
13318 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13319 if ( !this.isDisabled() ) {
13320 // 'keypress' event is not triggered for Backspace
13321 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13322 if ( this.items.length ) {
13323 this.removeItems( this.items.slice( -1 ) );
13324 }
13325 return false;
13326 }
13327 }
13328 };
13329
13330 /**
13331 * Handle input change events.
13332 *
13333 * @private
13334 * @param {jQuery.Event} e Event of some sort
13335 */
13336 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13337 if ( !this.isDisabled() ) {
13338 this.$input.width( this.$input.val().length + 'em' );
13339 }
13340 };
13341
13342 /**
13343 * Handle menu choose events.
13344 *
13345 * @private
13346 * @param {OO.ui.OptionWidget} item Chosen item
13347 */
13348 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13349 if ( item && item.isVisible() ) {
13350 this.addItemsFromData( [ item.getData() ] );
13351 this.clearInput();
13352 }
13353 };
13354
13355 /**
13356 * Handle menu item change events.
13357 *
13358 * @private
13359 */
13360 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13361 this.setItemsFromData( this.getItemsData() );
13362 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13363 };
13364
13365 /**
13366 * Clear the input field
13367 * @private
13368 */
13369 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13370 if ( this.$input ) {
13371 this.$input.val( '' );
13372 this.$input.width( '1em' );
13373 }
13374 if ( this.popup ) {
13375 this.popup.toggle( false );
13376 }
13377 this.menu.toggle( false );
13378 this.menu.selectItem();
13379 this.menu.highlightItem();
13380 };
13381
13382 /**
13383 * @inheritdoc
13384 */
13385 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13386 var i, len;
13387
13388 // Parent method
13389 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13390
13391 if ( this.$input ) {
13392 this.$input.prop( 'disabled', this.isDisabled() );
13393 }
13394 if ( this.menu ) {
13395 this.menu.setDisabled( this.isDisabled() );
13396 }
13397 if ( this.popup ) {
13398 this.popup.setDisabled( this.isDisabled() );
13399 }
13400
13401 if ( this.items ) {
13402 for ( i = 0, len = this.items.length; i < len; i++ ) {
13403 this.items[ i ].updateDisabled();
13404 }
13405 }
13406
13407 return this;
13408 };
13409
13410 /**
13411 * Focus the widget
13412 * @chainable
13413 * @return {OO.ui.CapsuleMultiSelectWidget}
13414 */
13415 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13416 if ( !this.isDisabled() ) {
13417 if ( this.popup ) {
13418 this.popup.setSize( this.$handle.width() );
13419 this.popup.toggle( true );
13420 this.popup.$element.find( '*' )
13421 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13422 .first()
13423 .focus();
13424 } else {
13425 this.menu.toggle( true );
13426 this.$input.focus();
13427 }
13428 }
13429 return this;
13430 };
13431
13432 /**
13433 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13434 * CapsuleMultiSelectWidget} to display the selected items.
13435 *
13436 * @class
13437 * @extends OO.ui.Widget
13438 * @mixins OO.ui.mixin.ItemWidget
13439 * @mixins OO.ui.mixin.IndicatorElement
13440 * @mixins OO.ui.mixin.LabelElement
13441 * @mixins OO.ui.mixin.FlaggedElement
13442 * @mixins OO.ui.mixin.TabIndexedElement
13443 *
13444 * @constructor
13445 * @param {Object} [config] Configuration options
13446 */
13447 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13448 // Configuration initialization
13449 config = config || {};
13450
13451 // Parent constructor
13452 OO.ui.CapsuleItemWidget.parent.call( this, config );
13453
13454 // Properties (must be set before mixin constructor calls)
13455 this.$indicator = $( '<span>' );
13456
13457 // Mixin constructors
13458 OO.ui.mixin.ItemWidget.call( this );
13459 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13460 OO.ui.mixin.LabelElement.call( this, config );
13461 OO.ui.mixin.FlaggedElement.call( this, config );
13462 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13463
13464 // Events
13465 this.$indicator.on( {
13466 keydown: this.onCloseKeyDown.bind( this ),
13467 click: this.onCloseClick.bind( this )
13468 } );
13469 this.$element.on( 'click', false );
13470
13471 // Initialization
13472 this.$element
13473 .addClass( 'oo-ui-capsuleItemWidget' )
13474 .append( this.$indicator, this.$label );
13475 };
13476
13477 /* Setup */
13478
13479 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13480 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13481 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13482 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13483 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13484 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13485
13486 /* Methods */
13487
13488 /**
13489 * Handle close icon clicks
13490 * @param {jQuery.Event} event
13491 */
13492 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13493 var element = this.getElementGroup();
13494
13495 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13496 element.removeItems( [ this ] );
13497 element.focus();
13498 }
13499 };
13500
13501 /**
13502 * Handle close keyboard events
13503 * @param {jQuery.Event} event Key down event
13504 */
13505 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13506 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13507 switch ( e.which ) {
13508 case OO.ui.Keys.ENTER:
13509 case OO.ui.Keys.BACKSPACE:
13510 case OO.ui.Keys.SPACE:
13511 this.getElementGroup().removeItems( [ this ] );
13512 return false;
13513 }
13514 }
13515 };
13516
13517 /**
13518 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13519 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13520 * users can interact with it.
13521 *
13522 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13523 * OO.ui.DropdownInputWidget instead.
13524 *
13525 * @example
13526 * // Example: A DropdownWidget with a menu that contains three options
13527 * var dropDown = new OO.ui.DropdownWidget( {
13528 * label: 'Dropdown menu: Select a menu option',
13529 * menu: {
13530 * items: [
13531 * new OO.ui.MenuOptionWidget( {
13532 * data: 'a',
13533 * label: 'First'
13534 * } ),
13535 * new OO.ui.MenuOptionWidget( {
13536 * data: 'b',
13537 * label: 'Second'
13538 * } ),
13539 * new OO.ui.MenuOptionWidget( {
13540 * data: 'c',
13541 * label: 'Third'
13542 * } )
13543 * ]
13544 * }
13545 * } );
13546 *
13547 * $( 'body' ).append( dropDown.$element );
13548 *
13549 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13550 *
13551 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13552 *
13553 * @class
13554 * @extends OO.ui.Widget
13555 * @mixins OO.ui.mixin.IconElement
13556 * @mixins OO.ui.mixin.IndicatorElement
13557 * @mixins OO.ui.mixin.LabelElement
13558 * @mixins OO.ui.mixin.TitledElement
13559 * @mixins OO.ui.mixin.TabIndexedElement
13560 *
13561 * @constructor
13562 * @param {Object} [config] Configuration options
13563 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13564 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13565 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13566 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13567 */
13568 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13569 // Configuration initialization
13570 config = $.extend( { indicator: 'down' }, config );
13571
13572 // Parent constructor
13573 OO.ui.DropdownWidget.parent.call( this, config );
13574
13575 // Properties (must be set before TabIndexedElement constructor call)
13576 this.$handle = this.$( '<span>' );
13577 this.$overlay = config.$overlay || this.$element;
13578
13579 // Mixin constructors
13580 OO.ui.mixin.IconElement.call( this, config );
13581 OO.ui.mixin.IndicatorElement.call( this, config );
13582 OO.ui.mixin.LabelElement.call( this, config );
13583 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13584 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13585
13586 // Properties
13587 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13588 widget: this,
13589 $container: this.$element
13590 }, config.menu ) );
13591
13592 // Events
13593 this.$handle.on( {
13594 click: this.onClick.bind( this ),
13595 keypress: this.onKeyPress.bind( this )
13596 } );
13597 this.menu.connect( this, { select: 'onMenuSelect' } );
13598
13599 // Initialization
13600 this.$handle
13601 .addClass( 'oo-ui-dropdownWidget-handle' )
13602 .append( this.$icon, this.$label, this.$indicator );
13603 this.$element
13604 .addClass( 'oo-ui-dropdownWidget' )
13605 .append( this.$handle );
13606 this.$overlay.append( this.menu.$element );
13607 };
13608
13609 /* Setup */
13610
13611 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13612 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13613 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13614 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13615 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13616 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13617
13618 /* Methods */
13619
13620 /**
13621 * Get the menu.
13622 *
13623 * @return {OO.ui.MenuSelectWidget} Menu of widget
13624 */
13625 OO.ui.DropdownWidget.prototype.getMenu = function () {
13626 return this.menu;
13627 };
13628
13629 /**
13630 * Handles menu select events.
13631 *
13632 * @private
13633 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13634 */
13635 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13636 var selectedLabel;
13637
13638 if ( !item ) {
13639 this.setLabel( null );
13640 return;
13641 }
13642
13643 selectedLabel = item.getLabel();
13644
13645 // If the label is a DOM element, clone it, because setLabel will append() it
13646 if ( selectedLabel instanceof jQuery ) {
13647 selectedLabel = selectedLabel.clone();
13648 }
13649
13650 this.setLabel( selectedLabel );
13651 };
13652
13653 /**
13654 * Handle mouse click events.
13655 *
13656 * @private
13657 * @param {jQuery.Event} e Mouse click event
13658 */
13659 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13660 if ( !this.isDisabled() && e.which === 1 ) {
13661 this.menu.toggle();
13662 }
13663 return false;
13664 };
13665
13666 /**
13667 * Handle key press events.
13668 *
13669 * @private
13670 * @param {jQuery.Event} e Key press event
13671 */
13672 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13673 if ( !this.isDisabled() &&
13674 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13675 ) {
13676 this.menu.toggle();
13677 return false;
13678 }
13679 };
13680
13681 /**
13682 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13683 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13684 * OO.ui.mixin.IndicatorElement indicators}.
13685 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13686 *
13687 * @example
13688 * // Example of a file select widget
13689 * var selectFile = new OO.ui.SelectFileWidget();
13690 * $( 'body' ).append( selectFile.$element );
13691 *
13692 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13693 *
13694 * @class
13695 * @extends OO.ui.Widget
13696 * @mixins OO.ui.mixin.IconElement
13697 * @mixins OO.ui.mixin.IndicatorElement
13698 * @mixins OO.ui.mixin.PendingElement
13699 * @mixins OO.ui.mixin.LabelElement
13700 * @mixins OO.ui.mixin.TabIndexedElement
13701 *
13702 * @constructor
13703 * @param {Object} [config] Configuration options
13704 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13705 * @cfg {string} [placeholder] Text to display when no file is selected.
13706 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13707 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13708 * @cfg {boolean} [dragDropUI=false] Whether to render the drag and drop UI.
13709 */
13710 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13711 var dragHandler,
13712 placeholderMsg = ( config && config.dragDropUI ) ?
13713 'ooui-selectfile-dragdrop-placeholder' :
13714 'ooui-selectfile-placeholder';
13715
13716 // Configuration initialization
13717 config = $.extend( {
13718 accept: null,
13719 placeholder: OO.ui.msg( placeholderMsg ),
13720 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13721 droppable: true,
13722 dragDropUI: false
13723 }, config );
13724
13725 // Parent constructor
13726 OO.ui.SelectFileWidget.parent.call( this, config );
13727
13728 // Properties (must be set before TabIndexedElement constructor call)
13729 this.$handle = $( '<span>' );
13730
13731 // Mixin constructors
13732 OO.ui.mixin.IconElement.call( this, config );
13733 OO.ui.mixin.IndicatorElement.call( this, config );
13734 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$handle } ) );
13735 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13736 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13737
13738 // Properties
13739 this.active = false;
13740 this.dragDropUI = config.dragDropUI;
13741 this.isSupported = this.constructor.static.isSupported();
13742 this.currentFile = null;
13743 if ( Array.isArray( config.accept ) ) {
13744 this.accept = config.accept;
13745 } else {
13746 this.accept = null;
13747 }
13748 this.placeholder = config.placeholder;
13749 this.notsupported = config.notsupported;
13750 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13751
13752 this.clearButton = new OO.ui.ButtonWidget( {
13753 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13754 framed: false,
13755 icon: 'remove',
13756 disabled: this.disabled
13757 } );
13758
13759 // Events
13760 this.$handle.on( {
13761 keypress: this.onKeyPress.bind( this )
13762 } );
13763 this.clearButton.connect( this, {
13764 click: 'onClearClick'
13765 } );
13766 if ( config.droppable ) {
13767 dragHandler = this.onDragEnterOrOver.bind( this );
13768 this.$handle.on( {
13769 dragenter: dragHandler,
13770 dragover: dragHandler,
13771 dragleave: this.onDragLeave.bind( this ),
13772 drop: this.onDrop.bind( this )
13773 } );
13774 }
13775
13776 // Initialization
13777 this.addInput();
13778 this.updateUI();
13779 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
13780 this.$handle
13781 .addClass( 'oo-ui-selectFileWidget-handle' )
13782 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
13783 this.$element
13784 .addClass( 'oo-ui-selectFileWidget' )
13785 .append( this.$handle );
13786 if ( config.droppable ) {
13787 if ( config.dragDropUI ) {
13788 this.$element.addClass( 'oo-ui-selectFileWidget-dragdrop-ui' );
13789 this.$element.on( {
13790 mouseover: this.onMouseOver.bind( this ),
13791 mouseleave: this.onMouseLeave.bind( this )
13792 } );
13793 } else {
13794 this.$element.addClass( 'oo-ui-selectFileWidget-droppable' );
13795 }
13796 }
13797 };
13798
13799 /* Setup */
13800
13801 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
13802 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
13803 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
13804 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
13805 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
13806 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.TabIndexedElement );
13807
13808 /* Static Properties */
13809
13810 /**
13811 * Check if this widget is supported
13812 *
13813 * @static
13814 * @return {boolean}
13815 */
13816 OO.ui.SelectFileWidget.static.isSupported = function () {
13817 var $input;
13818 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
13819 $input = $( '<input type="file">' );
13820 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
13821 }
13822 return OO.ui.SelectFileWidget.static.isSupportedCache;
13823 };
13824
13825 OO.ui.SelectFileWidget.static.isSupportedCache = null;
13826
13827 /* Events */
13828
13829 /**
13830 * @event change
13831 *
13832 * A change event is emitted when the on/off state of the toggle changes.
13833 *
13834 * @param {File|null} value New value
13835 */
13836
13837 /* Methods */
13838
13839 /**
13840 * Get the current value of the field
13841 *
13842 * @return {File|null}
13843 */
13844 OO.ui.SelectFileWidget.prototype.getValue = function () {
13845 return this.currentFile;
13846 };
13847
13848 /**
13849 * Set the current value of the field
13850 *
13851 * @param {File|null} file File to select
13852 */
13853 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
13854 if ( this.currentFile !== file ) {
13855 this.currentFile = file;
13856 this.updateUI();
13857 this.emit( 'change', this.currentFile );
13858 }
13859 };
13860
13861 /**
13862 * Update the user interface when a file is selected or unselected
13863 *
13864 * @protected
13865 */
13866 OO.ui.SelectFileWidget.prototype.updateUI = function () {
13867 if ( !this.isSupported ) {
13868 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
13869 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13870 this.setLabel( this.notsupported );
13871 } else if ( this.currentFile ) {
13872 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13873 this.setLabel( this.currentFile.name +
13874 ( this.currentFile.type !== '' ? OO.ui.msg( 'ooui-semicolon-separator' ) + this.currentFile.type : '' )
13875 );
13876 } else {
13877 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
13878 this.setLabel( this.placeholder );
13879 }
13880
13881 if ( this.$input ) {
13882 this.$input.attr( 'title', this.getLabel() );
13883 }
13884 };
13885
13886 /**
13887 * Add the input to the handle
13888 *
13889 * @private
13890 */
13891 OO.ui.SelectFileWidget.prototype.addInput = function () {
13892 if ( this.$input ) {
13893 this.$input.remove();
13894 }
13895
13896 if ( !this.isSupported ) {
13897 this.$input = null;
13898 return;
13899 }
13900
13901 this.$input = $( '<input type="file">' );
13902 this.$input.on( 'change', this.onFileSelectedHandler );
13903 this.$input.attr( {
13904 tabindex: -1,
13905 title: this.getLabel()
13906 } );
13907 if ( this.accept ) {
13908 this.$input.attr( 'accept', this.accept.join( ', ' ) );
13909 }
13910 this.$handle.append( this.$input );
13911 };
13912
13913 /**
13914 * Determine if we should accept this file
13915 *
13916 * @private
13917 * @param {File} file
13918 * @return {boolean}
13919 */
13920 OO.ui.SelectFileWidget.prototype.isFileAcceptable = function ( file ) {
13921 var i, mime, mimeTest;
13922
13923 if ( !this.accept || file.type === '' ) {
13924 return true;
13925 }
13926
13927 mime = file.type;
13928 for ( i = 0; i < this.accept.length; i++ ) {
13929 mimeTest = this.accept[ i ];
13930 if ( mimeTest === mime ) {
13931 return true;
13932 } else if ( mimeTest.substr( -2 ) === '/*' ) {
13933 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
13934 if ( mime.substr( 0, mimeTest.length ) === mimeTest ) {
13935 return true;
13936 }
13937 }
13938 }
13939
13940 return false;
13941 };
13942
13943 /**
13944 * Handle file selection from the input
13945 *
13946 * @private
13947 * @param {jQuery.Event} e
13948 */
13949 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
13950 var file = null;
13951
13952 if ( e.target.files && e.target.files[ 0 ] ) {
13953 file = e.target.files[ 0 ];
13954 if ( !this.isFileAcceptable( file ) ) {
13955 file = null;
13956 }
13957 }
13958
13959 this.setValue( file );
13960 this.addInput();
13961 };
13962
13963 /**
13964 * Handle clear button click events.
13965 *
13966 * @private
13967 */
13968 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
13969 this.setValue( null );
13970 return false;
13971 };
13972
13973 /**
13974 * Handle key press events.
13975 *
13976 * @private
13977 * @param {jQuery.Event} e Key press event
13978 */
13979 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
13980 if ( this.isSupported && !this.isDisabled() && this.$input &&
13981 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
13982 ) {
13983 this.$input.click();
13984 return false;
13985 }
13986 };
13987
13988 /**
13989 * Handle drag enter and over events
13990 *
13991 * @private
13992 * @param {jQuery.Event} e Drag event
13993 */
13994 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
13995 var file = null,
13996 dt = e.originalEvent.dataTransfer;
13997
13998 e.preventDefault();
13999 e.stopPropagation();
14000
14001 if ( this.isDisabled() || !this.isSupported ) {
14002 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14003 this.setActive( false );
14004 dt.dropEffect = 'none';
14005 return false;
14006 }
14007
14008 if ( dt && dt.files && dt.files[ 0 ] ) {
14009 file = dt.files[ 0 ];
14010 if ( !this.isFileAcceptable( file ) ) {
14011 file = null;
14012 }
14013 } else if ( dt && dt.types && dt.types.indexOf( 'Files' ) !== -1 ) {
14014 // We know we have files so set 'file' to something truthy, we just
14015 // can't know any details about them.
14016 // * https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14017 file = 'Files exist, but details are unknown';
14018 }
14019 if ( file ) {
14020 this.$element.addClass( 'oo-ui-selectFileWidget-canDrop' );
14021 this.setActive( true );
14022 } else {
14023 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14024 this.setActive( false );
14025 dt.dropEffect = 'none';
14026 }
14027
14028 return false;
14029 };
14030
14031 /**
14032 * Handle drag leave events
14033 *
14034 * @private
14035 * @param {jQuery.Event} e Drag event
14036 */
14037 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14038 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14039 this.setActive( false );
14040 };
14041
14042 /**
14043 * Handle drop events
14044 *
14045 * @private
14046 * @param {jQuery.Event} e Drop event
14047 */
14048 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14049 var file = null,
14050 dt = e.originalEvent.dataTransfer;
14051
14052 e.preventDefault();
14053 e.stopPropagation();
14054 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14055 this.setActive( false );
14056
14057 if ( this.isDisabled() || !this.isSupported ) {
14058 return false;
14059 }
14060
14061 if ( dt && dt.files && dt.files[ 0 ] ) {
14062 file = dt.files[ 0 ];
14063 if ( !this.isFileAcceptable( file ) ) {
14064 file = null;
14065 }
14066 }
14067 if ( file ) {
14068 this.setValue( file );
14069 }
14070
14071 return false;
14072 };
14073
14074 /**
14075 * Handle mouse over events.
14076 *
14077 * @private
14078 * @param {jQuery.Event} e Mouse over event
14079 */
14080 OO.ui.SelectFileWidget.prototype.onMouseOver = function () {
14081 this.setActive( true );
14082 };
14083
14084 /**
14085 * Handle mouse leave events.
14086 *
14087 * @private
14088 * @param {jQuery.Event} e Mouse over event
14089 */
14090 OO.ui.SelectFileWidget.prototype.onMouseLeave = function () {
14091 this.setActive( false );
14092 };
14093
14094 /**
14095 * @inheritdoc
14096 */
14097 OO.ui.SelectFileWidget.prototype.setDisabled = function ( state ) {
14098 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, state );
14099 if ( this.clearButton ) {
14100 this.clearButton.setDisabled( state );
14101 }
14102 return this;
14103 };
14104
14105 /**
14106 * Set 'active' (hover) state, only matters for widgets with `dragDropUI: true`.
14107 *
14108 * @param {boolean} value Whether widget is active
14109 * @chainable
14110 */
14111 OO.ui.SelectFileWidget.prototype.setActive = function ( value ) {
14112 if ( this.dragDropUI ) {
14113 this.active = value;
14114 this.updateThemeClasses();
14115 }
14116 return this;
14117 };
14118
14119 /**
14120 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14121 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14122 * for a list of icons included in the library.
14123 *
14124 * @example
14125 * // An icon widget with a label
14126 * var myIcon = new OO.ui.IconWidget( {
14127 * icon: 'help',
14128 * iconTitle: 'Help'
14129 * } );
14130 * // Create a label.
14131 * var iconLabel = new OO.ui.LabelWidget( {
14132 * label: 'Help'
14133 * } );
14134 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14135 *
14136 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14137 *
14138 * @class
14139 * @extends OO.ui.Widget
14140 * @mixins OO.ui.mixin.IconElement
14141 * @mixins OO.ui.mixin.TitledElement
14142 * @mixins OO.ui.mixin.FlaggedElement
14143 *
14144 * @constructor
14145 * @param {Object} [config] Configuration options
14146 */
14147 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14148 // Configuration initialization
14149 config = config || {};
14150
14151 // Parent constructor
14152 OO.ui.IconWidget.parent.call( this, config );
14153
14154 // Mixin constructors
14155 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14156 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14157 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14158
14159 // Initialization
14160 this.$element.addClass( 'oo-ui-iconWidget' );
14161 };
14162
14163 /* Setup */
14164
14165 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14166 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14167 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14168 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14169
14170 /* Static Properties */
14171
14172 OO.ui.IconWidget.static.tagName = 'span';
14173
14174 /**
14175 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14176 * attention to the status of an item or to clarify the function of a control. For a list of
14177 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14178 *
14179 * @example
14180 * // Example of an indicator widget
14181 * var indicator1 = new OO.ui.IndicatorWidget( {
14182 * indicator: 'alert'
14183 * } );
14184 *
14185 * // Create a fieldset layout to add a label
14186 * var fieldset = new OO.ui.FieldsetLayout();
14187 * fieldset.addItems( [
14188 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14189 * ] );
14190 * $( 'body' ).append( fieldset.$element );
14191 *
14192 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14193 *
14194 * @class
14195 * @extends OO.ui.Widget
14196 * @mixins OO.ui.mixin.IndicatorElement
14197 * @mixins OO.ui.mixin.TitledElement
14198 *
14199 * @constructor
14200 * @param {Object} [config] Configuration options
14201 */
14202 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14203 // Configuration initialization
14204 config = config || {};
14205
14206 // Parent constructor
14207 OO.ui.IndicatorWidget.parent.call( this, config );
14208
14209 // Mixin constructors
14210 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14211 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14212
14213 // Initialization
14214 this.$element.addClass( 'oo-ui-indicatorWidget' );
14215 };
14216
14217 /* Setup */
14218
14219 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14220 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14221 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14222
14223 /* Static Properties */
14224
14225 OO.ui.IndicatorWidget.static.tagName = 'span';
14226
14227 /**
14228 * InputWidget is the base class for all input widgets, which
14229 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14230 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14231 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14232 *
14233 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14234 *
14235 * @abstract
14236 * @class
14237 * @extends OO.ui.Widget
14238 * @mixins OO.ui.mixin.FlaggedElement
14239 * @mixins OO.ui.mixin.TabIndexedElement
14240 * @mixins OO.ui.mixin.TitledElement
14241 * @mixins OO.ui.mixin.AccessKeyedElement
14242 *
14243 * @constructor
14244 * @param {Object} [config] Configuration options
14245 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14246 * @cfg {string} [value=''] The value of the input.
14247 * @cfg {string} [accessKey=''] The access key of the input.
14248 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14249 * before it is accepted.
14250 */
14251 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14252 // Configuration initialization
14253 config = config || {};
14254
14255 // Parent constructor
14256 OO.ui.InputWidget.parent.call( this, config );
14257
14258 // Properties
14259 this.$input = this.getInputElement( config );
14260 this.value = '';
14261 this.inputFilter = config.inputFilter;
14262
14263 // Mixin constructors
14264 OO.ui.mixin.FlaggedElement.call( this, config );
14265 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14266 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14267 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14268
14269 // Events
14270 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14271
14272 // Initialization
14273 this.$input
14274 .addClass( 'oo-ui-inputWidget-input' )
14275 .attr( 'name', config.name )
14276 .prop( 'disabled', this.isDisabled() );
14277 this.$element
14278 .addClass( 'oo-ui-inputWidget' )
14279 .append( this.$input );
14280 this.setValue( config.value );
14281 this.setAccessKey( config.accessKey );
14282 };
14283
14284 /* Setup */
14285
14286 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14287 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14288 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14289 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14290 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14291
14292 /* Static Properties */
14293
14294 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14295
14296 /* Events */
14297
14298 /**
14299 * @event change
14300 *
14301 * A change event is emitted when the value of the input changes.
14302 *
14303 * @param {string} value
14304 */
14305
14306 /* Methods */
14307
14308 /**
14309 * Get input element.
14310 *
14311 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14312 * different circumstances. The element must have a `value` property (like form elements).
14313 *
14314 * @protected
14315 * @param {Object} config Configuration options
14316 * @return {jQuery} Input element
14317 */
14318 OO.ui.InputWidget.prototype.getInputElement = function () {
14319 return $( '<input>' );
14320 };
14321
14322 /**
14323 * Handle potentially value-changing events.
14324 *
14325 * @private
14326 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14327 */
14328 OO.ui.InputWidget.prototype.onEdit = function () {
14329 var widget = this;
14330 if ( !this.isDisabled() ) {
14331 // Allow the stack to clear so the value will be updated
14332 setTimeout( function () {
14333 widget.setValue( widget.$input.val() );
14334 } );
14335 }
14336 };
14337
14338 /**
14339 * Get the value of the input.
14340 *
14341 * @return {string} Input value
14342 */
14343 OO.ui.InputWidget.prototype.getValue = function () {
14344 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14345 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14346 var value = this.$input.val();
14347 if ( this.value !== value ) {
14348 this.setValue( value );
14349 }
14350 return this.value;
14351 };
14352
14353 /**
14354 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14355 *
14356 * @param {boolean} isRTL
14357 * Direction is right-to-left
14358 */
14359 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14360 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14361 };
14362
14363 /**
14364 * Set the value of the input.
14365 *
14366 * @param {string} value New value
14367 * @fires change
14368 * @chainable
14369 */
14370 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14371 value = this.cleanUpValue( value );
14372 // Update the DOM if it has changed. Note that with cleanUpValue, it
14373 // is possible for the DOM value to change without this.value changing.
14374 if ( this.$input.val() !== value ) {
14375 this.$input.val( value );
14376 }
14377 if ( this.value !== value ) {
14378 this.value = value;
14379 this.emit( 'change', this.value );
14380 }
14381 return this;
14382 };
14383
14384 /**
14385 * Set the input's access key.
14386 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14387 *
14388 * @param {string} accessKey Input's access key, use empty string to remove
14389 * @chainable
14390 */
14391 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14392 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14393
14394 if ( this.accessKey !== accessKey ) {
14395 if ( this.$input ) {
14396 if ( accessKey !== null ) {
14397 this.$input.attr( 'accesskey', accessKey );
14398 } else {
14399 this.$input.removeAttr( 'accesskey' );
14400 }
14401 }
14402 this.accessKey = accessKey;
14403 }
14404
14405 return this;
14406 };
14407
14408 /**
14409 * Clean up incoming value.
14410 *
14411 * Ensures value is a string, and converts undefined and null to empty string.
14412 *
14413 * @private
14414 * @param {string} value Original value
14415 * @return {string} Cleaned up value
14416 */
14417 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14418 if ( value === undefined || value === null ) {
14419 return '';
14420 } else if ( this.inputFilter ) {
14421 return this.inputFilter( String( value ) );
14422 } else {
14423 return String( value );
14424 }
14425 };
14426
14427 /**
14428 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14429 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14430 * called directly.
14431 */
14432 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14433 if ( !this.isDisabled() ) {
14434 if ( this.$input.is( ':checkbox, :radio' ) ) {
14435 this.$input.click();
14436 }
14437 if ( this.$input.is( ':input' ) ) {
14438 this.$input[ 0 ].focus();
14439 }
14440 }
14441 };
14442
14443 /**
14444 * @inheritdoc
14445 */
14446 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14447 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14448 if ( this.$input ) {
14449 this.$input.prop( 'disabled', this.isDisabled() );
14450 }
14451 return this;
14452 };
14453
14454 /**
14455 * Focus the input.
14456 *
14457 * @chainable
14458 */
14459 OO.ui.InputWidget.prototype.focus = function () {
14460 this.$input[ 0 ].focus();
14461 return this;
14462 };
14463
14464 /**
14465 * Blur the input.
14466 *
14467 * @chainable
14468 */
14469 OO.ui.InputWidget.prototype.blur = function () {
14470 this.$input[ 0 ].blur();
14471 return this;
14472 };
14473
14474 /**
14475 * @inheritdoc
14476 */
14477 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14478 var
14479 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14480 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14481 state.value = $input.val();
14482 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14483 state.focus = $input.is( ':focus' );
14484 return state;
14485 };
14486
14487 /**
14488 * @inheritdoc
14489 */
14490 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14491 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14492 if ( state.value !== undefined && state.value !== this.getValue() ) {
14493 this.setValue( state.value );
14494 }
14495 if ( state.focus ) {
14496 this.focus();
14497 }
14498 };
14499
14500 /**
14501 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14502 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14503 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14504 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14505 * [OOjs UI documentation on MediaWiki] [1] for more information.
14506 *
14507 * @example
14508 * // A ButtonInputWidget rendered as an HTML button, the default.
14509 * var button = new OO.ui.ButtonInputWidget( {
14510 * label: 'Input button',
14511 * icon: 'check',
14512 * value: 'check'
14513 * } );
14514 * $( 'body' ).append( button.$element );
14515 *
14516 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14517 *
14518 * @class
14519 * @extends OO.ui.InputWidget
14520 * @mixins OO.ui.mixin.ButtonElement
14521 * @mixins OO.ui.mixin.IconElement
14522 * @mixins OO.ui.mixin.IndicatorElement
14523 * @mixins OO.ui.mixin.LabelElement
14524 * @mixins OO.ui.mixin.TitledElement
14525 *
14526 * @constructor
14527 * @param {Object} [config] Configuration options
14528 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14529 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14530 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14531 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14532 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14533 */
14534 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14535 // Configuration initialization
14536 config = $.extend( { type: 'button', useInputTag: false }, config );
14537
14538 // Properties (must be set before parent constructor, which calls #setValue)
14539 this.useInputTag = config.useInputTag;
14540
14541 // Parent constructor
14542 OO.ui.ButtonInputWidget.parent.call( this, config );
14543
14544 // Mixin constructors
14545 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14546 OO.ui.mixin.IconElement.call( this, config );
14547 OO.ui.mixin.IndicatorElement.call( this, config );
14548 OO.ui.mixin.LabelElement.call( this, config );
14549 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14550
14551 // Initialization
14552 if ( !config.useInputTag ) {
14553 this.$input.append( this.$icon, this.$label, this.$indicator );
14554 }
14555 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14556 };
14557
14558 /* Setup */
14559
14560 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14561 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14562 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14563 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14564 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14565 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14566
14567 /* Static Properties */
14568
14569 /**
14570 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14571 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14572 */
14573 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14574
14575 /* Methods */
14576
14577 /**
14578 * @inheritdoc
14579 * @protected
14580 */
14581 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14582 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14583 config.type :
14584 'button';
14585 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14586 };
14587
14588 /**
14589 * Set label value.
14590 *
14591 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14592 *
14593 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14594 * text, or `null` for no label
14595 * @chainable
14596 */
14597 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14598 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14599
14600 if ( this.useInputTag ) {
14601 if ( typeof label === 'function' ) {
14602 label = OO.ui.resolveMsg( label );
14603 }
14604 if ( label instanceof jQuery ) {
14605 label = label.text();
14606 }
14607 if ( !label ) {
14608 label = '';
14609 }
14610 this.$input.val( label );
14611 }
14612
14613 return this;
14614 };
14615
14616 /**
14617 * Set the value of the input.
14618 *
14619 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14620 * they do not support {@link #value values}.
14621 *
14622 * @param {string} value New value
14623 * @chainable
14624 */
14625 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14626 if ( !this.useInputTag ) {
14627 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14628 }
14629 return this;
14630 };
14631
14632 /**
14633 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14634 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14635 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14636 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14637 *
14638 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14639 *
14640 * @example
14641 * // An example of selected, unselected, and disabled checkbox inputs
14642 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14643 * value: 'a',
14644 * selected: true
14645 * } );
14646 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14647 * value: 'b'
14648 * } );
14649 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14650 * value:'c',
14651 * disabled: true
14652 * } );
14653 * // Create a fieldset layout with fields for each checkbox.
14654 * var fieldset = new OO.ui.FieldsetLayout( {
14655 * label: 'Checkboxes'
14656 * } );
14657 * fieldset.addItems( [
14658 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14659 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14660 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14661 * ] );
14662 * $( 'body' ).append( fieldset.$element );
14663 *
14664 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14665 *
14666 * @class
14667 * @extends OO.ui.InputWidget
14668 *
14669 * @constructor
14670 * @param {Object} [config] Configuration options
14671 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14672 */
14673 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14674 // Configuration initialization
14675 config = config || {};
14676
14677 // Parent constructor
14678 OO.ui.CheckboxInputWidget.parent.call( this, config );
14679
14680 // Initialization
14681 this.$element
14682 .addClass( 'oo-ui-checkboxInputWidget' )
14683 // Required for pretty styling in MediaWiki theme
14684 .append( $( '<span>' ) );
14685 this.setSelected( config.selected !== undefined ? config.selected : false );
14686 };
14687
14688 /* Setup */
14689
14690 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14691
14692 /* Methods */
14693
14694 /**
14695 * @inheritdoc
14696 * @protected
14697 */
14698 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14699 return $( '<input type="checkbox" />' );
14700 };
14701
14702 /**
14703 * @inheritdoc
14704 */
14705 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14706 var widget = this;
14707 if ( !this.isDisabled() ) {
14708 // Allow the stack to clear so the value will be updated
14709 setTimeout( function () {
14710 widget.setSelected( widget.$input.prop( 'checked' ) );
14711 } );
14712 }
14713 };
14714
14715 /**
14716 * Set selection state of this checkbox.
14717 *
14718 * @param {boolean} state `true` for selected
14719 * @chainable
14720 */
14721 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14722 state = !!state;
14723 if ( this.selected !== state ) {
14724 this.selected = state;
14725 this.$input.prop( 'checked', this.selected );
14726 this.emit( 'change', this.selected );
14727 }
14728 return this;
14729 };
14730
14731 /**
14732 * Check if this checkbox is selected.
14733 *
14734 * @return {boolean} Checkbox is selected
14735 */
14736 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14737 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14738 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14739 var selected = this.$input.prop( 'checked' );
14740 if ( this.selected !== selected ) {
14741 this.setSelected( selected );
14742 }
14743 return this.selected;
14744 };
14745
14746 /**
14747 * @inheritdoc
14748 */
14749 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14750 var
14751 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14752 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14753 state.$input = $input; // shortcut for performance, used in InputWidget
14754 state.checked = $input.prop( 'checked' );
14755 return state;
14756 };
14757
14758 /**
14759 * @inheritdoc
14760 */
14761 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14762 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14763 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14764 this.setSelected( state.checked );
14765 }
14766 };
14767
14768 /**
14769 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14770 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14771 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14772 * more information about input widgets.
14773 *
14774 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14775 * are no options. If no `value` configuration option is provided, the first option is selected.
14776 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14777 *
14778 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14779 *
14780 * @example
14781 * // Example: A DropdownInputWidget with three options
14782 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14783 * options: [
14784 * { data: 'a', label: 'First' },
14785 * { data: 'b', label: 'Second'},
14786 * { data: 'c', label: 'Third' }
14787 * ]
14788 * } );
14789 * $( 'body' ).append( dropdownInput.$element );
14790 *
14791 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14792 *
14793 * @class
14794 * @extends OO.ui.InputWidget
14795 * @mixins OO.ui.mixin.TitledElement
14796 *
14797 * @constructor
14798 * @param {Object} [config] Configuration options
14799 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14800 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
14801 */
14802 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
14803 // Configuration initialization
14804 config = config || {};
14805
14806 // Properties (must be done before parent constructor which calls #setDisabled)
14807 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
14808
14809 // Parent constructor
14810 OO.ui.DropdownInputWidget.parent.call( this, config );
14811
14812 // Mixin constructors
14813 OO.ui.mixin.TitledElement.call( this, config );
14814
14815 // Events
14816 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
14817
14818 // Initialization
14819 this.setOptions( config.options || [] );
14820 this.$element
14821 .addClass( 'oo-ui-dropdownInputWidget' )
14822 .append( this.dropdownWidget.$element );
14823 };
14824
14825 /* Setup */
14826
14827 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
14828 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
14829
14830 /* Methods */
14831
14832 /**
14833 * @inheritdoc
14834 * @protected
14835 */
14836 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
14837 return $( '<input type="hidden">' );
14838 };
14839
14840 /**
14841 * Handles menu select events.
14842 *
14843 * @private
14844 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14845 */
14846 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
14847 this.setValue( item.getData() );
14848 };
14849
14850 /**
14851 * @inheritdoc
14852 */
14853 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
14854 value = this.cleanUpValue( value );
14855 this.dropdownWidget.getMenu().selectItemByData( value );
14856 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
14857 return this;
14858 };
14859
14860 /**
14861 * @inheritdoc
14862 */
14863 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
14864 this.dropdownWidget.setDisabled( state );
14865 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
14866 return this;
14867 };
14868
14869 /**
14870 * Set the options available for this input.
14871 *
14872 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14873 * @chainable
14874 */
14875 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
14876 var
14877 value = this.getValue(),
14878 widget = this;
14879
14880 // Rebuild the dropdown menu
14881 this.dropdownWidget.getMenu()
14882 .clearItems()
14883 .addItems( options.map( function ( opt ) {
14884 var optValue = widget.cleanUpValue( opt.data );
14885 return new OO.ui.MenuOptionWidget( {
14886 data: optValue,
14887 label: opt.label !== undefined ? opt.label : optValue
14888 } );
14889 } ) );
14890
14891 // Restore the previous value, or reset to something sensible
14892 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
14893 // Previous value is still available, ensure consistency with the dropdown
14894 this.setValue( value );
14895 } else {
14896 // No longer valid, reset
14897 if ( options.length ) {
14898 this.setValue( options[ 0 ].data );
14899 }
14900 }
14901
14902 return this;
14903 };
14904
14905 /**
14906 * @inheritdoc
14907 */
14908 OO.ui.DropdownInputWidget.prototype.focus = function () {
14909 this.dropdownWidget.getMenu().toggle( true );
14910 return this;
14911 };
14912
14913 /**
14914 * @inheritdoc
14915 */
14916 OO.ui.DropdownInputWidget.prototype.blur = function () {
14917 this.dropdownWidget.getMenu().toggle( false );
14918 return this;
14919 };
14920
14921 /**
14922 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14923 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14924 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14925 * please see the [OOjs UI documentation on MediaWiki][1].
14926 *
14927 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14928 *
14929 * @example
14930 * // An example of selected, unselected, and disabled radio inputs
14931 * var radio1 = new OO.ui.RadioInputWidget( {
14932 * value: 'a',
14933 * selected: true
14934 * } );
14935 * var radio2 = new OO.ui.RadioInputWidget( {
14936 * value: 'b'
14937 * } );
14938 * var radio3 = new OO.ui.RadioInputWidget( {
14939 * value: 'c',
14940 * disabled: true
14941 * } );
14942 * // Create a fieldset layout with fields for each radio button.
14943 * var fieldset = new OO.ui.FieldsetLayout( {
14944 * label: 'Radio inputs'
14945 * } );
14946 * fieldset.addItems( [
14947 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14948 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14949 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14950 * ] );
14951 * $( 'body' ).append( fieldset.$element );
14952 *
14953 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14954 *
14955 * @class
14956 * @extends OO.ui.InputWidget
14957 *
14958 * @constructor
14959 * @param {Object} [config] Configuration options
14960 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14961 */
14962 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
14963 // Configuration initialization
14964 config = config || {};
14965
14966 // Parent constructor
14967 OO.ui.RadioInputWidget.parent.call( this, config );
14968
14969 // Initialization
14970 this.$element
14971 .addClass( 'oo-ui-radioInputWidget' )
14972 // Required for pretty styling in MediaWiki theme
14973 .append( $( '<span>' ) );
14974 this.setSelected( config.selected !== undefined ? config.selected : false );
14975 };
14976
14977 /* Setup */
14978
14979 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
14980
14981 /* Methods */
14982
14983 /**
14984 * @inheritdoc
14985 * @protected
14986 */
14987 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
14988 return $( '<input type="radio" />' );
14989 };
14990
14991 /**
14992 * @inheritdoc
14993 */
14994 OO.ui.RadioInputWidget.prototype.onEdit = function () {
14995 // RadioInputWidget doesn't track its state.
14996 };
14997
14998 /**
14999 * Set selection state of this radio button.
15000 *
15001 * @param {boolean} state `true` for selected
15002 * @chainable
15003 */
15004 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
15005 // RadioInputWidget doesn't track its state.
15006 this.$input.prop( 'checked', state );
15007 return this;
15008 };
15009
15010 /**
15011 * Check if this radio button is selected.
15012 *
15013 * @return {boolean} Radio is selected
15014 */
15015 OO.ui.RadioInputWidget.prototype.isSelected = function () {
15016 return this.$input.prop( 'checked' );
15017 };
15018
15019 /**
15020 * @inheritdoc
15021 */
15022 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15023 var
15024 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15025 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15026 state.$input = $input; // shortcut for performance, used in InputWidget
15027 state.checked = $input.prop( 'checked' );
15028 return state;
15029 };
15030
15031 /**
15032 * @inheritdoc
15033 */
15034 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15035 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15036 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15037 this.setSelected( state.checked );
15038 }
15039 };
15040
15041 /**
15042 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15043 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15044 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15045 * more information about input widgets.
15046 *
15047 * This and OO.ui.DropdownInputWidget support the same configuration options.
15048 *
15049 * @example
15050 * // Example: A RadioSelectInputWidget with three options
15051 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15052 * options: [
15053 * { data: 'a', label: 'First' },
15054 * { data: 'b', label: 'Second'},
15055 * { data: 'c', label: 'Third' }
15056 * ]
15057 * } );
15058 * $( 'body' ).append( radioSelectInput.$element );
15059 *
15060 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15061 *
15062 * @class
15063 * @extends OO.ui.InputWidget
15064 *
15065 * @constructor
15066 * @param {Object} [config] Configuration options
15067 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15068 */
15069 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15070 // Configuration initialization
15071 config = config || {};
15072
15073 // Properties (must be done before parent constructor which calls #setDisabled)
15074 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15075
15076 // Parent constructor
15077 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15078
15079 // Events
15080 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15081
15082 // Initialization
15083 this.setOptions( config.options || [] );
15084 this.$element
15085 .addClass( 'oo-ui-radioSelectInputWidget' )
15086 .append( this.radioSelectWidget.$element );
15087 };
15088
15089 /* Setup */
15090
15091 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15092
15093 /* Static Properties */
15094
15095 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15096
15097 /* Methods */
15098
15099 /**
15100 * @inheritdoc
15101 * @protected
15102 */
15103 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15104 return $( '<input type="hidden">' );
15105 };
15106
15107 /**
15108 * Handles menu select events.
15109 *
15110 * @private
15111 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15112 */
15113 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15114 this.setValue( item.getData() );
15115 };
15116
15117 /**
15118 * @inheritdoc
15119 */
15120 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15121 value = this.cleanUpValue( value );
15122 this.radioSelectWidget.selectItemByData( value );
15123 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15124 return this;
15125 };
15126
15127 /**
15128 * @inheritdoc
15129 */
15130 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15131 this.radioSelectWidget.setDisabled( state );
15132 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15133 return this;
15134 };
15135
15136 /**
15137 * Set the options available for this input.
15138 *
15139 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15140 * @chainable
15141 */
15142 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15143 var
15144 value = this.getValue(),
15145 widget = this;
15146
15147 // Rebuild the radioSelect menu
15148 this.radioSelectWidget
15149 .clearItems()
15150 .addItems( options.map( function ( opt ) {
15151 var optValue = widget.cleanUpValue( opt.data );
15152 return new OO.ui.RadioOptionWidget( {
15153 data: optValue,
15154 label: opt.label !== undefined ? opt.label : optValue
15155 } );
15156 } ) );
15157
15158 // Restore the previous value, or reset to something sensible
15159 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15160 // Previous value is still available, ensure consistency with the radioSelect
15161 this.setValue( value );
15162 } else {
15163 // No longer valid, reset
15164 if ( options.length ) {
15165 this.setValue( options[ 0 ].data );
15166 }
15167 }
15168
15169 return this;
15170 };
15171
15172 /**
15173 * @inheritdoc
15174 */
15175 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15176 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15177 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15178 return state;
15179 };
15180
15181 /**
15182 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15183 * size of the field as well as its presentation. In addition, these widgets can be configured
15184 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15185 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15186 * which modifies incoming values rather than validating them.
15187 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15188 *
15189 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15190 *
15191 * @example
15192 * // Example of a text input widget
15193 * var textInput = new OO.ui.TextInputWidget( {
15194 * value: 'Text input'
15195 * } )
15196 * $( 'body' ).append( textInput.$element );
15197 *
15198 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15199 *
15200 * @class
15201 * @extends OO.ui.InputWidget
15202 * @mixins OO.ui.mixin.IconElement
15203 * @mixins OO.ui.mixin.IndicatorElement
15204 * @mixins OO.ui.mixin.PendingElement
15205 * @mixins OO.ui.mixin.LabelElement
15206 *
15207 * @constructor
15208 * @param {Object} [config] Configuration options
15209 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15210 * 'email' or 'url'. Ignored if `multiline` is true.
15211 *
15212 * Some values of `type` result in additional behaviors:
15213 *
15214 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15215 * empties the text field
15216 * @cfg {string} [placeholder] Placeholder text
15217 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15218 * instruct the browser to focus this widget.
15219 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15220 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15221 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15222 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15223 * specifies minimum number of rows to display.
15224 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15225 * Use the #maxRows config to specify a maximum number of displayed rows.
15226 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15227 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15228 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15229 * the value or placeholder text: `'before'` or `'after'`
15230 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15231 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15232 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15233 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15234 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15235 * value for it to be considered valid; when Function, a function receiving the value as parameter
15236 * that must return true, or promise resolving to true, for it to be considered valid.
15237 */
15238 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15239 // Configuration initialization
15240 config = $.extend( {
15241 type: 'text',
15242 labelPosition: 'after'
15243 }, config );
15244 if ( config.type === 'search' ) {
15245 if ( config.icon === undefined ) {
15246 config.icon = 'search';
15247 }
15248 // indicator: 'clear' is set dynamically later, depending on value
15249 }
15250 if ( config.required ) {
15251 if ( config.indicator === undefined ) {
15252 config.indicator = 'required';
15253 }
15254 }
15255
15256 // Parent constructor
15257 OO.ui.TextInputWidget.parent.call( this, config );
15258
15259 // Mixin constructors
15260 OO.ui.mixin.IconElement.call( this, config );
15261 OO.ui.mixin.IndicatorElement.call( this, config );
15262 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15263 OO.ui.mixin.LabelElement.call( this, config );
15264
15265 // Properties
15266 this.type = this.getSaneType( config );
15267 this.readOnly = false;
15268 this.multiline = !!config.multiline;
15269 this.autosize = !!config.autosize;
15270 this.minRows = config.rows !== undefined ? config.rows : '';
15271 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15272 this.validate = null;
15273
15274 // Clone for resizing
15275 if ( this.autosize ) {
15276 this.$clone = this.$input
15277 .clone()
15278 .insertAfter( this.$input )
15279 .attr( 'aria-hidden', 'true' )
15280 .addClass( 'oo-ui-element-hidden' );
15281 }
15282
15283 this.setValidation( config.validate );
15284 this.setLabelPosition( config.labelPosition );
15285
15286 // Events
15287 this.$input.on( {
15288 keypress: this.onKeyPress.bind( this ),
15289 blur: this.onBlur.bind( this )
15290 } );
15291 this.$input.one( {
15292 focus: this.onElementAttach.bind( this )
15293 } );
15294 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15295 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15296 this.on( 'labelChange', this.updatePosition.bind( this ) );
15297 this.connect( this, {
15298 change: 'onChange',
15299 disable: 'onDisable'
15300 } );
15301
15302 // Initialization
15303 this.$element
15304 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15305 .append( this.$icon, this.$indicator );
15306 this.setReadOnly( !!config.readOnly );
15307 this.updateSearchIndicator();
15308 if ( config.placeholder ) {
15309 this.$input.attr( 'placeholder', config.placeholder );
15310 }
15311 if ( config.maxLength !== undefined ) {
15312 this.$input.attr( 'maxlength', config.maxLength );
15313 }
15314 if ( config.autofocus ) {
15315 this.$input.attr( 'autofocus', 'autofocus' );
15316 }
15317 if ( config.required ) {
15318 this.$input.attr( 'required', 'required' );
15319 this.$input.attr( 'aria-required', 'true' );
15320 }
15321 if ( config.autocomplete === false ) {
15322 this.$input.attr( 'autocomplete', 'off' );
15323 }
15324 if ( this.multiline && config.rows ) {
15325 this.$input.attr( 'rows', config.rows );
15326 }
15327 if ( this.label || config.autosize ) {
15328 this.installParentChangeDetector();
15329 }
15330 };
15331
15332 /* Setup */
15333
15334 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15335 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15336 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15337 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15338 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15339
15340 /* Static Properties */
15341
15342 OO.ui.TextInputWidget.static.validationPatterns = {
15343 'non-empty': /.+/,
15344 integer: /^\d+$/
15345 };
15346
15347 /* Events */
15348
15349 /**
15350 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15351 *
15352 * Not emitted if the input is multiline.
15353 *
15354 * @event enter
15355 */
15356
15357 /* Methods */
15358
15359 /**
15360 * Handle icon mouse down events.
15361 *
15362 * @private
15363 * @param {jQuery.Event} e Mouse down event
15364 * @fires icon
15365 */
15366 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15367 if ( e.which === 1 ) {
15368 this.$input[ 0 ].focus();
15369 return false;
15370 }
15371 };
15372
15373 /**
15374 * Handle indicator mouse down events.
15375 *
15376 * @private
15377 * @param {jQuery.Event} e Mouse down event
15378 * @fires indicator
15379 */
15380 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15381 if ( e.which === 1 ) {
15382 if ( this.type === 'search' ) {
15383 // Clear the text field
15384 this.setValue( '' );
15385 }
15386 this.$input[ 0 ].focus();
15387 return false;
15388 }
15389 };
15390
15391 /**
15392 * Handle key press events.
15393 *
15394 * @private
15395 * @param {jQuery.Event} e Key press event
15396 * @fires enter If enter key is pressed and input is not multiline
15397 */
15398 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15399 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15400 this.emit( 'enter', e );
15401 }
15402 };
15403
15404 /**
15405 * Handle blur events.
15406 *
15407 * @private
15408 * @param {jQuery.Event} e Blur event
15409 */
15410 OO.ui.TextInputWidget.prototype.onBlur = function () {
15411 this.setValidityFlag();
15412 };
15413
15414 /**
15415 * Handle element attach events.
15416 *
15417 * @private
15418 * @param {jQuery.Event} e Element attach event
15419 */
15420 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15421 // Any previously calculated size is now probably invalid if we reattached elsewhere
15422 this.valCache = null;
15423 this.adjustSize();
15424 this.positionLabel();
15425 };
15426
15427 /**
15428 * Handle change events.
15429 *
15430 * @param {string} value
15431 * @private
15432 */
15433 OO.ui.TextInputWidget.prototype.onChange = function () {
15434 this.updateSearchIndicator();
15435 this.setValidityFlag();
15436 this.adjustSize();
15437 };
15438
15439 /**
15440 * Handle disable events.
15441 *
15442 * @param {boolean} disabled Element is disabled
15443 * @private
15444 */
15445 OO.ui.TextInputWidget.prototype.onDisable = function () {
15446 this.updateSearchIndicator();
15447 };
15448
15449 /**
15450 * Check if the input is {@link #readOnly read-only}.
15451 *
15452 * @return {boolean}
15453 */
15454 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15455 return this.readOnly;
15456 };
15457
15458 /**
15459 * Set the {@link #readOnly read-only} state of the input.
15460 *
15461 * @param {boolean} state Make input read-only
15462 * @chainable
15463 */
15464 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15465 this.readOnly = !!state;
15466 this.$input.prop( 'readOnly', this.readOnly );
15467 this.updateSearchIndicator();
15468 return this;
15469 };
15470
15471 /**
15472 * Support function for making #onElementAttach work across browsers.
15473 *
15474 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15475 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15476 *
15477 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15478 * first time that the element gets attached to the documented.
15479 */
15480 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15481 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15482 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15483 widget = this;
15484
15485 if ( MutationObserver ) {
15486 // The new way. If only it wasn't so ugly.
15487
15488 if ( this.$element.closest( 'html' ).length ) {
15489 // Widget is attached already, do nothing. This breaks the functionality of this function when
15490 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15491 // would require observation of the whole document, which would hurt performance of other,
15492 // more important code.
15493 return;
15494 }
15495
15496 // Find topmost node in the tree
15497 topmostNode = this.$element[ 0 ];
15498 while ( topmostNode.parentNode ) {
15499 topmostNode = topmostNode.parentNode;
15500 }
15501
15502 // We have no way to detect the $element being attached somewhere without observing the entire
15503 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15504 // parent node of $element, and instead detect when $element is removed from it (and thus
15505 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15506 // doesn't get attached, we end up back here and create the parent.
15507
15508 mutationObserver = new MutationObserver( function ( mutations ) {
15509 var i, j, removedNodes;
15510 for ( i = 0; i < mutations.length; i++ ) {
15511 removedNodes = mutations[ i ].removedNodes;
15512 for ( j = 0; j < removedNodes.length; j++ ) {
15513 if ( removedNodes[ j ] === topmostNode ) {
15514 setTimeout( onRemove, 0 );
15515 return;
15516 }
15517 }
15518 }
15519 } );
15520
15521 onRemove = function () {
15522 // If the node was attached somewhere else, report it
15523 if ( widget.$element.closest( 'html' ).length ) {
15524 widget.onElementAttach();
15525 }
15526 mutationObserver.disconnect();
15527 widget.installParentChangeDetector();
15528 };
15529
15530 // Create a fake parent and observe it
15531 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15532 mutationObserver.observe( fakeParentNode, { childList: true } );
15533 } else {
15534 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15535 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15536 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15537 }
15538 };
15539
15540 /**
15541 * Automatically adjust the size of the text input.
15542 *
15543 * This only affects #multiline inputs that are {@link #autosize autosized}.
15544 *
15545 * @chainable
15546 */
15547 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15548 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15549
15550 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15551 this.$clone
15552 .val( this.$input.val() )
15553 .attr( 'rows', this.minRows )
15554 // Set inline height property to 0 to measure scroll height
15555 .css( 'height', 0 );
15556
15557 this.$clone.removeClass( 'oo-ui-element-hidden' );
15558
15559 this.valCache = this.$input.val();
15560
15561 scrollHeight = this.$clone[ 0 ].scrollHeight;
15562
15563 // Remove inline height property to measure natural heights
15564 this.$clone.css( 'height', '' );
15565 innerHeight = this.$clone.innerHeight();
15566 outerHeight = this.$clone.outerHeight();
15567
15568 // Measure max rows height
15569 this.$clone
15570 .attr( 'rows', this.maxRows )
15571 .css( 'height', 'auto' )
15572 .val( '' );
15573 maxInnerHeight = this.$clone.innerHeight();
15574
15575 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15576 // Equals 1 on Blink-based browsers and 0 everywhere else
15577 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15578 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15579
15580 this.$clone.addClass( 'oo-ui-element-hidden' );
15581
15582 // Only apply inline height when expansion beyond natural height is needed
15583 if ( idealHeight > innerHeight ) {
15584 // Use the difference between the inner and outer height as a buffer
15585 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15586 } else {
15587 this.$input.css( 'height', '' );
15588 }
15589 }
15590 return this;
15591 };
15592
15593 /**
15594 * @inheritdoc
15595 * @protected
15596 */
15597 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15598 return config.multiline ?
15599 $( '<textarea>' ) :
15600 $( '<input type="' + this.getSaneType( config ) + '" />' );
15601 };
15602
15603 /**
15604 * Get sanitized value for 'type' for given config.
15605 *
15606 * @param {Object} config Configuration options
15607 * @return {string|null}
15608 * @private
15609 */
15610 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15611 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15612 config.type :
15613 'text';
15614 return config.multiline ? 'multiline' : type;
15615 };
15616
15617 /**
15618 * Check if the input supports multiple lines.
15619 *
15620 * @return {boolean}
15621 */
15622 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15623 return !!this.multiline;
15624 };
15625
15626 /**
15627 * Check if the input automatically adjusts its size.
15628 *
15629 * @return {boolean}
15630 */
15631 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15632 return !!this.autosize;
15633 };
15634
15635 /**
15636 * Select the entire text of the input.
15637 *
15638 * @chainable
15639 */
15640 OO.ui.TextInputWidget.prototype.select = function () {
15641 this.$input.select();
15642 return this;
15643 };
15644
15645 /**
15646 * Focus the input and move the cursor to the end.
15647 */
15648 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15649 var textRange,
15650 element = this.$input[ 0 ];
15651 this.focus();
15652 if ( element.selectionStart !== undefined ) {
15653 element.selectionStart = element.selectionEnd = element.value.length;
15654 } else if ( element.createTextRange ) {
15655 // IE 8 and below
15656 textRange = element.createTextRange();
15657 textRange.collapse( false );
15658 textRange.select();
15659 }
15660 };
15661
15662 /**
15663 * Set the validation pattern.
15664 *
15665 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15666 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15667 * value must contain only numbers).
15668 *
15669 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15670 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15671 */
15672 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15673 if ( validate instanceof RegExp || validate instanceof Function ) {
15674 this.validate = validate;
15675 } else {
15676 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15677 }
15678 };
15679
15680 /**
15681 * Sets the 'invalid' flag appropriately.
15682 *
15683 * @param {boolean} [isValid] Optionally override validation result
15684 */
15685 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15686 var widget = this,
15687 setFlag = function ( valid ) {
15688 if ( !valid ) {
15689 widget.$input.attr( 'aria-invalid', 'true' );
15690 } else {
15691 widget.$input.removeAttr( 'aria-invalid' );
15692 }
15693 widget.setFlags( { invalid: !valid } );
15694 };
15695
15696 if ( isValid !== undefined ) {
15697 setFlag( isValid );
15698 } else {
15699 this.getValidity().then( function () {
15700 setFlag( true );
15701 }, function () {
15702 setFlag( false );
15703 } );
15704 }
15705 };
15706
15707 /**
15708 * Check if a value is valid.
15709 *
15710 * This method returns a promise that resolves with a boolean `true` if the current value is
15711 * considered valid according to the supplied {@link #validate validation pattern}.
15712 *
15713 * @deprecated
15714 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15715 */
15716 OO.ui.TextInputWidget.prototype.isValid = function () {
15717 var result;
15718
15719 if ( this.validate instanceof Function ) {
15720 result = this.validate( this.getValue() );
15721 if ( $.isFunction( result.promise ) ) {
15722 return result.promise();
15723 } else {
15724 return $.Deferred().resolve( !!result ).promise();
15725 }
15726 } else {
15727 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15728 }
15729 };
15730
15731 /**
15732 * Get the validity of current value.
15733 *
15734 * This method returns a promise that resolves if the value is valid and rejects if
15735 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15736 *
15737 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15738 */
15739 OO.ui.TextInputWidget.prototype.getValidity = function () {
15740 var result, promise;
15741
15742 function rejectOrResolve( valid ) {
15743 if ( valid ) {
15744 return $.Deferred().resolve().promise();
15745 } else {
15746 return $.Deferred().reject().promise();
15747 }
15748 }
15749
15750 if ( this.validate instanceof Function ) {
15751 result = this.validate( this.getValue() );
15752
15753 if ( $.isFunction( result.promise ) ) {
15754 promise = $.Deferred();
15755
15756 result.then( function ( valid ) {
15757 if ( valid ) {
15758 promise.resolve();
15759 } else {
15760 promise.reject();
15761 }
15762 }, function () {
15763 promise.reject();
15764 } );
15765
15766 return promise.promise();
15767 } else {
15768 return rejectOrResolve( result );
15769 }
15770 } else {
15771 return rejectOrResolve( this.getValue().match( this.validate ) );
15772 }
15773 };
15774
15775 /**
15776 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15777 *
15778 * @param {string} labelPosition Label position, 'before' or 'after'
15779 * @chainable
15780 */
15781 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
15782 this.labelPosition = labelPosition;
15783 this.updatePosition();
15784 return this;
15785 };
15786
15787 /**
15788 * Deprecated alias of #setLabelPosition
15789 *
15790 * @deprecated Use setLabelPosition instead.
15791 */
15792 OO.ui.TextInputWidget.prototype.setPosition =
15793 OO.ui.TextInputWidget.prototype.setLabelPosition;
15794
15795 /**
15796 * Update the position of the inline label.
15797 *
15798 * This method is called by #setLabelPosition, and can also be called on its own if
15799 * something causes the label to be mispositioned.
15800 *
15801 * @chainable
15802 */
15803 OO.ui.TextInputWidget.prototype.updatePosition = function () {
15804 var after = this.labelPosition === 'after';
15805
15806 this.$element
15807 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
15808 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
15809
15810 this.positionLabel();
15811
15812 return this;
15813 };
15814
15815 /**
15816 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15817 * already empty or when it's not editable.
15818 */
15819 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
15820 if ( this.type === 'search' ) {
15821 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15822 this.setIndicator( null );
15823 } else {
15824 this.setIndicator( 'clear' );
15825 }
15826 }
15827 };
15828
15829 /**
15830 * Position the label by setting the correct padding on the input.
15831 *
15832 * @private
15833 * @chainable
15834 */
15835 OO.ui.TextInputWidget.prototype.positionLabel = function () {
15836 var after, rtl, property;
15837 // Clear old values
15838 this.$input
15839 // Clear old values if present
15840 .css( {
15841 'padding-right': '',
15842 'padding-left': ''
15843 } );
15844
15845 if ( this.label ) {
15846 this.$element.append( this.$label );
15847 } else {
15848 this.$label.detach();
15849 return;
15850 }
15851
15852 after = this.labelPosition === 'after';
15853 rtl = this.$element.css( 'direction' ) === 'rtl';
15854 property = after === rtl ? 'padding-left' : 'padding-right';
15855
15856 this.$input.css( property, this.$label.outerWidth( true ) );
15857
15858 return this;
15859 };
15860
15861 /**
15862 * @inheritdoc
15863 */
15864 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15865 var
15866 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15867 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15868 state.$input = $input; // shortcut for performance, used in InputWidget
15869 if ( this.multiline ) {
15870 state.scrollTop = $input.scrollTop();
15871 }
15872 return state;
15873 };
15874
15875 /**
15876 * @inheritdoc
15877 */
15878 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
15879 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15880 if ( state.scrollTop !== undefined ) {
15881 this.$input.scrollTop( state.scrollTop );
15882 }
15883 };
15884
15885 /**
15886 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15887 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15888 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15889 *
15890 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15891 * option, that option will appear to be selected.
15892 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15893 * input field.
15894 *
15895 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15896 *
15897 * @example
15898 * // Example: A ComboBoxWidget.
15899 * var comboBox = new OO.ui.ComboBoxWidget( {
15900 * label: 'ComboBoxWidget',
15901 * input: { value: 'Option One' },
15902 * menu: {
15903 * items: [
15904 * new OO.ui.MenuOptionWidget( {
15905 * data: 'Option 1',
15906 * label: 'Option One'
15907 * } ),
15908 * new OO.ui.MenuOptionWidget( {
15909 * data: 'Option 2',
15910 * label: 'Option Two'
15911 * } ),
15912 * new OO.ui.MenuOptionWidget( {
15913 * data: 'Option 3',
15914 * label: 'Option Three'
15915 * } ),
15916 * new OO.ui.MenuOptionWidget( {
15917 * data: 'Option 4',
15918 * label: 'Option Four'
15919 * } ),
15920 * new OO.ui.MenuOptionWidget( {
15921 * data: 'Option 5',
15922 * label: 'Option Five'
15923 * } )
15924 * ]
15925 * }
15926 * } );
15927 * $( 'body' ).append( comboBox.$element );
15928 *
15929 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15930 *
15931 * @class
15932 * @extends OO.ui.Widget
15933 * @mixins OO.ui.mixin.TabIndexedElement
15934 *
15935 * @constructor
15936 * @param {Object} [config] Configuration options
15937 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15938 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15939 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15940 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15941 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15942 */
15943 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
15944 // Configuration initialization
15945 config = config || {};
15946
15947 // Parent constructor
15948 OO.ui.ComboBoxWidget.parent.call( this, config );
15949
15950 // Properties (must be set before TabIndexedElement constructor call)
15951 this.$indicator = this.$( '<span>' );
15952
15953 // Mixin constructors
15954 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
15955
15956 // Properties
15957 this.$overlay = config.$overlay || this.$element;
15958 this.input = new OO.ui.TextInputWidget( $.extend(
15959 {
15960 indicator: 'down',
15961 $indicator: this.$indicator,
15962 disabled: this.isDisabled()
15963 },
15964 config.input
15965 ) );
15966 this.input.$input.eq( 0 ).attr( {
15967 role: 'combobox',
15968 'aria-autocomplete': 'list'
15969 } );
15970 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
15971 {
15972 widget: this,
15973 input: this.input,
15974 $container: this.input.$element,
15975 disabled: this.isDisabled()
15976 },
15977 config.menu
15978 ) );
15979
15980 // Events
15981 this.$indicator.on( {
15982 click: this.onClick.bind( this ),
15983 keypress: this.onKeyPress.bind( this )
15984 } );
15985 this.input.connect( this, {
15986 change: 'onInputChange',
15987 enter: 'onInputEnter'
15988 } );
15989 this.menu.connect( this, {
15990 choose: 'onMenuChoose',
15991 add: 'onMenuItemsChange',
15992 remove: 'onMenuItemsChange'
15993 } );
15994
15995 // Initialization
15996 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
15997 this.$overlay.append( this.menu.$element );
15998 this.onMenuItemsChange();
15999 };
16000
16001 /* Setup */
16002
16003 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
16004 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
16005
16006 /* Methods */
16007
16008 /**
16009 * Get the combobox's menu.
16010 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16011 */
16012 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
16013 return this.menu;
16014 };
16015
16016 /**
16017 * Get the combobox's text input widget.
16018 * @return {OO.ui.TextInputWidget} Text input widget
16019 */
16020 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16021 return this.input;
16022 };
16023
16024 /**
16025 * Handle input change events.
16026 *
16027 * @private
16028 * @param {string} value New value
16029 */
16030 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16031 var match = this.menu.getItemFromData( value );
16032
16033 this.menu.selectItem( match );
16034 if ( this.menu.getHighlightedItem() ) {
16035 this.menu.highlightItem( match );
16036 }
16037
16038 if ( !this.isDisabled() ) {
16039 this.menu.toggle( true );
16040 }
16041 };
16042
16043 /**
16044 * Handle mouse click events.
16045 *
16046 *
16047 * @private
16048 * @param {jQuery.Event} e Mouse click event
16049 */
16050 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16051 if ( !this.isDisabled() && e.which === 1 ) {
16052 this.menu.toggle();
16053 this.input.$input[ 0 ].focus();
16054 }
16055 return false;
16056 };
16057
16058 /**
16059 * Handle key press events.
16060 *
16061 *
16062 * @private
16063 * @param {jQuery.Event} e Key press event
16064 */
16065 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16066 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16067 this.menu.toggle();
16068 this.input.$input[ 0 ].focus();
16069 return false;
16070 }
16071 };
16072
16073 /**
16074 * Handle input enter events.
16075 *
16076 * @private
16077 */
16078 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16079 if ( !this.isDisabled() ) {
16080 this.menu.toggle( false );
16081 }
16082 };
16083
16084 /**
16085 * Handle menu choose events.
16086 *
16087 * @private
16088 * @param {OO.ui.OptionWidget} item Chosen item
16089 */
16090 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16091 this.input.setValue( item.getData() );
16092 };
16093
16094 /**
16095 * Handle menu item change events.
16096 *
16097 * @private
16098 */
16099 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16100 var match = this.menu.getItemFromData( this.input.getValue() );
16101 this.menu.selectItem( match );
16102 if ( this.menu.getHighlightedItem() ) {
16103 this.menu.highlightItem( match );
16104 }
16105 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16106 };
16107
16108 /**
16109 * @inheritdoc
16110 */
16111 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16112 // Parent method
16113 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16114
16115 if ( this.input ) {
16116 this.input.setDisabled( this.isDisabled() );
16117 }
16118 if ( this.menu ) {
16119 this.menu.setDisabled( this.isDisabled() );
16120 }
16121
16122 return this;
16123 };
16124
16125 /**
16126 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16127 * be configured with a `label` option that is set to a string, a label node, or a function:
16128 *
16129 * - String: a plaintext string
16130 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16131 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16132 * - Function: a function that will produce a string in the future. Functions are used
16133 * in cases where the value of the label is not currently defined.
16134 *
16135 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16136 * will come into focus when the label is clicked.
16137 *
16138 * @example
16139 * // Examples of LabelWidgets
16140 * var label1 = new OO.ui.LabelWidget( {
16141 * label: 'plaintext label'
16142 * } );
16143 * var label2 = new OO.ui.LabelWidget( {
16144 * label: $( '<a href="default.html">jQuery label</a>' )
16145 * } );
16146 * // Create a fieldset layout with fields for each example
16147 * var fieldset = new OO.ui.FieldsetLayout();
16148 * fieldset.addItems( [
16149 * new OO.ui.FieldLayout( label1 ),
16150 * new OO.ui.FieldLayout( label2 )
16151 * ] );
16152 * $( 'body' ).append( fieldset.$element );
16153 *
16154 *
16155 * @class
16156 * @extends OO.ui.Widget
16157 * @mixins OO.ui.mixin.LabelElement
16158 *
16159 * @constructor
16160 * @param {Object} [config] Configuration options
16161 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16162 * Clicking the label will focus the specified input field.
16163 */
16164 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16165 // Configuration initialization
16166 config = config || {};
16167
16168 // Parent constructor
16169 OO.ui.LabelWidget.parent.call( this, config );
16170
16171 // Mixin constructors
16172 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16173 OO.ui.mixin.TitledElement.call( this, config );
16174
16175 // Properties
16176 this.input = config.input;
16177
16178 // Events
16179 if ( this.input instanceof OO.ui.InputWidget ) {
16180 this.$element.on( 'click', this.onClick.bind( this ) );
16181 }
16182
16183 // Initialization
16184 this.$element.addClass( 'oo-ui-labelWidget' );
16185 };
16186
16187 /* Setup */
16188
16189 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16190 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16191 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16192
16193 /* Static Properties */
16194
16195 OO.ui.LabelWidget.static.tagName = 'span';
16196
16197 /* Methods */
16198
16199 /**
16200 * Handles label mouse click events.
16201 *
16202 * @private
16203 * @param {jQuery.Event} e Mouse click event
16204 */
16205 OO.ui.LabelWidget.prototype.onClick = function () {
16206 this.input.simulateLabelClick();
16207 return false;
16208 };
16209
16210 /**
16211 * OptionWidgets are special elements that can be selected and configured with data. The
16212 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16213 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16214 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16215 *
16216 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16217 *
16218 * @class
16219 * @extends OO.ui.Widget
16220 * @mixins OO.ui.mixin.LabelElement
16221 * @mixins OO.ui.mixin.FlaggedElement
16222 *
16223 * @constructor
16224 * @param {Object} [config] Configuration options
16225 */
16226 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16227 // Configuration initialization
16228 config = config || {};
16229
16230 // Parent constructor
16231 OO.ui.OptionWidget.parent.call( this, config );
16232
16233 // Mixin constructors
16234 OO.ui.mixin.ItemWidget.call( this );
16235 OO.ui.mixin.LabelElement.call( this, config );
16236 OO.ui.mixin.FlaggedElement.call( this, config );
16237
16238 // Properties
16239 this.selected = false;
16240 this.highlighted = false;
16241 this.pressed = false;
16242
16243 // Initialization
16244 this.$element
16245 .data( 'oo-ui-optionWidget', this )
16246 .attr( 'role', 'option' )
16247 .attr( 'aria-selected', 'false' )
16248 .addClass( 'oo-ui-optionWidget' )
16249 .append( this.$label );
16250 };
16251
16252 /* Setup */
16253
16254 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16255 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16256 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16257 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16258
16259 /* Static Properties */
16260
16261 OO.ui.OptionWidget.static.selectable = true;
16262
16263 OO.ui.OptionWidget.static.highlightable = true;
16264
16265 OO.ui.OptionWidget.static.pressable = true;
16266
16267 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16268
16269 /* Methods */
16270
16271 /**
16272 * Check if the option can be selected.
16273 *
16274 * @return {boolean} Item is selectable
16275 */
16276 OO.ui.OptionWidget.prototype.isSelectable = function () {
16277 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16278 };
16279
16280 /**
16281 * Check if the option can be highlighted. A highlight indicates that the option
16282 * may be selected when a user presses enter or clicks. Disabled items cannot
16283 * be highlighted.
16284 *
16285 * @return {boolean} Item is highlightable
16286 */
16287 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16288 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16289 };
16290
16291 /**
16292 * Check if the option can be pressed. The pressed state occurs when a user mouses
16293 * down on an item, but has not yet let go of the mouse.
16294 *
16295 * @return {boolean} Item is pressable
16296 */
16297 OO.ui.OptionWidget.prototype.isPressable = function () {
16298 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16299 };
16300
16301 /**
16302 * Check if the option is selected.
16303 *
16304 * @return {boolean} Item is selected
16305 */
16306 OO.ui.OptionWidget.prototype.isSelected = function () {
16307 return this.selected;
16308 };
16309
16310 /**
16311 * Check if the option is highlighted. A highlight indicates that the
16312 * item may be selected when a user presses enter or clicks.
16313 *
16314 * @return {boolean} Item is highlighted
16315 */
16316 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16317 return this.highlighted;
16318 };
16319
16320 /**
16321 * Check if the option is pressed. The pressed state occurs when a user mouses
16322 * down on an item, but has not yet let go of the mouse. The item may appear
16323 * selected, but it will not be selected until the user releases the mouse.
16324 *
16325 * @return {boolean} Item is pressed
16326 */
16327 OO.ui.OptionWidget.prototype.isPressed = function () {
16328 return this.pressed;
16329 };
16330
16331 /**
16332 * Set the option’s selected state. In general, all modifications to the selection
16333 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16334 * method instead of this method.
16335 *
16336 * @param {boolean} [state=false] Select option
16337 * @chainable
16338 */
16339 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16340 if ( this.constructor.static.selectable ) {
16341 this.selected = !!state;
16342 this.$element
16343 .toggleClass( 'oo-ui-optionWidget-selected', state )
16344 .attr( 'aria-selected', state.toString() );
16345 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16346 this.scrollElementIntoView();
16347 }
16348 this.updateThemeClasses();
16349 }
16350 return this;
16351 };
16352
16353 /**
16354 * Set the option’s highlighted state. In general, all programmatic
16355 * modifications to the highlight should be handled by the
16356 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16357 * method instead of this method.
16358 *
16359 * @param {boolean} [state=false] Highlight option
16360 * @chainable
16361 */
16362 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16363 if ( this.constructor.static.highlightable ) {
16364 this.highlighted = !!state;
16365 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16366 this.updateThemeClasses();
16367 }
16368 return this;
16369 };
16370
16371 /**
16372 * Set the option’s pressed state. In general, all
16373 * programmatic modifications to the pressed state should be handled by the
16374 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16375 * method instead of this method.
16376 *
16377 * @param {boolean} [state=false] Press option
16378 * @chainable
16379 */
16380 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16381 if ( this.constructor.static.pressable ) {
16382 this.pressed = !!state;
16383 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16384 this.updateThemeClasses();
16385 }
16386 return this;
16387 };
16388
16389 /**
16390 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16391 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16392 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16393 * options. For more information about options and selects, please see the
16394 * [OOjs UI documentation on MediaWiki][1].
16395 *
16396 * @example
16397 * // Decorated options in a select widget
16398 * var select = new OO.ui.SelectWidget( {
16399 * items: [
16400 * new OO.ui.DecoratedOptionWidget( {
16401 * data: 'a',
16402 * label: 'Option with icon',
16403 * icon: 'help'
16404 * } ),
16405 * new OO.ui.DecoratedOptionWidget( {
16406 * data: 'b',
16407 * label: 'Option with indicator',
16408 * indicator: 'next'
16409 * } )
16410 * ]
16411 * } );
16412 * $( 'body' ).append( select.$element );
16413 *
16414 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16415 *
16416 * @class
16417 * @extends OO.ui.OptionWidget
16418 * @mixins OO.ui.mixin.IconElement
16419 * @mixins OO.ui.mixin.IndicatorElement
16420 *
16421 * @constructor
16422 * @param {Object} [config] Configuration options
16423 */
16424 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16425 // Parent constructor
16426 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16427
16428 // Mixin constructors
16429 OO.ui.mixin.IconElement.call( this, config );
16430 OO.ui.mixin.IndicatorElement.call( this, config );
16431
16432 // Initialization
16433 this.$element
16434 .addClass( 'oo-ui-decoratedOptionWidget' )
16435 .prepend( this.$icon )
16436 .append( this.$indicator );
16437 };
16438
16439 /* Setup */
16440
16441 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16442 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16443 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16444
16445 /**
16446 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16447 * can be selected and configured with data. The class is
16448 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16449 * [OOjs UI documentation on MediaWiki] [1] for more information.
16450 *
16451 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16452 *
16453 * @class
16454 * @extends OO.ui.DecoratedOptionWidget
16455 * @mixins OO.ui.mixin.ButtonElement
16456 * @mixins OO.ui.mixin.TabIndexedElement
16457 * @mixins OO.ui.mixin.TitledElement
16458 *
16459 * @constructor
16460 * @param {Object} [config] Configuration options
16461 */
16462 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16463 // Configuration initialization
16464 config = config || {};
16465
16466 // Parent constructor
16467 OO.ui.ButtonOptionWidget.parent.call( this, config );
16468
16469 // Mixin constructors
16470 OO.ui.mixin.ButtonElement.call( this, config );
16471 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16472 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16473 $tabIndexed: this.$button,
16474 tabIndex: -1
16475 } ) );
16476
16477 // Initialization
16478 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16479 this.$button.append( this.$element.contents() );
16480 this.$element.append( this.$button );
16481 };
16482
16483 /* Setup */
16484
16485 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16486 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16487 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16488 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16489
16490 /* Static Properties */
16491
16492 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16493 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16494
16495 OO.ui.ButtonOptionWidget.static.highlightable = false;
16496
16497 /* Methods */
16498
16499 /**
16500 * @inheritdoc
16501 */
16502 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16503 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16504
16505 if ( this.constructor.static.selectable ) {
16506 this.setActive( state );
16507 }
16508
16509 return this;
16510 };
16511
16512 /**
16513 * RadioOptionWidget is an option widget that looks like a radio button.
16514 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16515 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16516 *
16517 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16518 *
16519 * @class
16520 * @extends OO.ui.OptionWidget
16521 *
16522 * @constructor
16523 * @param {Object} [config] Configuration options
16524 */
16525 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16526 // Configuration initialization
16527 config = config || {};
16528
16529 // Properties (must be done before parent constructor which calls #setDisabled)
16530 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16531
16532 // Parent constructor
16533 OO.ui.RadioOptionWidget.parent.call( this, config );
16534
16535 // Events
16536 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16537
16538 // Initialization
16539 // Remove implicit role, we're handling it ourselves
16540 this.radio.$input.attr( 'role', 'presentation' );
16541 this.$element
16542 .addClass( 'oo-ui-radioOptionWidget' )
16543 .attr( 'role', 'radio' )
16544 .attr( 'aria-checked', 'false' )
16545 .removeAttr( 'aria-selected' )
16546 .prepend( this.radio.$element );
16547 };
16548
16549 /* Setup */
16550
16551 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16552
16553 /* Static Properties */
16554
16555 OO.ui.RadioOptionWidget.static.highlightable = false;
16556
16557 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16558
16559 OO.ui.RadioOptionWidget.static.pressable = false;
16560
16561 OO.ui.RadioOptionWidget.static.tagName = 'label';
16562
16563 /* Methods */
16564
16565 /**
16566 * @param {jQuery.Event} e Focus event
16567 * @private
16568 */
16569 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16570 this.radio.$input.blur();
16571 this.$element.parent().focus();
16572 };
16573
16574 /**
16575 * @inheritdoc
16576 */
16577 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16578 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16579
16580 this.radio.setSelected( state );
16581 this.$element
16582 .attr( 'aria-checked', state.toString() )
16583 .removeAttr( 'aria-selected' );
16584
16585 return this;
16586 };
16587
16588 /**
16589 * @inheritdoc
16590 */
16591 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16592 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16593
16594 this.radio.setDisabled( this.isDisabled() );
16595
16596 return this;
16597 };
16598
16599 /**
16600 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16601 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16602 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16603 *
16604 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16605 *
16606 * @class
16607 * @extends OO.ui.DecoratedOptionWidget
16608 *
16609 * @constructor
16610 * @param {Object} [config] Configuration options
16611 */
16612 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16613 // Configuration initialization
16614 config = $.extend( { icon: 'check' }, config );
16615
16616 // Parent constructor
16617 OO.ui.MenuOptionWidget.parent.call( this, config );
16618
16619 // Initialization
16620 this.$element
16621 .attr( 'role', 'menuitem' )
16622 .addClass( 'oo-ui-menuOptionWidget' );
16623 };
16624
16625 /* Setup */
16626
16627 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16628
16629 /* Static Properties */
16630
16631 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16632
16633 /**
16634 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16635 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16636 *
16637 * @example
16638 * var myDropdown = new OO.ui.DropdownWidget( {
16639 * menu: {
16640 * items: [
16641 * new OO.ui.MenuSectionOptionWidget( {
16642 * label: 'Dogs'
16643 * } ),
16644 * new OO.ui.MenuOptionWidget( {
16645 * data: 'corgi',
16646 * label: 'Welsh Corgi'
16647 * } ),
16648 * new OO.ui.MenuOptionWidget( {
16649 * data: 'poodle',
16650 * label: 'Standard Poodle'
16651 * } ),
16652 * new OO.ui.MenuSectionOptionWidget( {
16653 * label: 'Cats'
16654 * } ),
16655 * new OO.ui.MenuOptionWidget( {
16656 * data: 'lion',
16657 * label: 'Lion'
16658 * } )
16659 * ]
16660 * }
16661 * } );
16662 * $( 'body' ).append( myDropdown.$element );
16663 *
16664 *
16665 * @class
16666 * @extends OO.ui.DecoratedOptionWidget
16667 *
16668 * @constructor
16669 * @param {Object} [config] Configuration options
16670 */
16671 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16672 // Parent constructor
16673 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16674
16675 // Initialization
16676 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16677 };
16678
16679 /* Setup */
16680
16681 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16682
16683 /* Static Properties */
16684
16685 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16686
16687 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16688
16689 /**
16690 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16691 *
16692 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16693 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16694 * for an example.
16695 *
16696 * @class
16697 * @extends OO.ui.DecoratedOptionWidget
16698 *
16699 * @constructor
16700 * @param {Object} [config] Configuration options
16701 * @cfg {number} [level] Indentation level
16702 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16703 */
16704 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16705 // Configuration initialization
16706 config = config || {};
16707
16708 // Parent constructor
16709 OO.ui.OutlineOptionWidget.parent.call( this, config );
16710
16711 // Properties
16712 this.level = 0;
16713 this.movable = !!config.movable;
16714 this.removable = !!config.removable;
16715
16716 // Initialization
16717 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16718 this.setLevel( config.level );
16719 };
16720
16721 /* Setup */
16722
16723 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16724
16725 /* Static Properties */
16726
16727 OO.ui.OutlineOptionWidget.static.highlightable = false;
16728
16729 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16730
16731 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16732
16733 OO.ui.OutlineOptionWidget.static.levels = 3;
16734
16735 /* Methods */
16736
16737 /**
16738 * Check if item is movable.
16739 *
16740 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16741 *
16742 * @return {boolean} Item is movable
16743 */
16744 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16745 return this.movable;
16746 };
16747
16748 /**
16749 * Check if item is removable.
16750 *
16751 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16752 *
16753 * @return {boolean} Item is removable
16754 */
16755 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16756 return this.removable;
16757 };
16758
16759 /**
16760 * Get indentation level.
16761 *
16762 * @return {number} Indentation level
16763 */
16764 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16765 return this.level;
16766 };
16767
16768 /**
16769 * Set movability.
16770 *
16771 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16772 *
16773 * @param {boolean} movable Item is movable
16774 * @chainable
16775 */
16776 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16777 this.movable = !!movable;
16778 this.updateThemeClasses();
16779 return this;
16780 };
16781
16782 /**
16783 * Set removability.
16784 *
16785 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16786 *
16787 * @param {boolean} movable Item is removable
16788 * @chainable
16789 */
16790 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
16791 this.removable = !!removable;
16792 this.updateThemeClasses();
16793 return this;
16794 };
16795
16796 /**
16797 * Set indentation level.
16798 *
16799 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16800 * @chainable
16801 */
16802 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
16803 var levels = this.constructor.static.levels,
16804 levelClass = this.constructor.static.levelClass,
16805 i = levels;
16806
16807 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
16808 while ( i-- ) {
16809 if ( this.level === i ) {
16810 this.$element.addClass( levelClass + i );
16811 } else {
16812 this.$element.removeClass( levelClass + i );
16813 }
16814 }
16815 this.updateThemeClasses();
16816
16817 return this;
16818 };
16819
16820 /**
16821 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16822 *
16823 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16824 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16825 * for an example.
16826 *
16827 * @class
16828 * @extends OO.ui.OptionWidget
16829 *
16830 * @constructor
16831 * @param {Object} [config] Configuration options
16832 */
16833 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
16834 // Configuration initialization
16835 config = config || {};
16836
16837 // Parent constructor
16838 OO.ui.TabOptionWidget.parent.call( this, config );
16839
16840 // Initialization
16841 this.$element.addClass( 'oo-ui-tabOptionWidget' );
16842 };
16843
16844 /* Setup */
16845
16846 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
16847
16848 /* Static Properties */
16849
16850 OO.ui.TabOptionWidget.static.highlightable = false;
16851
16852 /**
16853 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16854 * By default, each popup has an anchor that points toward its origin.
16855 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16856 *
16857 * @example
16858 * // A popup widget.
16859 * var popup = new OO.ui.PopupWidget( {
16860 * $content: $( '<p>Hi there!</p>' ),
16861 * padded: true,
16862 * width: 300
16863 * } );
16864 *
16865 * $( 'body' ).append( popup.$element );
16866 * // To display the popup, toggle the visibility to 'true'.
16867 * popup.toggle( true );
16868 *
16869 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16870 *
16871 * @class
16872 * @extends OO.ui.Widget
16873 * @mixins OO.ui.mixin.LabelElement
16874 *
16875 * @constructor
16876 * @param {Object} [config] Configuration options
16877 * @cfg {number} [width=320] Width of popup in pixels
16878 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16879 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16880 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16881 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16882 * popup is leaning towards the right of the screen.
16883 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16884 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16885 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16886 * sentence in the given language.
16887 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16888 * See the [OOjs UI docs on MediaWiki][3] for an example.
16889 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16890 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16891 * @cfg {jQuery} [$content] Content to append to the popup's body
16892 * @cfg {jQuery} [$footer] Content to append to the popup's footer
16893 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16894 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16895 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16896 * for an example.
16897 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16898 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16899 * button.
16900 * @cfg {boolean} [padded] Add padding to the popup's body
16901 */
16902 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
16903 // Configuration initialization
16904 config = config || {};
16905
16906 // Parent constructor
16907 OO.ui.PopupWidget.parent.call( this, config );
16908
16909 // Properties (must be set before ClippableElement constructor call)
16910 this.$body = $( '<div>' );
16911 this.$popup = $( '<div>' );
16912
16913 // Mixin constructors
16914 OO.ui.mixin.LabelElement.call( this, config );
16915 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
16916 $clippable: this.$body,
16917 $clippableContainer: this.$popup
16918 } ) );
16919
16920 // Properties
16921 this.$head = $( '<div>' );
16922 this.$footer = $( '<div>' );
16923 this.$anchor = $( '<div>' );
16924 // If undefined, will be computed lazily in updateDimensions()
16925 this.$container = config.$container;
16926 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
16927 this.autoClose = !!config.autoClose;
16928 this.$autoCloseIgnore = config.$autoCloseIgnore;
16929 this.transitionTimeout = null;
16930 this.anchor = null;
16931 this.width = config.width !== undefined ? config.width : 320;
16932 this.height = config.height !== undefined ? config.height : null;
16933 this.setAlignment( config.align );
16934 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
16935 this.onMouseDownHandler = this.onMouseDown.bind( this );
16936 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
16937
16938 // Events
16939 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
16940
16941 // Initialization
16942 this.toggleAnchor( config.anchor === undefined || config.anchor );
16943 this.$body.addClass( 'oo-ui-popupWidget-body' );
16944 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
16945 this.$head
16946 .addClass( 'oo-ui-popupWidget-head' )
16947 .append( this.$label, this.closeButton.$element );
16948 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
16949 if ( !config.head ) {
16950 this.$head.addClass( 'oo-ui-element-hidden' );
16951 }
16952 if ( !config.$footer ) {
16953 this.$footer.addClass( 'oo-ui-element-hidden' );
16954 }
16955 this.$popup
16956 .addClass( 'oo-ui-popupWidget-popup' )
16957 .append( this.$head, this.$body, this.$footer );
16958 this.$element
16959 .addClass( 'oo-ui-popupWidget' )
16960 .append( this.$popup, this.$anchor );
16961 // Move content, which was added to #$element by OO.ui.Widget, to the body
16962 if ( config.$content instanceof jQuery ) {
16963 this.$body.append( config.$content );
16964 }
16965 if ( config.$footer instanceof jQuery ) {
16966 this.$footer.append( config.$footer );
16967 }
16968 if ( config.padded ) {
16969 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
16970 }
16971
16972 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16973 // that reference properties not initialized at that time of parent class construction
16974 // TODO: Find a better way to handle post-constructor setup
16975 this.visible = false;
16976 this.$element.addClass( 'oo-ui-element-hidden' );
16977 };
16978
16979 /* Setup */
16980
16981 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
16982 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
16983 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
16984
16985 /* Methods */
16986
16987 /**
16988 * Handles mouse down events.
16989 *
16990 * @private
16991 * @param {MouseEvent} e Mouse down event
16992 */
16993 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
16994 if (
16995 this.isVisible() &&
16996 !$.contains( this.$element[ 0 ], e.target ) &&
16997 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
16998 ) {
16999 this.toggle( false );
17000 }
17001 };
17002
17003 /**
17004 * Bind mouse down listener.
17005 *
17006 * @private
17007 */
17008 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
17009 // Capture clicks outside popup
17010 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17011 };
17012
17013 /**
17014 * Handles close button click events.
17015 *
17016 * @private
17017 */
17018 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17019 if ( this.isVisible() ) {
17020 this.toggle( false );
17021 }
17022 };
17023
17024 /**
17025 * Unbind mouse down listener.
17026 *
17027 * @private
17028 */
17029 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17030 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17031 };
17032
17033 /**
17034 * Handles key down events.
17035 *
17036 * @private
17037 * @param {KeyboardEvent} e Key down event
17038 */
17039 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17040 if (
17041 e.which === OO.ui.Keys.ESCAPE &&
17042 this.isVisible()
17043 ) {
17044 this.toggle( false );
17045 e.preventDefault();
17046 e.stopPropagation();
17047 }
17048 };
17049
17050 /**
17051 * Bind key down listener.
17052 *
17053 * @private
17054 */
17055 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17056 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17057 };
17058
17059 /**
17060 * Unbind key down listener.
17061 *
17062 * @private
17063 */
17064 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17065 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17066 };
17067
17068 /**
17069 * Show, hide, or toggle the visibility of the anchor.
17070 *
17071 * @param {boolean} [show] Show anchor, omit to toggle
17072 */
17073 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17074 show = show === undefined ? !this.anchored : !!show;
17075
17076 if ( this.anchored !== show ) {
17077 if ( show ) {
17078 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17079 } else {
17080 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17081 }
17082 this.anchored = show;
17083 }
17084 };
17085
17086 /**
17087 * Check if the anchor is visible.
17088 *
17089 * @return {boolean} Anchor is visible
17090 */
17091 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17092 return this.anchor;
17093 };
17094
17095 /**
17096 * @inheritdoc
17097 */
17098 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17099 var change;
17100 show = show === undefined ? !this.isVisible() : !!show;
17101
17102 change = show !== this.isVisible();
17103
17104 // Parent method
17105 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17106
17107 if ( change ) {
17108 if ( show ) {
17109 if ( this.autoClose ) {
17110 this.bindMouseDownListener();
17111 this.bindKeyDownListener();
17112 }
17113 this.updateDimensions();
17114 this.toggleClipping( true );
17115 } else {
17116 this.toggleClipping( false );
17117 if ( this.autoClose ) {
17118 this.unbindMouseDownListener();
17119 this.unbindKeyDownListener();
17120 }
17121 }
17122 }
17123
17124 return this;
17125 };
17126
17127 /**
17128 * Set the size of the popup.
17129 *
17130 * Changing the size may also change the popup's position depending on the alignment.
17131 *
17132 * @param {number} width Width in pixels
17133 * @param {number} height Height in pixels
17134 * @param {boolean} [transition=false] Use a smooth transition
17135 * @chainable
17136 */
17137 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17138 this.width = width;
17139 this.height = height !== undefined ? height : null;
17140 if ( this.isVisible() ) {
17141 this.updateDimensions( transition );
17142 }
17143 };
17144
17145 /**
17146 * Update the size and position.
17147 *
17148 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17149 * be called automatically.
17150 *
17151 * @param {boolean} [transition=false] Use a smooth transition
17152 * @chainable
17153 */
17154 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17155 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17156 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17157 align = this.align,
17158 widget = this;
17159
17160 if ( !this.$container ) {
17161 // Lazy-initialize $container if not specified in constructor
17162 this.$container = $( this.getClosestScrollableElementContainer() );
17163 }
17164
17165 // Set height and width before measuring things, since it might cause our measurements
17166 // to change (e.g. due to scrollbars appearing or disappearing)
17167 this.$popup.css( {
17168 width: this.width,
17169 height: this.height !== null ? this.height : 'auto'
17170 } );
17171
17172 // If we are in RTL, we need to flip the alignment, unless it is center
17173 if ( align === 'forwards' || align === 'backwards' ) {
17174 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17175 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17176 } else {
17177 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17178 }
17179
17180 }
17181
17182 // Compute initial popupOffset based on alignment
17183 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17184
17185 // Figure out if this will cause the popup to go beyond the edge of the container
17186 originOffset = this.$element.offset().left;
17187 containerLeft = this.$container.offset().left;
17188 containerWidth = this.$container.innerWidth();
17189 containerRight = containerLeft + containerWidth;
17190 popupLeft = popupOffset - this.containerPadding;
17191 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17192 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17193 overlapRight = containerRight - ( originOffset + popupRight );
17194
17195 // Adjust offset to make the popup not go beyond the edge, if needed
17196 if ( overlapRight < 0 ) {
17197 popupOffset += overlapRight;
17198 } else if ( overlapLeft < 0 ) {
17199 popupOffset -= overlapLeft;
17200 }
17201
17202 // Adjust offset to avoid anchor being rendered too close to the edge
17203 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17204 // TODO: Find a measurement that works for CSS anchors and image anchors
17205 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17206 if ( popupOffset + this.width < anchorWidth ) {
17207 popupOffset = anchorWidth - this.width;
17208 } else if ( -popupOffset < anchorWidth ) {
17209 popupOffset = -anchorWidth;
17210 }
17211
17212 // Prevent transition from being interrupted
17213 clearTimeout( this.transitionTimeout );
17214 if ( transition ) {
17215 // Enable transition
17216 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17217 }
17218
17219 // Position body relative to anchor
17220 this.$popup.css( 'margin-left', popupOffset );
17221
17222 if ( transition ) {
17223 // Prevent transitioning after transition is complete
17224 this.transitionTimeout = setTimeout( function () {
17225 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17226 }, 200 );
17227 } else {
17228 // Prevent transitioning immediately
17229 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17230 }
17231
17232 // Reevaluate clipping state since we've relocated and resized the popup
17233 this.clip();
17234
17235 return this;
17236 };
17237
17238 /**
17239 * Set popup alignment
17240 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17241 * `backwards` or `forwards`.
17242 */
17243 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17244 // Validate alignment and transform deprecated values
17245 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17246 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17247 } else {
17248 this.align = 'center';
17249 }
17250 };
17251
17252 /**
17253 * Get popup alignment
17254 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17255 * `backwards` or `forwards`.
17256 */
17257 OO.ui.PopupWidget.prototype.getAlignment = function () {
17258 return this.align;
17259 };
17260
17261 /**
17262 * Progress bars visually display the status of an operation, such as a download,
17263 * and can be either determinate or indeterminate:
17264 *
17265 * - **determinate** process bars show the percent of an operation that is complete.
17266 *
17267 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17268 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17269 * not use percentages.
17270 *
17271 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17272 *
17273 * @example
17274 * // Examples of determinate and indeterminate progress bars.
17275 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17276 * progress: 33
17277 * } );
17278 * var progressBar2 = new OO.ui.ProgressBarWidget();
17279 *
17280 * // Create a FieldsetLayout to layout progress bars
17281 * var fieldset = new OO.ui.FieldsetLayout;
17282 * fieldset.addItems( [
17283 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17284 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17285 * ] );
17286 * $( 'body' ).append( fieldset.$element );
17287 *
17288 * @class
17289 * @extends OO.ui.Widget
17290 *
17291 * @constructor
17292 * @param {Object} [config] Configuration options
17293 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17294 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17295 * By default, the progress bar is indeterminate.
17296 */
17297 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17298 // Configuration initialization
17299 config = config || {};
17300
17301 // Parent constructor
17302 OO.ui.ProgressBarWidget.parent.call( this, config );
17303
17304 // Properties
17305 this.$bar = $( '<div>' );
17306 this.progress = null;
17307
17308 // Initialization
17309 this.setProgress( config.progress !== undefined ? config.progress : false );
17310 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17311 this.$element
17312 .attr( {
17313 role: 'progressbar',
17314 'aria-valuemin': 0,
17315 'aria-valuemax': 100
17316 } )
17317 .addClass( 'oo-ui-progressBarWidget' )
17318 .append( this.$bar );
17319 };
17320
17321 /* Setup */
17322
17323 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17324
17325 /* Static Properties */
17326
17327 OO.ui.ProgressBarWidget.static.tagName = 'div';
17328
17329 /* Methods */
17330
17331 /**
17332 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17333 *
17334 * @return {number|boolean} Progress percent
17335 */
17336 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17337 return this.progress;
17338 };
17339
17340 /**
17341 * Set the percent of the process completed or `false` for an indeterminate process.
17342 *
17343 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17344 */
17345 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17346 this.progress = progress;
17347
17348 if ( progress !== false ) {
17349 this.$bar.css( 'width', this.progress + '%' );
17350 this.$element.attr( 'aria-valuenow', this.progress );
17351 } else {
17352 this.$bar.css( 'width', '' );
17353 this.$element.removeAttr( 'aria-valuenow' );
17354 }
17355 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17356 };
17357
17358 /**
17359 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17360 * and a menu of search results, which is displayed beneath the query
17361 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17362 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17363 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17364 *
17365 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17366 * the [OOjs UI demos][1] for an example.
17367 *
17368 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17369 *
17370 * @class
17371 * @extends OO.ui.Widget
17372 *
17373 * @constructor
17374 * @param {Object} [config] Configuration options
17375 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17376 * @cfg {string} [value] Initial query value
17377 */
17378 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17379 // Configuration initialization
17380 config = config || {};
17381
17382 // Parent constructor
17383 OO.ui.SearchWidget.parent.call( this, config );
17384
17385 // Properties
17386 this.query = new OO.ui.TextInputWidget( {
17387 icon: 'search',
17388 placeholder: config.placeholder,
17389 value: config.value
17390 } );
17391 this.results = new OO.ui.SelectWidget();
17392 this.$query = $( '<div>' );
17393 this.$results = $( '<div>' );
17394
17395 // Events
17396 this.query.connect( this, {
17397 change: 'onQueryChange',
17398 enter: 'onQueryEnter'
17399 } );
17400 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17401
17402 // Initialization
17403 this.$query
17404 .addClass( 'oo-ui-searchWidget-query' )
17405 .append( this.query.$element );
17406 this.$results
17407 .addClass( 'oo-ui-searchWidget-results' )
17408 .append( this.results.$element );
17409 this.$element
17410 .addClass( 'oo-ui-searchWidget' )
17411 .append( this.$results, this.$query );
17412 };
17413
17414 /* Setup */
17415
17416 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17417
17418 /* Methods */
17419
17420 /**
17421 * Handle query key down events.
17422 *
17423 * @private
17424 * @param {jQuery.Event} e Key down event
17425 */
17426 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17427 var highlightedItem, nextItem,
17428 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17429
17430 if ( dir ) {
17431 highlightedItem = this.results.getHighlightedItem();
17432 if ( !highlightedItem ) {
17433 highlightedItem = this.results.getSelectedItem();
17434 }
17435 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17436 this.results.highlightItem( nextItem );
17437 nextItem.scrollElementIntoView();
17438 }
17439 };
17440
17441 /**
17442 * Handle select widget select events.
17443 *
17444 * Clears existing results. Subclasses should repopulate items according to new query.
17445 *
17446 * @private
17447 * @param {string} value New value
17448 */
17449 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17450 // Reset
17451 this.results.clearItems();
17452 };
17453
17454 /**
17455 * Handle select widget enter key events.
17456 *
17457 * Chooses highlighted item.
17458 *
17459 * @private
17460 * @param {string} value New value
17461 */
17462 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17463 // Reset
17464 this.results.chooseItem( this.results.getHighlightedItem() );
17465 };
17466
17467 /**
17468 * Get the query input.
17469 *
17470 * @return {OO.ui.TextInputWidget} Query input
17471 */
17472 OO.ui.SearchWidget.prototype.getQuery = function () {
17473 return this.query;
17474 };
17475
17476 /**
17477 * Get the search results menu.
17478 *
17479 * @return {OO.ui.SelectWidget} Menu of search results
17480 */
17481 OO.ui.SearchWidget.prototype.getResults = function () {
17482 return this.results;
17483 };
17484
17485 /**
17486 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17487 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17488 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17489 * menu selects}.
17490 *
17491 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17492 * information, please see the [OOjs UI documentation on MediaWiki][1].
17493 *
17494 * @example
17495 * // Example of a select widget with three options
17496 * var select = new OO.ui.SelectWidget( {
17497 * items: [
17498 * new OO.ui.OptionWidget( {
17499 * data: 'a',
17500 * label: 'Option One',
17501 * } ),
17502 * new OO.ui.OptionWidget( {
17503 * data: 'b',
17504 * label: 'Option Two',
17505 * } ),
17506 * new OO.ui.OptionWidget( {
17507 * data: 'c',
17508 * label: 'Option Three',
17509 * } )
17510 * ]
17511 * } );
17512 * $( 'body' ).append( select.$element );
17513 *
17514 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17515 *
17516 * @abstract
17517 * @class
17518 * @extends OO.ui.Widget
17519 * @mixins OO.ui.mixin.GroupWidget
17520 *
17521 * @constructor
17522 * @param {Object} [config] Configuration options
17523 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17524 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17525 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17526 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17527 */
17528 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17529 // Configuration initialization
17530 config = config || {};
17531
17532 // Parent constructor
17533 OO.ui.SelectWidget.parent.call( this, config );
17534
17535 // Mixin constructors
17536 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17537
17538 // Properties
17539 this.pressed = false;
17540 this.selecting = null;
17541 this.onMouseUpHandler = this.onMouseUp.bind( this );
17542 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17543 this.onKeyDownHandler = this.onKeyDown.bind( this );
17544 this.onKeyPressHandler = this.onKeyPress.bind( this );
17545 this.keyPressBuffer = '';
17546 this.keyPressBufferTimer = null;
17547
17548 // Events
17549 this.connect( this, {
17550 toggle: 'onToggle'
17551 } );
17552 this.$element.on( {
17553 mousedown: this.onMouseDown.bind( this ),
17554 mouseover: this.onMouseOver.bind( this ),
17555 mouseleave: this.onMouseLeave.bind( this )
17556 } );
17557
17558 // Initialization
17559 this.$element
17560 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17561 .attr( 'role', 'listbox' );
17562 if ( Array.isArray( config.items ) ) {
17563 this.addItems( config.items );
17564 }
17565 };
17566
17567 /* Setup */
17568
17569 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17570
17571 // Need to mixin base class as well
17572 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17573 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17574
17575 /* Static */
17576 OO.ui.SelectWidget.static.passAllFilter = function () {
17577 return true;
17578 };
17579
17580 /* Events */
17581
17582 /**
17583 * @event highlight
17584 *
17585 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17586 *
17587 * @param {OO.ui.OptionWidget|null} item Highlighted item
17588 */
17589
17590 /**
17591 * @event press
17592 *
17593 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17594 * pressed state of an option.
17595 *
17596 * @param {OO.ui.OptionWidget|null} item Pressed item
17597 */
17598
17599 /**
17600 * @event select
17601 *
17602 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17603 *
17604 * @param {OO.ui.OptionWidget|null} item Selected item
17605 */
17606
17607 /**
17608 * @event choose
17609 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17610 * @param {OO.ui.OptionWidget} item Chosen item
17611 */
17612
17613 /**
17614 * @event add
17615 *
17616 * An `add` event is emitted when options are added to the select with the #addItems method.
17617 *
17618 * @param {OO.ui.OptionWidget[]} items Added items
17619 * @param {number} index Index of insertion point
17620 */
17621
17622 /**
17623 * @event remove
17624 *
17625 * A `remove` event is emitted when options are removed from the select with the #clearItems
17626 * or #removeItems methods.
17627 *
17628 * @param {OO.ui.OptionWidget[]} items Removed items
17629 */
17630
17631 /* Methods */
17632
17633 /**
17634 * Handle mouse down events.
17635 *
17636 * @private
17637 * @param {jQuery.Event} e Mouse down event
17638 */
17639 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17640 var item;
17641
17642 if ( !this.isDisabled() && e.which === 1 ) {
17643 this.togglePressed( true );
17644 item = this.getTargetItem( e );
17645 if ( item && item.isSelectable() ) {
17646 this.pressItem( item );
17647 this.selecting = item;
17648 OO.ui.addCaptureEventListener(
17649 this.getElementDocument(),
17650 'mouseup',
17651 this.onMouseUpHandler
17652 );
17653 OO.ui.addCaptureEventListener(
17654 this.getElementDocument(),
17655 'mousemove',
17656 this.onMouseMoveHandler
17657 );
17658 }
17659 }
17660 return false;
17661 };
17662
17663 /**
17664 * Handle mouse up events.
17665 *
17666 * @private
17667 * @param {jQuery.Event} e Mouse up event
17668 */
17669 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17670 var item;
17671
17672 this.togglePressed( false );
17673 if ( !this.selecting ) {
17674 item = this.getTargetItem( e );
17675 if ( item && item.isSelectable() ) {
17676 this.selecting = item;
17677 }
17678 }
17679 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17680 this.pressItem( null );
17681 this.chooseItem( this.selecting );
17682 this.selecting = null;
17683 }
17684
17685 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17686 this.onMouseUpHandler );
17687 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17688 this.onMouseMoveHandler );
17689
17690 return false;
17691 };
17692
17693 /**
17694 * Handle mouse move events.
17695 *
17696 * @private
17697 * @param {jQuery.Event} e Mouse move event
17698 */
17699 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17700 var item;
17701
17702 if ( !this.isDisabled() && this.pressed ) {
17703 item = this.getTargetItem( e );
17704 if ( item && item !== this.selecting && item.isSelectable() ) {
17705 this.pressItem( item );
17706 this.selecting = item;
17707 }
17708 }
17709 return false;
17710 };
17711
17712 /**
17713 * Handle mouse over events.
17714 *
17715 * @private
17716 * @param {jQuery.Event} e Mouse over event
17717 */
17718 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17719 var item;
17720
17721 if ( !this.isDisabled() ) {
17722 item = this.getTargetItem( e );
17723 this.highlightItem( item && item.isHighlightable() ? item : null );
17724 }
17725 return false;
17726 };
17727
17728 /**
17729 * Handle mouse leave events.
17730 *
17731 * @private
17732 * @param {jQuery.Event} e Mouse over event
17733 */
17734 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17735 if ( !this.isDisabled() ) {
17736 this.highlightItem( null );
17737 }
17738 return false;
17739 };
17740
17741 /**
17742 * Handle key down events.
17743 *
17744 * @protected
17745 * @param {jQuery.Event} e Key down event
17746 */
17747 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17748 var nextItem,
17749 handled = false,
17750 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17751
17752 if ( !this.isDisabled() && this.isVisible() ) {
17753 switch ( e.keyCode ) {
17754 case OO.ui.Keys.ENTER:
17755 if ( currentItem && currentItem.constructor.static.highlightable ) {
17756 // Was only highlighted, now let's select it. No-op if already selected.
17757 this.chooseItem( currentItem );
17758 handled = true;
17759 }
17760 break;
17761 case OO.ui.Keys.UP:
17762 case OO.ui.Keys.LEFT:
17763 this.clearKeyPressBuffer();
17764 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17765 handled = true;
17766 break;
17767 case OO.ui.Keys.DOWN:
17768 case OO.ui.Keys.RIGHT:
17769 this.clearKeyPressBuffer();
17770 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17771 handled = true;
17772 break;
17773 case OO.ui.Keys.ESCAPE:
17774 case OO.ui.Keys.TAB:
17775 if ( currentItem && currentItem.constructor.static.highlightable ) {
17776 currentItem.setHighlighted( false );
17777 }
17778 this.unbindKeyDownListener();
17779 this.unbindKeyPressListener();
17780 // Don't prevent tabbing away / defocusing
17781 handled = false;
17782 break;
17783 }
17784
17785 if ( nextItem ) {
17786 if ( nextItem.constructor.static.highlightable ) {
17787 this.highlightItem( nextItem );
17788 } else {
17789 this.chooseItem( nextItem );
17790 }
17791 nextItem.scrollElementIntoView();
17792 }
17793
17794 if ( handled ) {
17795 // Can't just return false, because e is not always a jQuery event
17796 e.preventDefault();
17797 e.stopPropagation();
17798 }
17799 }
17800 };
17801
17802 /**
17803 * Bind key down listener.
17804 *
17805 * @protected
17806 */
17807 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
17808 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17809 };
17810
17811 /**
17812 * Unbind key down listener.
17813 *
17814 * @protected
17815 */
17816 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
17817 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17818 };
17819
17820 /**
17821 * Clear the key-press buffer
17822 *
17823 * @protected
17824 */
17825 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
17826 if ( this.keyPressBufferTimer ) {
17827 clearTimeout( this.keyPressBufferTimer );
17828 this.keyPressBufferTimer = null;
17829 }
17830 this.keyPressBuffer = '';
17831 };
17832
17833 /**
17834 * Handle key press events.
17835 *
17836 * @protected
17837 * @param {jQuery.Event} e Key press event
17838 */
17839 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
17840 var c, filter, item;
17841
17842 if ( !e.charCode ) {
17843 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
17844 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
17845 return false;
17846 }
17847 return;
17848 }
17849 if ( String.fromCodePoint ) {
17850 c = String.fromCodePoint( e.charCode );
17851 } else {
17852 c = String.fromCharCode( e.charCode );
17853 }
17854
17855 if ( this.keyPressBufferTimer ) {
17856 clearTimeout( this.keyPressBufferTimer );
17857 }
17858 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
17859
17860 item = this.getHighlightedItem() || this.getSelectedItem();
17861
17862 if ( this.keyPressBuffer === c ) {
17863 // Common (if weird) special case: typing "xxxx" will cycle through all
17864 // the items beginning with "x".
17865 if ( item ) {
17866 item = this.getRelativeSelectableItem( item, 1 );
17867 }
17868 } else {
17869 this.keyPressBuffer += c;
17870 }
17871
17872 filter = this.getItemMatcher( this.keyPressBuffer, false );
17873 if ( !item || !filter( item ) ) {
17874 item = this.getRelativeSelectableItem( item, 1, filter );
17875 }
17876 if ( item ) {
17877 if ( item.constructor.static.highlightable ) {
17878 this.highlightItem( item );
17879 } else {
17880 this.chooseItem( item );
17881 }
17882 item.scrollElementIntoView();
17883 }
17884
17885 return false;
17886 };
17887
17888 /**
17889 * Get a matcher for the specific string
17890 *
17891 * @protected
17892 * @param {string} s String to match against items
17893 * @param {boolean} [exact=false] Only accept exact matches
17894 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17895 */
17896 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
17897 var re;
17898
17899 if ( s.normalize ) {
17900 s = s.normalize();
17901 }
17902 s = exact ? s.trim() : s.replace( /^\s+/, '' );
17903 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17904 if ( exact ) {
17905 re += '\\s*$';
17906 }
17907 re = new RegExp( re, 'i' );
17908 return function ( item ) {
17909 var l = item.getLabel();
17910 if ( typeof l !== 'string' ) {
17911 l = item.$label.text();
17912 }
17913 if ( l.normalize ) {
17914 l = l.normalize();
17915 }
17916 return re.test( l );
17917 };
17918 };
17919
17920 /**
17921 * Bind key press listener.
17922 *
17923 * @protected
17924 */
17925 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
17926 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17927 };
17928
17929 /**
17930 * Unbind key down listener.
17931 *
17932 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17933 * implementation.
17934 *
17935 * @protected
17936 */
17937 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
17938 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17939 this.clearKeyPressBuffer();
17940 };
17941
17942 /**
17943 * Visibility change handler
17944 *
17945 * @protected
17946 * @param {boolean} visible
17947 */
17948 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
17949 if ( !visible ) {
17950 this.clearKeyPressBuffer();
17951 }
17952 };
17953
17954 /**
17955 * Get the closest item to a jQuery.Event.
17956 *
17957 * @private
17958 * @param {jQuery.Event} e
17959 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17960 */
17961 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
17962 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17963 };
17964
17965 /**
17966 * Get selected item.
17967 *
17968 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17969 */
17970 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
17971 var i, len;
17972
17973 for ( i = 0, len = this.items.length; i < len; i++ ) {
17974 if ( this.items[ i ].isSelected() ) {
17975 return this.items[ i ];
17976 }
17977 }
17978 return null;
17979 };
17980
17981 /**
17982 * Get highlighted item.
17983 *
17984 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17985 */
17986 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
17987 var i, len;
17988
17989 for ( i = 0, len = this.items.length; i < len; i++ ) {
17990 if ( this.items[ i ].isHighlighted() ) {
17991 return this.items[ i ];
17992 }
17993 }
17994 return null;
17995 };
17996
17997 /**
17998 * Toggle pressed state.
17999 *
18000 * Press is a state that occurs when a user mouses down on an item, but
18001 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18002 * until the user releases the mouse.
18003 *
18004 * @param {boolean} pressed An option is being pressed
18005 */
18006 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
18007 if ( pressed === undefined ) {
18008 pressed = !this.pressed;
18009 }
18010 if ( pressed !== this.pressed ) {
18011 this.$element
18012 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
18013 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
18014 this.pressed = pressed;
18015 }
18016 };
18017
18018 /**
18019 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18020 * and any existing highlight will be removed. The highlight is mutually exclusive.
18021 *
18022 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18023 * @fires highlight
18024 * @chainable
18025 */
18026 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18027 var i, len, highlighted,
18028 changed = false;
18029
18030 for ( i = 0, len = this.items.length; i < len; i++ ) {
18031 highlighted = this.items[ i ] === item;
18032 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18033 this.items[ i ].setHighlighted( highlighted );
18034 changed = true;
18035 }
18036 }
18037 if ( changed ) {
18038 this.emit( 'highlight', item );
18039 }
18040
18041 return this;
18042 };
18043
18044 /**
18045 * Fetch an item by its label.
18046 *
18047 * @param {string} label Label of the item to select.
18048 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18049 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18050 */
18051 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18052 var i, item, found,
18053 len = this.items.length,
18054 filter = this.getItemMatcher( label, true );
18055
18056 for ( i = 0; i < len; i++ ) {
18057 item = this.items[ i ];
18058 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18059 return item;
18060 }
18061 }
18062
18063 if ( prefix ) {
18064 found = null;
18065 filter = this.getItemMatcher( label, false );
18066 for ( i = 0; i < len; i++ ) {
18067 item = this.items[ i ];
18068 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18069 if ( found ) {
18070 return null;
18071 }
18072 found = item;
18073 }
18074 }
18075 if ( found ) {
18076 return found;
18077 }
18078 }
18079
18080 return null;
18081 };
18082
18083 /**
18084 * Programmatically select an option by its label. If the item does not exist,
18085 * all options will be deselected.
18086 *
18087 * @param {string} [label] Label of the item to select.
18088 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18089 * @fires select
18090 * @chainable
18091 */
18092 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18093 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18094 if ( label === undefined || !itemFromLabel ) {
18095 return this.selectItem();
18096 }
18097 return this.selectItem( itemFromLabel );
18098 };
18099
18100 /**
18101 * Programmatically select an option by its data. If the `data` parameter is omitted,
18102 * or if the item does not exist, all options will be deselected.
18103 *
18104 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18105 * @fires select
18106 * @chainable
18107 */
18108 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18109 var itemFromData = this.getItemFromData( data );
18110 if ( data === undefined || !itemFromData ) {
18111 return this.selectItem();
18112 }
18113 return this.selectItem( itemFromData );
18114 };
18115
18116 /**
18117 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18118 * all options will be deselected.
18119 *
18120 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18121 * @fires select
18122 * @chainable
18123 */
18124 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18125 var i, len, selected,
18126 changed = false;
18127
18128 for ( i = 0, len = this.items.length; i < len; i++ ) {
18129 selected = this.items[ i ] === item;
18130 if ( this.items[ i ].isSelected() !== selected ) {
18131 this.items[ i ].setSelected( selected );
18132 changed = true;
18133 }
18134 }
18135 if ( changed ) {
18136 this.emit( 'select', item );
18137 }
18138
18139 return this;
18140 };
18141
18142 /**
18143 * Press an item.
18144 *
18145 * Press is a state that occurs when a user mouses down on an item, but has not
18146 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18147 * releases the mouse.
18148 *
18149 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18150 * @fires press
18151 * @chainable
18152 */
18153 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18154 var i, len, pressed,
18155 changed = false;
18156
18157 for ( i = 0, len = this.items.length; i < len; i++ ) {
18158 pressed = this.items[ i ] === item;
18159 if ( this.items[ i ].isPressed() !== pressed ) {
18160 this.items[ i ].setPressed( pressed );
18161 changed = true;
18162 }
18163 }
18164 if ( changed ) {
18165 this.emit( 'press', item );
18166 }
18167
18168 return this;
18169 };
18170
18171 /**
18172 * Choose an item.
18173 *
18174 * Note that ‘choose’ should never be modified programmatically. A user can choose
18175 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18176 * use the #selectItem method.
18177 *
18178 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18179 * when users choose an item with the keyboard or mouse.
18180 *
18181 * @param {OO.ui.OptionWidget} item Item to choose
18182 * @fires choose
18183 * @chainable
18184 */
18185 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18186 this.selectItem( item );
18187 this.emit( 'choose', item );
18188
18189 return this;
18190 };
18191
18192 /**
18193 * Get an option by its position relative to the specified item (or to the start of the option array,
18194 * if item is `null`). The direction in which to search through the option array is specified with a
18195 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18196 * `null` if there are no options in the array.
18197 *
18198 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18199 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18200 * @param {Function} filter Only consider items for which this function returns
18201 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18202 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18203 */
18204 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18205 var currentIndex, nextIndex, i,
18206 increase = direction > 0 ? 1 : -1,
18207 len = this.items.length;
18208
18209 if ( !$.isFunction( filter ) ) {
18210 filter = OO.ui.SelectWidget.static.passAllFilter;
18211 }
18212
18213 if ( item instanceof OO.ui.OptionWidget ) {
18214 currentIndex = this.items.indexOf( item );
18215 nextIndex = ( currentIndex + increase + len ) % len;
18216 } else {
18217 // If no item is selected and moving forward, start at the beginning.
18218 // If moving backward, start at the end.
18219 nextIndex = direction > 0 ? 0 : len - 1;
18220 }
18221
18222 for ( i = 0; i < len; i++ ) {
18223 item = this.items[ nextIndex ];
18224 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18225 return item;
18226 }
18227 nextIndex = ( nextIndex + increase + len ) % len;
18228 }
18229 return null;
18230 };
18231
18232 /**
18233 * Get the next selectable item or `null` if there are no selectable items.
18234 * Disabled options and menu-section markers and breaks are not selectable.
18235 *
18236 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18237 */
18238 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18239 var i, len, item;
18240
18241 for ( i = 0, len = this.items.length; i < len; i++ ) {
18242 item = this.items[ i ];
18243 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18244 return item;
18245 }
18246 }
18247
18248 return null;
18249 };
18250
18251 /**
18252 * Add an array of options to the select. Optionally, an index number can be used to
18253 * specify an insertion point.
18254 *
18255 * @param {OO.ui.OptionWidget[]} items Items to add
18256 * @param {number} [index] Index to insert items after
18257 * @fires add
18258 * @chainable
18259 */
18260 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18261 // Mixin method
18262 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18263
18264 // Always provide an index, even if it was omitted
18265 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18266
18267 return this;
18268 };
18269
18270 /**
18271 * Remove the specified array of options from the select. Options will be detached
18272 * from the DOM, not removed, so they can be reused later. To remove all options from
18273 * the select, you may wish to use the #clearItems method instead.
18274 *
18275 * @param {OO.ui.OptionWidget[]} items Items to remove
18276 * @fires remove
18277 * @chainable
18278 */
18279 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18280 var i, len, item;
18281
18282 // Deselect items being removed
18283 for ( i = 0, len = items.length; i < len; i++ ) {
18284 item = items[ i ];
18285 if ( item.isSelected() ) {
18286 this.selectItem( null );
18287 }
18288 }
18289
18290 // Mixin method
18291 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18292
18293 this.emit( 'remove', items );
18294
18295 return this;
18296 };
18297
18298 /**
18299 * Clear all options from the select. Options will be detached from the DOM, not removed,
18300 * so that they can be reused later. To remove a subset of options from the select, use
18301 * the #removeItems method.
18302 *
18303 * @fires remove
18304 * @chainable
18305 */
18306 OO.ui.SelectWidget.prototype.clearItems = function () {
18307 var items = this.items.slice();
18308
18309 // Mixin method
18310 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18311
18312 // Clear selection
18313 this.selectItem( null );
18314
18315 this.emit( 'remove', items );
18316
18317 return this;
18318 };
18319
18320 /**
18321 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18322 * button options and is used together with
18323 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18324 * highlighting, choosing, and selecting mutually exclusive options. Please see
18325 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18326 *
18327 * @example
18328 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18329 * var option1 = new OO.ui.ButtonOptionWidget( {
18330 * data: 1,
18331 * label: 'Option 1',
18332 * title: 'Button option 1'
18333 * } );
18334 *
18335 * var option2 = new OO.ui.ButtonOptionWidget( {
18336 * data: 2,
18337 * label: 'Option 2',
18338 * title: 'Button option 2'
18339 * } );
18340 *
18341 * var option3 = new OO.ui.ButtonOptionWidget( {
18342 * data: 3,
18343 * label: 'Option 3',
18344 * title: 'Button option 3'
18345 * } );
18346 *
18347 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18348 * items: [ option1, option2, option3 ]
18349 * } );
18350 * $( 'body' ).append( buttonSelect.$element );
18351 *
18352 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18353 *
18354 * @class
18355 * @extends OO.ui.SelectWidget
18356 * @mixins OO.ui.mixin.TabIndexedElement
18357 *
18358 * @constructor
18359 * @param {Object} [config] Configuration options
18360 */
18361 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18362 // Parent constructor
18363 OO.ui.ButtonSelectWidget.parent.call( this, config );
18364
18365 // Mixin constructors
18366 OO.ui.mixin.TabIndexedElement.call( this, config );
18367
18368 // Events
18369 this.$element.on( {
18370 focus: this.bindKeyDownListener.bind( this ),
18371 blur: this.unbindKeyDownListener.bind( this )
18372 } );
18373
18374 // Initialization
18375 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18376 };
18377
18378 /* Setup */
18379
18380 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18381 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18382
18383 /**
18384 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18385 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18386 * an interface for adding, removing and selecting options.
18387 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18388 *
18389 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18390 * OO.ui.RadioSelectInputWidget instead.
18391 *
18392 * @example
18393 * // A RadioSelectWidget with RadioOptions.
18394 * var option1 = new OO.ui.RadioOptionWidget( {
18395 * data: 'a',
18396 * label: 'Selected radio option'
18397 * } );
18398 *
18399 * var option2 = new OO.ui.RadioOptionWidget( {
18400 * data: 'b',
18401 * label: 'Unselected radio option'
18402 * } );
18403 *
18404 * var radioSelect=new OO.ui.RadioSelectWidget( {
18405 * items: [ option1, option2 ]
18406 * } );
18407 *
18408 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18409 * radioSelect.selectItem( option1 );
18410 *
18411 * $( 'body' ).append( radioSelect.$element );
18412 *
18413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18414
18415 *
18416 * @class
18417 * @extends OO.ui.SelectWidget
18418 * @mixins OO.ui.mixin.TabIndexedElement
18419 *
18420 * @constructor
18421 * @param {Object} [config] Configuration options
18422 */
18423 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18424 // Parent constructor
18425 OO.ui.RadioSelectWidget.parent.call( this, config );
18426
18427 // Mixin constructors
18428 OO.ui.mixin.TabIndexedElement.call( this, config );
18429
18430 // Events
18431 this.$element.on( {
18432 focus: this.bindKeyDownListener.bind( this ),
18433 blur: this.unbindKeyDownListener.bind( this )
18434 } );
18435
18436 // Initialization
18437 this.$element
18438 .addClass( 'oo-ui-radioSelectWidget' )
18439 .attr( 'role', 'radiogroup' );
18440 };
18441
18442 /* Setup */
18443
18444 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18445 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18446
18447 /**
18448 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18449 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18450 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18451 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18452 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18453 * and customized to be opened, closed, and displayed as needed.
18454 *
18455 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18456 * mouse outside the menu.
18457 *
18458 * Menus also have support for keyboard interaction:
18459 *
18460 * - Enter/Return key: choose and select a menu option
18461 * - Up-arrow key: highlight the previous menu option
18462 * - Down-arrow key: highlight the next menu option
18463 * - Esc key: hide the menu
18464 *
18465 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18466 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18467 *
18468 * @class
18469 * @extends OO.ui.SelectWidget
18470 * @mixins OO.ui.mixin.ClippableElement
18471 *
18472 * @constructor
18473 * @param {Object} [config] Configuration options
18474 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18475 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18476 * and {@link OO.ui.mixin.LookupElement LookupElement}
18477 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18478 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18479 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18480 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18481 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18482 * that button, unless the button (or its parent widget) is passed in here.
18483 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18484 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18485 */
18486 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18487 // Configuration initialization
18488 config = config || {};
18489
18490 // Parent constructor
18491 OO.ui.MenuSelectWidget.parent.call( this, config );
18492
18493 // Mixin constructors
18494 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18495
18496 // Properties
18497 this.newItems = null;
18498 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18499 this.filterFromInput = !!config.filterFromInput;
18500 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18501 this.$widget = config.widget ? config.widget.$element : null;
18502 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18503 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18504
18505 // Initialization
18506 this.$element
18507 .addClass( 'oo-ui-menuSelectWidget' )
18508 .attr( 'role', 'menu' );
18509
18510 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18511 // that reference properties not initialized at that time of parent class construction
18512 // TODO: Find a better way to handle post-constructor setup
18513 this.visible = false;
18514 this.$element.addClass( 'oo-ui-element-hidden' );
18515 };
18516
18517 /* Setup */
18518
18519 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18520 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18521
18522 /* Methods */
18523
18524 /**
18525 * Handles document mouse down events.
18526 *
18527 * @protected
18528 * @param {jQuery.Event} e Key down event
18529 */
18530 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18531 if (
18532 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18533 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18534 ) {
18535 this.toggle( false );
18536 }
18537 };
18538
18539 /**
18540 * @inheritdoc
18541 */
18542 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18543 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18544
18545 if ( !this.isDisabled() && this.isVisible() ) {
18546 switch ( e.keyCode ) {
18547 case OO.ui.Keys.LEFT:
18548 case OO.ui.Keys.RIGHT:
18549 // Do nothing if a text field is associated, arrow keys will be handled natively
18550 if ( !this.$input ) {
18551 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18552 }
18553 break;
18554 case OO.ui.Keys.ESCAPE:
18555 case OO.ui.Keys.TAB:
18556 if ( currentItem ) {
18557 currentItem.setHighlighted( false );
18558 }
18559 this.toggle( false );
18560 // Don't prevent tabbing away, prevent defocusing
18561 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18562 e.preventDefault();
18563 e.stopPropagation();
18564 }
18565 break;
18566 default:
18567 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18568 return;
18569 }
18570 }
18571 };
18572
18573 /**
18574 * Update menu item visibility after input changes.
18575 * @protected
18576 */
18577 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18578 var i, item,
18579 len = this.items.length,
18580 showAll = !this.isVisible(),
18581 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18582
18583 for ( i = 0; i < len; i++ ) {
18584 item = this.items[ i ];
18585 if ( item instanceof OO.ui.OptionWidget ) {
18586 item.toggle( showAll || filter( item ) );
18587 }
18588 }
18589
18590 // Reevaluate clipping
18591 this.clip();
18592 };
18593
18594 /**
18595 * @inheritdoc
18596 */
18597 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18598 if ( this.$input ) {
18599 this.$input.on( 'keydown', this.onKeyDownHandler );
18600 } else {
18601 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18602 }
18603 };
18604
18605 /**
18606 * @inheritdoc
18607 */
18608 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18609 if ( this.$input ) {
18610 this.$input.off( 'keydown', this.onKeyDownHandler );
18611 } else {
18612 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18613 }
18614 };
18615
18616 /**
18617 * @inheritdoc
18618 */
18619 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18620 if ( this.$input ) {
18621 if ( this.filterFromInput ) {
18622 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18623 }
18624 } else {
18625 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18626 }
18627 };
18628
18629 /**
18630 * @inheritdoc
18631 */
18632 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18633 if ( this.$input ) {
18634 if ( this.filterFromInput ) {
18635 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18636 this.updateItemVisibility();
18637 }
18638 } else {
18639 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18640 }
18641 };
18642
18643 /**
18644 * Choose an item.
18645 *
18646 * When a user chooses an item, the menu is closed.
18647 *
18648 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18649 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18650 * @param {OO.ui.OptionWidget} item Item to choose
18651 * @chainable
18652 */
18653 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18654 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18655 this.toggle( false );
18656 return this;
18657 };
18658
18659 /**
18660 * @inheritdoc
18661 */
18662 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18663 var i, len, item;
18664
18665 // Parent method
18666 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18667
18668 // Auto-initialize
18669 if ( !this.newItems ) {
18670 this.newItems = [];
18671 }
18672
18673 for ( i = 0, len = items.length; i < len; i++ ) {
18674 item = items[ i ];
18675 if ( this.isVisible() ) {
18676 // Defer fitting label until item has been attached
18677 item.fitLabel();
18678 } else {
18679 this.newItems.push( item );
18680 }
18681 }
18682
18683 // Reevaluate clipping
18684 this.clip();
18685
18686 return this;
18687 };
18688
18689 /**
18690 * @inheritdoc
18691 */
18692 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18693 // Parent method
18694 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18695
18696 // Reevaluate clipping
18697 this.clip();
18698
18699 return this;
18700 };
18701
18702 /**
18703 * @inheritdoc
18704 */
18705 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18706 // Parent method
18707 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18708
18709 // Reevaluate clipping
18710 this.clip();
18711
18712 return this;
18713 };
18714
18715 /**
18716 * @inheritdoc
18717 */
18718 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18719 var i, len, change;
18720
18721 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18722 change = visible !== this.isVisible();
18723
18724 // Parent method
18725 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18726
18727 if ( change ) {
18728 if ( visible ) {
18729 this.bindKeyDownListener();
18730 this.bindKeyPressListener();
18731
18732 if ( this.newItems && this.newItems.length ) {
18733 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18734 this.newItems[ i ].fitLabel();
18735 }
18736 this.newItems = null;
18737 }
18738 this.toggleClipping( true );
18739
18740 // Auto-hide
18741 if ( this.autoHide ) {
18742 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18743 }
18744 } else {
18745 this.unbindKeyDownListener();
18746 this.unbindKeyPressListener();
18747 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18748 this.toggleClipping( false );
18749 }
18750 }
18751
18752 return this;
18753 };
18754
18755 /**
18756 * FloatingMenuSelectWidget is a menu that will stick under a specified
18757 * container, even when it is inserted elsewhere in the document (for example,
18758 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18759 * menu from being clipped too aggresively.
18760 *
18761 * The menu's position is automatically calculated and maintained when the menu
18762 * is toggled or the window is resized.
18763 *
18764 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18765 *
18766 * @class
18767 * @extends OO.ui.MenuSelectWidget
18768 *
18769 * @constructor
18770 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18771 * Deprecated, omit this parameter and specify `$container` instead.
18772 * @param {Object} [config] Configuration options
18773 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18774 */
18775 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
18776 // Allow 'inputWidget' parameter and config for backwards compatibility
18777 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18778 config = inputWidget;
18779 inputWidget = config.inputWidget;
18780 }
18781
18782 // Configuration initialization
18783 config = config || {};
18784
18785 // Parent constructor
18786 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
18787
18788 // Properties
18789 this.inputWidget = inputWidget; // For backwards compatibility
18790 this.$container = config.$container || this.inputWidget.$element;
18791 this.onWindowResizeHandler = this.onWindowResize.bind( this );
18792
18793 // Initialization
18794 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
18795 // For backwards compatibility
18796 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
18797 };
18798
18799 /* Setup */
18800
18801 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
18802
18803 // For backwards compatibility
18804 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
18805
18806 /* Methods */
18807
18808 /**
18809 * Handle window resize event.
18810 *
18811 * @private
18812 * @param {jQuery.Event} e Window resize event
18813 */
18814 OO.ui.FloatingMenuSelectWidget.prototype.onWindowResize = function () {
18815 this.position();
18816 };
18817
18818 /**
18819 * @inheritdoc
18820 */
18821 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
18822 var change;
18823 visible = visible === undefined ? !this.isVisible() : !!visible;
18824
18825 change = visible !== this.isVisible();
18826
18827 if ( change && visible ) {
18828 // Make sure the width is set before the parent method runs.
18829 // After this we have to call this.position(); again to actually
18830 // position ourselves correctly.
18831 this.position();
18832 }
18833
18834 // Parent method
18835 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
18836
18837 if ( change ) {
18838 if ( this.isVisible() ) {
18839 this.position();
18840 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
18841 } else {
18842 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
18843 }
18844 }
18845
18846 return this;
18847 };
18848
18849 /**
18850 * Position the menu.
18851 *
18852 * @private
18853 * @chainable
18854 */
18855 OO.ui.FloatingMenuSelectWidget.prototype.position = function () {
18856 var $container = this.$container,
18857 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
18858
18859 // Position under input
18860 pos.top += $container.height();
18861 this.$element.css( pos );
18862
18863 // Set width
18864 this.setIdealSize( $container.width() );
18865 // We updated the position, so re-evaluate the clipping state
18866 this.clip();
18867
18868 return this;
18869 };
18870
18871 /**
18872 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18873 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18874 *
18875 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18876 *
18877 * @class
18878 * @extends OO.ui.SelectWidget
18879 * @mixins OO.ui.mixin.TabIndexedElement
18880 *
18881 * @constructor
18882 * @param {Object} [config] Configuration options
18883 */
18884 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
18885 // Parent constructor
18886 OO.ui.OutlineSelectWidget.parent.call( this, config );
18887
18888 // Mixin constructors
18889 OO.ui.mixin.TabIndexedElement.call( this, config );
18890
18891 // Events
18892 this.$element.on( {
18893 focus: this.bindKeyDownListener.bind( this ),
18894 blur: this.unbindKeyDownListener.bind( this )
18895 } );
18896
18897 // Initialization
18898 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
18899 };
18900
18901 /* Setup */
18902
18903 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
18904 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
18905
18906 /**
18907 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18908 *
18909 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18910 *
18911 * @class
18912 * @extends OO.ui.SelectWidget
18913 * @mixins OO.ui.mixin.TabIndexedElement
18914 *
18915 * @constructor
18916 * @param {Object} [config] Configuration options
18917 */
18918 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
18919 // Parent constructor
18920 OO.ui.TabSelectWidget.parent.call( this, config );
18921
18922 // Mixin constructors
18923 OO.ui.mixin.TabIndexedElement.call( this, config );
18924
18925 // Events
18926 this.$element.on( {
18927 focus: this.bindKeyDownListener.bind( this ),
18928 blur: this.unbindKeyDownListener.bind( this )
18929 } );
18930
18931 // Initialization
18932 this.$element.addClass( 'oo-ui-tabSelectWidget' );
18933 };
18934
18935 /* Setup */
18936
18937 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
18938 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
18939
18940 /**
18941 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18942 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18943 * (to adjust the value in increments) to allow the user to enter a number.
18944 *
18945 * @example
18946 * // Example: A NumberInputWidget.
18947 * var numberInput = new OO.ui.NumberInputWidget( {
18948 * label: 'NumberInputWidget',
18949 * input: { value: 5, min: 1, max: 10 }
18950 * } );
18951 * $( 'body' ).append( numberInput.$element );
18952 *
18953 * @class
18954 * @extends OO.ui.Widget
18955 *
18956 * @constructor
18957 * @param {Object} [config] Configuration options
18958 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18959 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18960 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18961 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18962 * @cfg {number} [min=-Infinity] Minimum allowed value
18963 * @cfg {number} [max=Infinity] Maximum allowed value
18964 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18965 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18966 */
18967 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
18968 // Configuration initialization
18969 config = $.extend( {
18970 isInteger: false,
18971 min: -Infinity,
18972 max: Infinity,
18973 step: 1,
18974 pageStep: null
18975 }, config );
18976
18977 // Parent constructor
18978 OO.ui.NumberInputWidget.parent.call( this, config );
18979
18980 // Properties
18981 this.input = new OO.ui.TextInputWidget( $.extend(
18982 {
18983 disabled: this.isDisabled()
18984 },
18985 config.input
18986 ) );
18987 this.minusButton = new OO.ui.ButtonWidget( $.extend(
18988 {
18989 disabled: this.isDisabled(),
18990 tabIndex: -1
18991 },
18992 config.minusButton,
18993 {
18994 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
18995 label: '−'
18996 }
18997 ) );
18998 this.plusButton = new OO.ui.ButtonWidget( $.extend(
18999 {
19000 disabled: this.isDisabled(),
19001 tabIndex: -1
19002 },
19003 config.plusButton,
19004 {
19005 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
19006 label: '+'
19007 }
19008 ) );
19009
19010 // Events
19011 this.input.connect( this, {
19012 change: this.emit.bind( this, 'change' ),
19013 enter: this.emit.bind( this, 'enter' )
19014 } );
19015 this.input.$input.on( {
19016 keydown: this.onKeyDown.bind( this ),
19017 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19018 } );
19019 this.plusButton.connect( this, {
19020 click: [ 'onButtonClick', +1 ]
19021 } );
19022 this.minusButton.connect( this, {
19023 click: [ 'onButtonClick', -1 ]
19024 } );
19025
19026 // Initialization
19027 this.setIsInteger( !!config.isInteger );
19028 this.setRange( config.min, config.max );
19029 this.setStep( config.step, config.pageStep );
19030
19031 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19032 .append(
19033 this.minusButton.$element,
19034 this.input.$element,
19035 this.plusButton.$element
19036 );
19037 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19038 this.input.setValidation( this.validateNumber.bind( this ) );
19039 };
19040
19041 /* Setup */
19042
19043 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19044
19045 /* Events */
19046
19047 /**
19048 * A `change` event is emitted when the value of the input changes.
19049 *
19050 * @event change
19051 */
19052
19053 /**
19054 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19055 *
19056 * @event enter
19057 */
19058
19059 /* Methods */
19060
19061 /**
19062 * Set whether only integers are allowed
19063 * @param {boolean} flag
19064 */
19065 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19066 this.isInteger = !!flag;
19067 this.input.setValidityFlag();
19068 };
19069
19070 /**
19071 * Get whether only integers are allowed
19072 * @return {boolean} Flag value
19073 */
19074 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19075 return this.isInteger;
19076 };
19077
19078 /**
19079 * Set the range of allowed values
19080 * @param {number} min Minimum allowed value
19081 * @param {number} max Maximum allowed value
19082 */
19083 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19084 if ( min > max ) {
19085 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19086 }
19087 this.min = min;
19088 this.max = max;
19089 this.input.setValidityFlag();
19090 };
19091
19092 /**
19093 * Get the current range
19094 * @return {number[]} Minimum and maximum values
19095 */
19096 OO.ui.NumberInputWidget.prototype.getRange = function () {
19097 return [ this.min, this.max ];
19098 };
19099
19100 /**
19101 * Set the stepping deltas
19102 * @param {number} step Normal step
19103 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19104 */
19105 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19106 if ( step <= 0 ) {
19107 throw new Error( 'Step value must be positive' );
19108 }
19109 if ( pageStep === null ) {
19110 pageStep = step * 10;
19111 } else if ( pageStep <= 0 ) {
19112 throw new Error( 'Page step value must be positive' );
19113 }
19114 this.step = step;
19115 this.pageStep = pageStep;
19116 };
19117
19118 /**
19119 * Get the current stepping values
19120 * @return {number[]} Step and page step
19121 */
19122 OO.ui.NumberInputWidget.prototype.getStep = function () {
19123 return [ this.step, this.pageStep ];
19124 };
19125
19126 /**
19127 * Get the current value of the widget
19128 * @return {string}
19129 */
19130 OO.ui.NumberInputWidget.prototype.getValue = function () {
19131 return this.input.getValue();
19132 };
19133
19134 /**
19135 * Get the current value of the widget as a number
19136 * @return {number} May be NaN, or an invalid number
19137 */
19138 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19139 return +this.input.getValue();
19140 };
19141
19142 /**
19143 * Set the value of the widget
19144 * @param {string} value Invalid values are allowed
19145 */
19146 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19147 this.input.setValue( value );
19148 };
19149
19150 /**
19151 * Adjust the value of the widget
19152 * @param {number} delta Adjustment amount
19153 */
19154 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19155 var n, v = this.getNumericValue();
19156
19157 delta = +delta;
19158 if ( isNaN( delta ) || !isFinite( delta ) ) {
19159 throw new Error( 'Delta must be a finite number' );
19160 }
19161
19162 if ( isNaN( v ) ) {
19163 n = 0;
19164 } else {
19165 n = v + delta;
19166 n = Math.max( Math.min( n, this.max ), this.min );
19167 if ( this.isInteger ) {
19168 n = Math.round( n );
19169 }
19170 }
19171
19172 if ( n !== v ) {
19173 this.setValue( n );
19174 }
19175 };
19176
19177 /**
19178 * Validate input
19179 * @private
19180 * @param {string} value Field value
19181 * @return {boolean}
19182 */
19183 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19184 var n = +value;
19185 if ( isNaN( n ) || !isFinite( n ) ) {
19186 return false;
19187 }
19188
19189 /*jshint bitwise: false */
19190 if ( this.isInteger && ( n | 0 ) !== n ) {
19191 return false;
19192 }
19193 /*jshint bitwise: true */
19194
19195 if ( n < this.min || n > this.max ) {
19196 return false;
19197 }
19198
19199 return true;
19200 };
19201
19202 /**
19203 * Handle mouse click events.
19204 *
19205 * @private
19206 * @param {number} dir +1 or -1
19207 */
19208 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19209 this.adjustValue( dir * this.step );
19210 };
19211
19212 /**
19213 * Handle mouse wheel events.
19214 *
19215 * @private
19216 * @param {jQuery.Event} event
19217 */
19218 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19219 var delta = 0;
19220
19221 // Standard 'wheel' event
19222 if ( event.originalEvent.deltaMode !== undefined ) {
19223 this.sawWheelEvent = true;
19224 }
19225 if ( event.originalEvent.deltaY ) {
19226 delta = -event.originalEvent.deltaY;
19227 } else if ( event.originalEvent.deltaX ) {
19228 delta = event.originalEvent.deltaX;
19229 }
19230
19231 // Non-standard events
19232 if ( !this.sawWheelEvent ) {
19233 if ( event.originalEvent.wheelDeltaX ) {
19234 delta = -event.originalEvent.wheelDeltaX;
19235 } else if ( event.originalEvent.wheelDeltaY ) {
19236 delta = event.originalEvent.wheelDeltaY;
19237 } else if ( event.originalEvent.wheelDelta ) {
19238 delta = event.originalEvent.wheelDelta;
19239 } else if ( event.originalEvent.detail ) {
19240 delta = -event.originalEvent.detail;
19241 }
19242 }
19243
19244 if ( delta ) {
19245 delta = delta < 0 ? -1 : 1;
19246 this.adjustValue( delta * this.step );
19247 }
19248
19249 return false;
19250 };
19251
19252 /**
19253 * Handle key down events.
19254 *
19255 *
19256 * @private
19257 * @param {jQuery.Event} e Key down event
19258 */
19259 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19260 if ( !this.isDisabled() ) {
19261 switch ( e.which ) {
19262 case OO.ui.Keys.UP:
19263 this.adjustValue( this.step );
19264 return false;
19265 case OO.ui.Keys.DOWN:
19266 this.adjustValue( -this.step );
19267 return false;
19268 case OO.ui.Keys.PAGEUP:
19269 this.adjustValue( this.pageStep );
19270 return false;
19271 case OO.ui.Keys.PAGEDOWN:
19272 this.adjustValue( -this.pageStep );
19273 return false;
19274 }
19275 }
19276 };
19277
19278 /**
19279 * @inheritdoc
19280 */
19281 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19282 // Parent method
19283 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19284
19285 if ( this.input ) {
19286 this.input.setDisabled( this.isDisabled() );
19287 }
19288 if ( this.minusButton ) {
19289 this.minusButton.setDisabled( this.isDisabled() );
19290 }
19291 if ( this.plusButton ) {
19292 this.plusButton.setDisabled( this.isDisabled() );
19293 }
19294
19295 return this;
19296 };
19297
19298 /**
19299 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19300 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19301 * visually by a slider in the leftmost position.
19302 *
19303 * @example
19304 * // Toggle switches in the 'off' and 'on' position.
19305 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19306 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19307 * value: true
19308 * } );
19309 *
19310 * // Create a FieldsetLayout to layout and label switches
19311 * var fieldset = new OO.ui.FieldsetLayout( {
19312 * label: 'Toggle switches'
19313 * } );
19314 * fieldset.addItems( [
19315 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19316 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19317 * ] );
19318 * $( 'body' ).append( fieldset.$element );
19319 *
19320 * @class
19321 * @extends OO.ui.ToggleWidget
19322 * @mixins OO.ui.mixin.TabIndexedElement
19323 *
19324 * @constructor
19325 * @param {Object} [config] Configuration options
19326 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19327 * By default, the toggle switch is in the 'off' position.
19328 */
19329 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19330 // Parent constructor
19331 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19332
19333 // Mixin constructors
19334 OO.ui.mixin.TabIndexedElement.call( this, config );
19335
19336 // Properties
19337 this.dragging = false;
19338 this.dragStart = null;
19339 this.sliding = false;
19340 this.$glow = $( '<span>' );
19341 this.$grip = $( '<span>' );
19342
19343 // Events
19344 this.$element.on( {
19345 click: this.onClick.bind( this ),
19346 keypress: this.onKeyPress.bind( this )
19347 } );
19348
19349 // Initialization
19350 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19351 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19352 this.$element
19353 .addClass( 'oo-ui-toggleSwitchWidget' )
19354 .attr( 'role', 'checkbox' )
19355 .append( this.$glow, this.$grip );
19356 };
19357
19358 /* Setup */
19359
19360 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19361 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19362
19363 /* Methods */
19364
19365 /**
19366 * Handle mouse click events.
19367 *
19368 * @private
19369 * @param {jQuery.Event} e Mouse click event
19370 */
19371 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19372 if ( !this.isDisabled() && e.which === 1 ) {
19373 this.setValue( !this.value );
19374 }
19375 return false;
19376 };
19377
19378 /**
19379 * Handle key press events.
19380 *
19381 * @private
19382 * @param {jQuery.Event} e Key press event
19383 */
19384 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19385 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19386 this.setValue( !this.value );
19387 return false;
19388 }
19389 };
19390
19391 /*!
19392 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19393 */
19394
19395 /**
19396 * @inheritdoc OO.ui.mixin.ButtonElement
19397 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19398 */
19399 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19400
19401 /**
19402 * @inheritdoc OO.ui.mixin.ClippableElement
19403 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19404 */
19405 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19406
19407 /**
19408 * @inheritdoc OO.ui.mixin.DraggableElement
19409 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19410 */
19411 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19412
19413 /**
19414 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19415 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19416 */
19417 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19418
19419 /**
19420 * @inheritdoc OO.ui.mixin.FlaggedElement
19421 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19422 */
19423 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19424
19425 /**
19426 * @inheritdoc OO.ui.mixin.GroupElement
19427 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19428 */
19429 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19430
19431 /**
19432 * @inheritdoc OO.ui.mixin.GroupWidget
19433 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19434 */
19435 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19436
19437 /**
19438 * @inheritdoc OO.ui.mixin.IconElement
19439 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19440 */
19441 OO.ui.IconElement = OO.ui.mixin.IconElement;
19442
19443 /**
19444 * @inheritdoc OO.ui.mixin.IndicatorElement
19445 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19446 */
19447 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19448
19449 /**
19450 * @inheritdoc OO.ui.mixin.ItemWidget
19451 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19452 */
19453 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19454
19455 /**
19456 * @inheritdoc OO.ui.mixin.LabelElement
19457 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19458 */
19459 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19460
19461 /**
19462 * @inheritdoc OO.ui.mixin.LookupElement
19463 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19464 */
19465 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19466
19467 /**
19468 * @inheritdoc OO.ui.mixin.PendingElement
19469 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19470 */
19471 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19472
19473 /**
19474 * @inheritdoc OO.ui.mixin.PopupElement
19475 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19476 */
19477 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19478
19479 /**
19480 * @inheritdoc OO.ui.mixin.TabIndexedElement
19481 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19482 */
19483 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19484
19485 /**
19486 * @inheritdoc OO.ui.mixin.TitledElement
19487 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19488 */
19489 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19490
19491 }( OO ) );