Merge "Move query rewriting into search backend"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.8
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-09-08T20:55:55Z
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 // Label for the file selection widget's select file button
283 'ooui-selectfile-button-select': 'Select a file',
284 // Label for the file selection widget if file selection is not supported
285 'ooui-selectfile-not-supported': 'File selection is not supported',
286 // Label for the file selection widget when no file is currently selected
287 'ooui-selectfile-placeholder': 'No file is selected',
288 // Label for the file selection widget's drop target
289 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
290 // Semicolon separator
291 'ooui-semicolon-separator': '; '
292 };
293
294 /**
295 * Get a localized message.
296 *
297 * In environments that provide a localization system, this function should be overridden to
298 * return the message translated in the user's language. The default implementation always returns
299 * English messages.
300 *
301 * After the message key, message parameters may optionally be passed. In the default implementation,
302 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
303 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
304 * they support unnamed, ordered message parameters.
305 *
306 * @abstract
307 * @param {string} key Message key
308 * @param {Mixed...} [params] Message parameters
309 * @return {string} Translated message with parameters substituted
310 */
311 OO.ui.msg = function ( key ) {
312 var message = messages[ key ],
313 params = Array.prototype.slice.call( arguments, 1 );
314 if ( typeof message === 'string' ) {
315 // Perform $1 substitution
316 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
317 var i = parseInt( n, 10 );
318 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
319 } );
320 } else {
321 // Return placeholder if message not found
322 message = '[' + key + ']';
323 }
324 return message;
325 };
326
327 /**
328 * Package a message and arguments for deferred resolution.
329 *
330 * Use this when you are statically specifying a message and the message may not yet be present.
331 *
332 * @param {string} key Message key
333 * @param {Mixed...} [params] Message parameters
334 * @return {Function} Function that returns the resolved message when executed
335 */
336 OO.ui.deferMsg = function () {
337 var args = arguments;
338 return function () {
339 return OO.ui.msg.apply( OO.ui, args );
340 };
341 };
342
343 /**
344 * Resolve a message.
345 *
346 * If the message is a function it will be executed, otherwise it will pass through directly.
347 *
348 * @param {Function|string} msg Deferred message, or message text
349 * @return {string} Resolved message
350 */
351 OO.ui.resolveMsg = function ( msg ) {
352 if ( $.isFunction( msg ) ) {
353 return msg();
354 }
355 return msg;
356 };
357
358 /**
359 * @param {string} url
360 * @return {boolean}
361 */
362 OO.ui.isSafeUrl = function ( url ) {
363 var protocol,
364 // Keep in sync with php/Tag.php
365 whitelist = [
366 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
367 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
368 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
369 ];
370
371 if ( url.indexOf( ':' ) === -1 ) {
372 // No protocol, safe
373 return true;
374 }
375
376 protocol = url.split( ':', 1 )[ 0 ] + ':';
377 if ( !protocol.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
378 // Not a valid protocol, safe
379 return true;
380 }
381
382 // Safe if in the whitelist
383 return whitelist.indexOf( protocol ) !== -1;
384 };
385
386 } )();
387
388 /*!
389 * Mixin namespace.
390 */
391
392 /**
393 * Namespace for OOjs UI mixins.
394 *
395 * Mixins are named according to the type of object they are intended to
396 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
397 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
398 * is intended to be mixed in to an instance of OO.ui.Widget.
399 *
400 * @class
401 * @singleton
402 */
403 OO.ui.mixin = {};
404
405 /**
406 * PendingElement is a mixin that is used to create elements that notify users that something is happening
407 * and that they should wait before proceeding. The pending state is visually represented with a pending
408 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
409 * field of a {@link OO.ui.TextInputWidget text input widget}.
410 *
411 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
412 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
413 * in process dialogs.
414 *
415 * @example
416 * function MessageDialog( config ) {
417 * MessageDialog.parent.call( this, config );
418 * }
419 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
420 *
421 * MessageDialog.static.actions = [
422 * { action: 'save', label: 'Done', flags: 'primary' },
423 * { label: 'Cancel', flags: 'safe' }
424 * ];
425 *
426 * MessageDialog.prototype.initialize = function () {
427 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
428 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
429 * 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>' );
430 * this.$body.append( this.content.$element );
431 * };
432 * MessageDialog.prototype.getBodyHeight = function () {
433 * return 100;
434 * }
435 * MessageDialog.prototype.getActionProcess = function ( action ) {
436 * var dialog = this;
437 * if ( action === 'save' ) {
438 * dialog.getActions().get({actions: 'save'})[0].pushPending();
439 * return new OO.ui.Process()
440 * .next( 1000 )
441 * .next( function () {
442 * dialog.getActions().get({actions: 'save'})[0].popPending();
443 * } );
444 * }
445 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
446 * };
447 *
448 * var windowManager = new OO.ui.WindowManager();
449 * $( 'body' ).append( windowManager.$element );
450 *
451 * var dialog = new MessageDialog();
452 * windowManager.addWindows( [ dialog ] );
453 * windowManager.openWindow( dialog );
454 *
455 * @abstract
456 * @class
457 *
458 * @constructor
459 * @param {Object} [config] Configuration options
460 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
461 */
462 OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) {
463 // Configuration initialization
464 config = config || {};
465
466 // Properties
467 this.pending = 0;
468 this.$pending = null;
469
470 // Initialisation
471 this.setPendingElement( config.$pending || this.$element );
472 };
473
474 /* Setup */
475
476 OO.initClass( OO.ui.mixin.PendingElement );
477
478 /* Methods */
479
480 /**
481 * Set the pending element (and clean up any existing one).
482 *
483 * @param {jQuery} $pending The element to set to pending.
484 */
485 OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) {
486 if ( this.$pending ) {
487 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
488 }
489
490 this.$pending = $pending;
491 if ( this.pending > 0 ) {
492 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
493 }
494 };
495
496 /**
497 * Check if an element is pending.
498 *
499 * @return {boolean} Element is pending
500 */
501 OO.ui.mixin.PendingElement.prototype.isPending = function () {
502 return !!this.pending;
503 };
504
505 /**
506 * Increase the pending counter. The pending state will remain active until the counter is zero
507 * (i.e., the number of calls to #pushPending and #popPending is the same).
508 *
509 * @chainable
510 */
511 OO.ui.mixin.PendingElement.prototype.pushPending = function () {
512 if ( this.pending === 0 ) {
513 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
514 this.updateThemeClasses();
515 }
516 this.pending++;
517
518 return this;
519 };
520
521 /**
522 * Decrease the pending counter. The pending state will remain active until the counter is zero
523 * (i.e., the number of calls to #pushPending and #popPending is the same).
524 *
525 * @chainable
526 */
527 OO.ui.mixin.PendingElement.prototype.popPending = function () {
528 if ( this.pending === 1 ) {
529 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
530 this.updateThemeClasses();
531 }
532 this.pending = Math.max( 0, this.pending - 1 );
533
534 return this;
535 };
536
537 /**
538 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
539 * Actions can be made available for specific contexts (modes) and circumstances
540 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
541 *
542 * ActionSets contain two types of actions:
543 *
544 * - 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.
545 * - Other: Other actions include all non-special visible actions.
546 *
547 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
548 *
549 * @example
550 * // Example: An action set used in a process dialog
551 * function MyProcessDialog( config ) {
552 * MyProcessDialog.parent.call( this, config );
553 * }
554 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
555 * MyProcessDialog.static.title = 'An action set in a process dialog';
556 * // An action set that uses modes ('edit' and 'help' mode, in this example).
557 * MyProcessDialog.static.actions = [
558 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
559 * { action: 'help', modes: 'edit', label: 'Help' },
560 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
561 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
562 * ];
563 *
564 * MyProcessDialog.prototype.initialize = function () {
565 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
566 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
567 * 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>' );
568 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
569 * 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>' );
570 * this.stackLayout = new OO.ui.StackLayout( {
571 * items: [ this.panel1, this.panel2 ]
572 * } );
573 * this.$body.append( this.stackLayout.$element );
574 * };
575 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
576 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
577 * .next( function () {
578 * this.actions.setMode( 'edit' );
579 * }, this );
580 * };
581 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
582 * if ( action === 'help' ) {
583 * this.actions.setMode( 'help' );
584 * this.stackLayout.setItem( this.panel2 );
585 * } else if ( action === 'back' ) {
586 * this.actions.setMode( 'edit' );
587 * this.stackLayout.setItem( this.panel1 );
588 * } else if ( action === 'continue' ) {
589 * var dialog = this;
590 * return new OO.ui.Process( function () {
591 * dialog.close();
592 * } );
593 * }
594 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
595 * };
596 * MyProcessDialog.prototype.getBodyHeight = function () {
597 * return this.panel1.$element.outerHeight( true );
598 * };
599 * var windowManager = new OO.ui.WindowManager();
600 * $( 'body' ).append( windowManager.$element );
601 * var dialog = new MyProcessDialog( {
602 * size: 'medium'
603 * } );
604 * windowManager.addWindows( [ dialog ] );
605 * windowManager.openWindow( dialog );
606 *
607 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
608 *
609 * @abstract
610 * @class
611 * @mixins OO.EventEmitter
612 *
613 * @constructor
614 * @param {Object} [config] Configuration options
615 */
616 OO.ui.ActionSet = function OoUiActionSet( config ) {
617 // Configuration initialization
618 config = config || {};
619
620 // Mixin constructors
621 OO.EventEmitter.call( this );
622
623 // Properties
624 this.list = [];
625 this.categories = {
626 actions: 'getAction',
627 flags: 'getFlags',
628 modes: 'getModes'
629 };
630 this.categorized = {};
631 this.special = {};
632 this.others = [];
633 this.organized = false;
634 this.changing = false;
635 this.changed = false;
636 };
637
638 /* Setup */
639
640 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
641
642 /* Static Properties */
643
644 /**
645 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
646 * header of a {@link OO.ui.ProcessDialog process dialog}.
647 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
648 *
649 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
650 *
651 * @abstract
652 * @static
653 * @inheritable
654 * @property {string}
655 */
656 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
657
658 /* Events */
659
660 /**
661 * @event click
662 *
663 * A 'click' event is emitted when an action is clicked.
664 *
665 * @param {OO.ui.ActionWidget} action Action that was clicked
666 */
667
668 /**
669 * @event resize
670 *
671 * A 'resize' event is emitted when an action widget is resized.
672 *
673 * @param {OO.ui.ActionWidget} action Action that was resized
674 */
675
676 /**
677 * @event add
678 *
679 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
680 *
681 * @param {OO.ui.ActionWidget[]} added Actions added
682 */
683
684 /**
685 * @event remove
686 *
687 * A 'remove' event is emitted when actions are {@link #method-remove removed}
688 * or {@link #clear cleared}.
689 *
690 * @param {OO.ui.ActionWidget[]} added Actions removed
691 */
692
693 /**
694 * @event change
695 *
696 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
697 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
698 *
699 */
700
701 /* Methods */
702
703 /**
704 * Handle action change events.
705 *
706 * @private
707 * @fires change
708 */
709 OO.ui.ActionSet.prototype.onActionChange = function () {
710 this.organized = false;
711 if ( this.changing ) {
712 this.changed = true;
713 } else {
714 this.emit( 'change' );
715 }
716 };
717
718 /**
719 * Check if an action is one of the special actions.
720 *
721 * @param {OO.ui.ActionWidget} action Action to check
722 * @return {boolean} Action is special
723 */
724 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
725 var flag;
726
727 for ( flag in this.special ) {
728 if ( action === this.special[ flag ] ) {
729 return true;
730 }
731 }
732
733 return false;
734 };
735
736 /**
737 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
738 * or ‘disabled’.
739 *
740 * @param {Object} [filters] Filters to use, omit to get all actions
741 * @param {string|string[]} [filters.actions] Actions that action widgets must have
742 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
743 * @param {string|string[]} [filters.modes] Modes that action widgets must have
744 * @param {boolean} [filters.visible] Action widgets must be visible
745 * @param {boolean} [filters.disabled] Action widgets must be disabled
746 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
747 */
748 OO.ui.ActionSet.prototype.get = function ( filters ) {
749 var i, len, list, category, actions, index, match, matches;
750
751 if ( filters ) {
752 this.organize();
753
754 // Collect category candidates
755 matches = [];
756 for ( category in this.categorized ) {
757 list = filters[ category ];
758 if ( list ) {
759 if ( !Array.isArray( list ) ) {
760 list = [ list ];
761 }
762 for ( i = 0, len = list.length; i < len; i++ ) {
763 actions = this.categorized[ category ][ list[ i ] ];
764 if ( Array.isArray( actions ) ) {
765 matches.push.apply( matches, actions );
766 }
767 }
768 }
769 }
770 // Remove by boolean filters
771 for ( i = 0, len = matches.length; i < len; i++ ) {
772 match = matches[ i ];
773 if (
774 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
775 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
776 ) {
777 matches.splice( i, 1 );
778 len--;
779 i--;
780 }
781 }
782 // Remove duplicates
783 for ( i = 0, len = matches.length; i < len; i++ ) {
784 match = matches[ i ];
785 index = matches.lastIndexOf( match );
786 while ( index !== i ) {
787 matches.splice( index, 1 );
788 len--;
789 index = matches.lastIndexOf( match );
790 }
791 }
792 return matches;
793 }
794 return this.list.slice();
795 };
796
797 /**
798 * Get 'special' actions.
799 *
800 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
801 * Special flags can be configured in subclasses by changing the static #specialFlags property.
802 *
803 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
804 */
805 OO.ui.ActionSet.prototype.getSpecial = function () {
806 this.organize();
807 return $.extend( {}, this.special );
808 };
809
810 /**
811 * Get 'other' actions.
812 *
813 * Other actions include all non-special visible action widgets.
814 *
815 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
816 */
817 OO.ui.ActionSet.prototype.getOthers = function () {
818 this.organize();
819 return this.others.slice();
820 };
821
822 /**
823 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
824 * to be available in the specified mode will be made visible. All other actions will be hidden.
825 *
826 * @param {string} mode The mode. Only actions configured to be available in the specified
827 * mode will be made visible.
828 * @chainable
829 * @fires toggle
830 * @fires change
831 */
832 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
833 var i, len, action;
834
835 this.changing = true;
836 for ( i = 0, len = this.list.length; i < len; i++ ) {
837 action = this.list[ i ];
838 action.toggle( action.hasMode( mode ) );
839 }
840
841 this.organized = false;
842 this.changing = false;
843 this.emit( 'change' );
844
845 return this;
846 };
847
848 /**
849 * Set the abilities of the specified actions.
850 *
851 * Action widgets that are configured with the specified actions will be enabled
852 * or disabled based on the boolean values specified in the `actions`
853 * parameter.
854 *
855 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
856 * values that indicate whether or not the action should be enabled.
857 * @chainable
858 */
859 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
860 var i, len, action, item;
861
862 for ( i = 0, len = this.list.length; i < len; i++ ) {
863 item = this.list[ i ];
864 action = item.getAction();
865 if ( actions[ action ] !== undefined ) {
866 item.setDisabled( !actions[ action ] );
867 }
868 }
869
870 return this;
871 };
872
873 /**
874 * Executes a function once per action.
875 *
876 * When making changes to multiple actions, use this method instead of iterating over the actions
877 * manually to defer emitting a #change event until after all actions have been changed.
878 *
879 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
880 * @param {Function} callback Callback to run for each action; callback is invoked with three
881 * arguments: the action, the action's index, the list of actions being iterated over
882 * @chainable
883 */
884 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
885 this.changed = false;
886 this.changing = true;
887 this.get( filter ).forEach( callback );
888 this.changing = false;
889 if ( this.changed ) {
890 this.emit( 'change' );
891 }
892
893 return this;
894 };
895
896 /**
897 * Add action widgets to the action set.
898 *
899 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
900 * @chainable
901 * @fires add
902 * @fires change
903 */
904 OO.ui.ActionSet.prototype.add = function ( actions ) {
905 var i, len, action;
906
907 this.changing = true;
908 for ( i = 0, len = actions.length; i < len; i++ ) {
909 action = actions[ i ];
910 action.connect( this, {
911 click: [ 'emit', 'click', action ],
912 resize: [ 'emit', 'resize', action ],
913 toggle: [ 'onActionChange' ]
914 } );
915 this.list.push( action );
916 }
917 this.organized = false;
918 this.emit( 'add', actions );
919 this.changing = false;
920 this.emit( 'change' );
921
922 return this;
923 };
924
925 /**
926 * Remove action widgets from the set.
927 *
928 * To remove all actions, you may wish to use the #clear method instead.
929 *
930 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
931 * @chainable
932 * @fires remove
933 * @fires change
934 */
935 OO.ui.ActionSet.prototype.remove = function ( actions ) {
936 var i, len, index, action;
937
938 this.changing = true;
939 for ( i = 0, len = actions.length; i < len; i++ ) {
940 action = actions[ i ];
941 index = this.list.indexOf( action );
942 if ( index !== -1 ) {
943 action.disconnect( this );
944 this.list.splice( index, 1 );
945 }
946 }
947 this.organized = false;
948 this.emit( 'remove', actions );
949 this.changing = false;
950 this.emit( 'change' );
951
952 return this;
953 };
954
955 /**
956 * Remove all action widets from the set.
957 *
958 * To remove only specified actions, use the {@link #method-remove remove} method instead.
959 *
960 * @chainable
961 * @fires remove
962 * @fires change
963 */
964 OO.ui.ActionSet.prototype.clear = function () {
965 var i, len, action,
966 removed = this.list.slice();
967
968 this.changing = true;
969 for ( i = 0, len = this.list.length; i < len; i++ ) {
970 action = this.list[ i ];
971 action.disconnect( this );
972 }
973
974 this.list = [];
975
976 this.organized = false;
977 this.emit( 'remove', removed );
978 this.changing = false;
979 this.emit( 'change' );
980
981 return this;
982 };
983
984 /**
985 * Organize actions.
986 *
987 * This is called whenever organized information is requested. It will only reorganize the actions
988 * if something has changed since the last time it ran.
989 *
990 * @private
991 * @chainable
992 */
993 OO.ui.ActionSet.prototype.organize = function () {
994 var i, iLen, j, jLen, flag, action, category, list, item, special,
995 specialFlags = this.constructor.static.specialFlags;
996
997 if ( !this.organized ) {
998 this.categorized = {};
999 this.special = {};
1000 this.others = [];
1001 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
1002 action = this.list[ i ];
1003 if ( action.isVisible() ) {
1004 // Populate categories
1005 for ( category in this.categories ) {
1006 if ( !this.categorized[ category ] ) {
1007 this.categorized[ category ] = {};
1008 }
1009 list = action[ this.categories[ category ] ]();
1010 if ( !Array.isArray( list ) ) {
1011 list = [ list ];
1012 }
1013 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
1014 item = list[ j ];
1015 if ( !this.categorized[ category ][ item ] ) {
1016 this.categorized[ category ][ item ] = [];
1017 }
1018 this.categorized[ category ][ item ].push( action );
1019 }
1020 }
1021 // Populate special/others
1022 special = false;
1023 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
1024 flag = specialFlags[ j ];
1025 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
1026 this.special[ flag ] = action;
1027 special = true;
1028 break;
1029 }
1030 }
1031 if ( !special ) {
1032 this.others.push( action );
1033 }
1034 }
1035 }
1036 this.organized = true;
1037 }
1038
1039 return this;
1040 };
1041
1042 /**
1043 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1044 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1045 * connected to them and can't be interacted with.
1046 *
1047 * @abstract
1048 * @class
1049 *
1050 * @constructor
1051 * @param {Object} [config] Configuration options
1052 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1053 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1054 * for an example.
1055 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1056 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1057 * @cfg {string} [text] Text to insert
1058 * @cfg {Array} [content] An array of content elements to append (after #text).
1059 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1060 * Instances of OO.ui.Element will have their $element appended.
1061 * @cfg {jQuery} [$content] Content elements to append (after #text)
1062 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1063 * Data can also be specified with the #setData method.
1064 */
1065 OO.ui.Element = function OoUiElement( config ) {
1066 // Configuration initialization
1067 config = config || {};
1068
1069 // Properties
1070 this.$ = $;
1071 this.visible = true;
1072 this.data = config.data;
1073 this.$element = config.$element ||
1074 $( document.createElement( this.getTagName() ) );
1075 this.elementGroup = null;
1076 this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses );
1077
1078 // Initialization
1079 if ( Array.isArray( config.classes ) ) {
1080 this.$element.addClass( config.classes.join( ' ' ) );
1081 }
1082 if ( config.id ) {
1083 this.$element.attr( 'id', config.id );
1084 }
1085 if ( config.text ) {
1086 this.$element.text( config.text );
1087 }
1088 if ( config.content ) {
1089 // The `content` property treats plain strings as text; use an
1090 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1091 // appropriate $element appended.
1092 this.$element.append( config.content.map( function ( v ) {
1093 if ( typeof v === 'string' ) {
1094 // Escape string so it is properly represented in HTML.
1095 return document.createTextNode( v );
1096 } else if ( v instanceof OO.ui.HtmlSnippet ) {
1097 // Bypass escaping.
1098 return v.toString();
1099 } else if ( v instanceof OO.ui.Element ) {
1100 return v.$element;
1101 }
1102 return v;
1103 } ) );
1104 }
1105 if ( config.$content ) {
1106 // The `$content` property treats plain strings as HTML.
1107 this.$element.append( config.$content );
1108 }
1109 };
1110
1111 /* Setup */
1112
1113 OO.initClass( OO.ui.Element );
1114
1115 /* Static Properties */
1116
1117 /**
1118 * The name of the HTML tag used by the element.
1119 *
1120 * The static value may be ignored if the #getTagName method is overridden.
1121 *
1122 * @static
1123 * @inheritable
1124 * @property {string}
1125 */
1126 OO.ui.Element.static.tagName = 'div';
1127
1128 /* Static Methods */
1129
1130 /**
1131 * Reconstitute a JavaScript object corresponding to a widget created
1132 * by the PHP implementation.
1133 *
1134 * @param {string|HTMLElement|jQuery} idOrNode
1135 * A DOM id (if a string) or node for the widget to infuse.
1136 * @return {OO.ui.Element}
1137 * The `OO.ui.Element` corresponding to this (infusable) document node.
1138 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1139 * the value returned is a newly-created Element wrapping around the existing
1140 * DOM node.
1141 */
1142 OO.ui.Element.static.infuse = function ( idOrNode ) {
1143 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false );
1144 // Verify that the type matches up.
1145 // FIXME: uncomment after T89721 is fixed (see T90929)
1146 /*
1147 if ( !( obj instanceof this['class'] ) ) {
1148 throw new Error( 'Infusion type mismatch!' );
1149 }
1150 */
1151 return obj;
1152 };
1153
1154 /**
1155 * Implementation helper for `infuse`; skips the type check and has an
1156 * extra property so that only the top-level invocation touches the DOM.
1157 * @private
1158 * @param {string|HTMLElement|jQuery} idOrNode
1159 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1160 * when the top-level widget of this infusion is inserted into DOM,
1161 * replacing the original node; or false for top-level invocation.
1162 * @return {OO.ui.Element}
1163 */
1164 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) {
1165 // look for a cached result of a previous infusion.
1166 var id, $elem, data, cls, parts, parent, obj, top, state;
1167 if ( typeof idOrNode === 'string' ) {
1168 id = idOrNode;
1169 $elem = $( document.getElementById( id ) );
1170 } else {
1171 $elem = $( idOrNode );
1172 id = $elem.attr( 'id' );
1173 }
1174 if ( !$elem.length ) {
1175 throw new Error( 'Widget not found: ' + id );
1176 }
1177 data = $elem.data( 'ooui-infused' ) || $elem[ 0 ].oouiInfused;
1178 if ( data ) {
1179 // cached!
1180 if ( data === true ) {
1181 throw new Error( 'Circular dependency! ' + id );
1182 }
1183 return data;
1184 }
1185 data = $elem.attr( 'data-ooui' );
1186 if ( !data ) {
1187 throw new Error( 'No infusion data found: ' + id );
1188 }
1189 try {
1190 data = $.parseJSON( data );
1191 } catch ( _ ) {
1192 data = null;
1193 }
1194 if ( !( data && data._ ) ) {
1195 throw new Error( 'No valid infusion data found: ' + id );
1196 }
1197 if ( data._ === 'Tag' ) {
1198 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1199 return new OO.ui.Element( { $element: $elem } );
1200 }
1201 parts = data._.split( '.' );
1202 cls = OO.getProp.apply( OO, [ window ].concat( parts ) );
1203 if ( cls === undefined ) {
1204 // The PHP output might be old and not including the "OO.ui" prefix
1205 // TODO: Remove this back-compat after next major release
1206 cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) );
1207 if ( cls === undefined ) {
1208 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1209 }
1210 }
1211
1212 // Verify that we're creating an OO.ui.Element instance
1213 parent = cls.parent;
1214
1215 while ( parent !== undefined ) {
1216 if ( parent === OO.ui.Element ) {
1217 // Safe
1218 break;
1219 }
1220
1221 parent = parent.parent;
1222 }
1223
1224 if ( parent !== OO.ui.Element ) {
1225 throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ );
1226 }
1227
1228 if ( domPromise === false ) {
1229 top = $.Deferred();
1230 domPromise = top.promise();
1231 }
1232 $elem.data( 'ooui-infused', true ); // prevent loops
1233 data.id = id; // implicit
1234 data = OO.copy( data, null, function deserialize( value ) {
1235 if ( OO.isPlainObject( value ) ) {
1236 if ( value.tag ) {
1237 return OO.ui.Element.static.unsafeInfuse( value.tag, domPromise );
1238 }
1239 if ( value.html ) {
1240 return new OO.ui.HtmlSnippet( value.html );
1241 }
1242 }
1243 } );
1244 // jscs:disable requireCapitalizedConstructors
1245 obj = new cls( data ); // rebuild widget
1246 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1247 state = obj.gatherPreInfuseState( $elem );
1248 // now replace old DOM with this new DOM.
1249 if ( top ) {
1250 $elem.replaceWith( obj.$element );
1251 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1252 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1253 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1254 $elem[ 0 ].oouiInfused = obj;
1255 top.resolve();
1256 }
1257 obj.$element.data( 'ooui-infused', obj );
1258 // set the 'data-ooui' attribute so we can identify infused widgets
1259 obj.$element.attr( 'data-ooui', '' );
1260 // restore dynamic state after the new element is inserted into DOM
1261 domPromise.done( obj.restorePreInfuseState.bind( obj, state ) );
1262 return obj;
1263 };
1264
1265 /**
1266 * Get a jQuery function within a specific document.
1267 *
1268 * @static
1269 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1270 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1271 * not in an iframe
1272 * @return {Function} Bound jQuery function
1273 */
1274 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1275 function wrapper( selector ) {
1276 return $( selector, wrapper.context );
1277 }
1278
1279 wrapper.context = this.getDocument( context );
1280
1281 if ( $iframe ) {
1282 wrapper.$iframe = $iframe;
1283 }
1284
1285 return wrapper;
1286 };
1287
1288 /**
1289 * Get the document of an element.
1290 *
1291 * @static
1292 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1293 * @return {HTMLDocument|null} Document object
1294 */
1295 OO.ui.Element.static.getDocument = function ( obj ) {
1296 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1297 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1298 // Empty jQuery selections might have a context
1299 obj.context ||
1300 // HTMLElement
1301 obj.ownerDocument ||
1302 // Window
1303 obj.document ||
1304 // HTMLDocument
1305 ( obj.nodeType === 9 && obj ) ||
1306 null;
1307 };
1308
1309 /**
1310 * Get the window of an element or document.
1311 *
1312 * @static
1313 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1314 * @return {Window} Window object
1315 */
1316 OO.ui.Element.static.getWindow = function ( obj ) {
1317 var doc = this.getDocument( obj );
1318 // Support: IE 8
1319 // Standard Document.defaultView is IE9+
1320 return doc.parentWindow || doc.defaultView;
1321 };
1322
1323 /**
1324 * Get the direction of an element or document.
1325 *
1326 * @static
1327 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1328 * @return {string} Text direction, either 'ltr' or 'rtl'
1329 */
1330 OO.ui.Element.static.getDir = function ( obj ) {
1331 var isDoc, isWin;
1332
1333 if ( obj instanceof jQuery ) {
1334 obj = obj[ 0 ];
1335 }
1336 isDoc = obj.nodeType === 9;
1337 isWin = obj.document !== undefined;
1338 if ( isDoc || isWin ) {
1339 if ( isWin ) {
1340 obj = obj.document;
1341 }
1342 obj = obj.body;
1343 }
1344 return $( obj ).css( 'direction' );
1345 };
1346
1347 /**
1348 * Get the offset between two frames.
1349 *
1350 * TODO: Make this function not use recursion.
1351 *
1352 * @static
1353 * @param {Window} from Window of the child frame
1354 * @param {Window} [to=window] Window of the parent frame
1355 * @param {Object} [offset] Offset to start with, used internally
1356 * @return {Object} Offset object, containing left and top properties
1357 */
1358 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1359 var i, len, frames, frame, rect;
1360
1361 if ( !to ) {
1362 to = window;
1363 }
1364 if ( !offset ) {
1365 offset = { top: 0, left: 0 };
1366 }
1367 if ( from.parent === from ) {
1368 return offset;
1369 }
1370
1371 // Get iframe element
1372 frames = from.parent.document.getElementsByTagName( 'iframe' );
1373 for ( i = 0, len = frames.length; i < len; i++ ) {
1374 if ( frames[ i ].contentWindow === from ) {
1375 frame = frames[ i ];
1376 break;
1377 }
1378 }
1379
1380 // Recursively accumulate offset values
1381 if ( frame ) {
1382 rect = frame.getBoundingClientRect();
1383 offset.left += rect.left;
1384 offset.top += rect.top;
1385 if ( from !== to ) {
1386 this.getFrameOffset( from.parent, offset );
1387 }
1388 }
1389 return offset;
1390 };
1391
1392 /**
1393 * Get the offset between two elements.
1394 *
1395 * The two elements may be in a different frame, but in that case the frame $element is in must
1396 * be contained in the frame $anchor is in.
1397 *
1398 * @static
1399 * @param {jQuery} $element Element whose position to get
1400 * @param {jQuery} $anchor Element to get $element's position relative to
1401 * @return {Object} Translated position coordinates, containing top and left properties
1402 */
1403 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1404 var iframe, iframePos,
1405 pos = $element.offset(),
1406 anchorPos = $anchor.offset(),
1407 elementDocument = this.getDocument( $element ),
1408 anchorDocument = this.getDocument( $anchor );
1409
1410 // If $element isn't in the same document as $anchor, traverse up
1411 while ( elementDocument !== anchorDocument ) {
1412 iframe = elementDocument.defaultView.frameElement;
1413 if ( !iframe ) {
1414 throw new Error( '$element frame is not contained in $anchor frame' );
1415 }
1416 iframePos = $( iframe ).offset();
1417 pos.left += iframePos.left;
1418 pos.top += iframePos.top;
1419 elementDocument = iframe.ownerDocument;
1420 }
1421 pos.left -= anchorPos.left;
1422 pos.top -= anchorPos.top;
1423 return pos;
1424 };
1425
1426 /**
1427 * Get element border sizes.
1428 *
1429 * @static
1430 * @param {HTMLElement} el Element to measure
1431 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1432 */
1433 OO.ui.Element.static.getBorders = function ( el ) {
1434 var doc = el.ownerDocument,
1435 // Support: IE 8
1436 // Standard Document.defaultView is IE9+
1437 win = doc.parentWindow || doc.defaultView,
1438 style = win && win.getComputedStyle ?
1439 win.getComputedStyle( el, null ) :
1440 // Support: IE 8
1441 // Standard getComputedStyle() is IE9+
1442 el.currentStyle,
1443 $el = $( el ),
1444 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1445 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1446 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1447 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1448
1449 return {
1450 top: top,
1451 left: left,
1452 bottom: bottom,
1453 right: right
1454 };
1455 };
1456
1457 /**
1458 * Get dimensions of an element or window.
1459 *
1460 * @static
1461 * @param {HTMLElement|Window} el Element to measure
1462 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1463 */
1464 OO.ui.Element.static.getDimensions = function ( el ) {
1465 var $el, $win,
1466 doc = el.ownerDocument || el.document,
1467 // Support: IE 8
1468 // Standard Document.defaultView is IE9+
1469 win = doc.parentWindow || doc.defaultView;
1470
1471 if ( win === el || el === doc.documentElement ) {
1472 $win = $( win );
1473 return {
1474 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1475 scroll: {
1476 top: $win.scrollTop(),
1477 left: $win.scrollLeft()
1478 },
1479 scrollbar: { right: 0, bottom: 0 },
1480 rect: {
1481 top: 0,
1482 left: 0,
1483 bottom: $win.innerHeight(),
1484 right: $win.innerWidth()
1485 }
1486 };
1487 } else {
1488 $el = $( el );
1489 return {
1490 borders: this.getBorders( el ),
1491 scroll: {
1492 top: $el.scrollTop(),
1493 left: $el.scrollLeft()
1494 },
1495 scrollbar: {
1496 right: $el.innerWidth() - el.clientWidth,
1497 bottom: $el.innerHeight() - el.clientHeight
1498 },
1499 rect: el.getBoundingClientRect()
1500 };
1501 }
1502 };
1503
1504 /**
1505 * Get scrollable object parent
1506 *
1507 * documentElement can't be used to get or set the scrollTop
1508 * property on Blink. Changing and testing its value lets us
1509 * use 'body' or 'documentElement' based on what is working.
1510 *
1511 * https://code.google.com/p/chromium/issues/detail?id=303131
1512 *
1513 * @static
1514 * @param {HTMLElement} el Element to find scrollable parent for
1515 * @return {HTMLElement} Scrollable parent
1516 */
1517 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1518 var scrollTop, body;
1519
1520 if ( OO.ui.scrollableElement === undefined ) {
1521 body = el.ownerDocument.body;
1522 scrollTop = body.scrollTop;
1523 body.scrollTop = 1;
1524
1525 if ( body.scrollTop === 1 ) {
1526 body.scrollTop = scrollTop;
1527 OO.ui.scrollableElement = 'body';
1528 } else {
1529 OO.ui.scrollableElement = 'documentElement';
1530 }
1531 }
1532
1533 return el.ownerDocument[ OO.ui.scrollableElement ];
1534 };
1535
1536 /**
1537 * Get closest scrollable container.
1538 *
1539 * Traverses up until either a scrollable element or the root is reached, in which case the window
1540 * will be returned.
1541 *
1542 * @static
1543 * @param {HTMLElement} el Element to find scrollable container for
1544 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1545 * @return {HTMLElement} Closest scrollable container
1546 */
1547 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1548 var i, val,
1549 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1550 props = [ 'overflow-x', 'overflow-y' ],
1551 $parent = $( el ).parent();
1552
1553 if ( dimension === 'x' || dimension === 'y' ) {
1554 props = [ 'overflow-' + dimension ];
1555 }
1556
1557 while ( $parent.length ) {
1558 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1559 return $parent[ 0 ];
1560 }
1561 i = props.length;
1562 while ( i-- ) {
1563 val = $parent.css( props[ i ] );
1564 if ( val === 'auto' || val === 'scroll' ) {
1565 return $parent[ 0 ];
1566 }
1567 }
1568 $parent = $parent.parent();
1569 }
1570 return this.getDocument( el ).body;
1571 };
1572
1573 /**
1574 * Scroll element into view.
1575 *
1576 * @static
1577 * @param {HTMLElement} el Element to scroll into view
1578 * @param {Object} [config] Configuration options
1579 * @param {string} [config.duration] jQuery animation duration value
1580 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1581 * to scroll in both directions
1582 * @param {Function} [config.complete] Function to call when scrolling completes
1583 */
1584 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1585 var rel, anim, callback, sc, $sc, eld, scd, $win;
1586
1587 // Configuration initialization
1588 config = config || {};
1589
1590 anim = {};
1591 callback = typeof config.complete === 'function' && config.complete;
1592 sc = this.getClosestScrollableContainer( el, config.direction );
1593 $sc = $( sc );
1594 eld = this.getDimensions( el );
1595 scd = this.getDimensions( sc );
1596 $win = $( this.getWindow( el ) );
1597
1598 // Compute the distances between the edges of el and the edges of the scroll viewport
1599 if ( $sc.is( 'html, body' ) ) {
1600 // If the scrollable container is the root, this is easy
1601 rel = {
1602 top: eld.rect.top,
1603 bottom: $win.innerHeight() - eld.rect.bottom,
1604 left: eld.rect.left,
1605 right: $win.innerWidth() - eld.rect.right
1606 };
1607 } else {
1608 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1609 rel = {
1610 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1611 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1612 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1613 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1614 };
1615 }
1616
1617 if ( !config.direction || config.direction === 'y' ) {
1618 if ( rel.top < 0 ) {
1619 anim.scrollTop = scd.scroll.top + rel.top;
1620 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1621 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1622 }
1623 }
1624 if ( !config.direction || config.direction === 'x' ) {
1625 if ( rel.left < 0 ) {
1626 anim.scrollLeft = scd.scroll.left + rel.left;
1627 } else if ( rel.left > 0 && rel.right < 0 ) {
1628 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1629 }
1630 }
1631 if ( !$.isEmptyObject( anim ) ) {
1632 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1633 if ( callback ) {
1634 $sc.queue( function ( next ) {
1635 callback();
1636 next();
1637 } );
1638 }
1639 } else {
1640 if ( callback ) {
1641 callback();
1642 }
1643 }
1644 };
1645
1646 /**
1647 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1648 * and reserve space for them, because it probably doesn't.
1649 *
1650 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1651 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1652 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1653 * and then reattach (or show) them back.
1654 *
1655 * @static
1656 * @param {HTMLElement} el Element to reconsider the scrollbars on
1657 */
1658 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1659 var i, len, scrollLeft, scrollTop, nodes = [];
1660 // Save scroll position
1661 scrollLeft = el.scrollLeft;
1662 scrollTop = el.scrollTop;
1663 // Detach all children
1664 while ( el.firstChild ) {
1665 nodes.push( el.firstChild );
1666 el.removeChild( el.firstChild );
1667 }
1668 // Force reflow
1669 void el.offsetHeight;
1670 // Reattach all children
1671 for ( i = 0, len = nodes.length; i < len; i++ ) {
1672 el.appendChild( nodes[ i ] );
1673 }
1674 // Restore scroll position (no-op if scrollbars disappeared)
1675 el.scrollLeft = scrollLeft;
1676 el.scrollTop = scrollTop;
1677 };
1678
1679 /* Methods */
1680
1681 /**
1682 * Toggle visibility of an element.
1683 *
1684 * @param {boolean} [show] Make element visible, omit to toggle visibility
1685 * @fires visible
1686 * @chainable
1687 */
1688 OO.ui.Element.prototype.toggle = function ( show ) {
1689 show = show === undefined ? !this.visible : !!show;
1690
1691 if ( show !== this.isVisible() ) {
1692 this.visible = show;
1693 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1694 this.emit( 'toggle', show );
1695 }
1696
1697 return this;
1698 };
1699
1700 /**
1701 * Check if element is visible.
1702 *
1703 * @return {boolean} element is visible
1704 */
1705 OO.ui.Element.prototype.isVisible = function () {
1706 return this.visible;
1707 };
1708
1709 /**
1710 * Get element data.
1711 *
1712 * @return {Mixed} Element data
1713 */
1714 OO.ui.Element.prototype.getData = function () {
1715 return this.data;
1716 };
1717
1718 /**
1719 * Set element data.
1720 *
1721 * @param {Mixed} Element data
1722 * @chainable
1723 */
1724 OO.ui.Element.prototype.setData = function ( data ) {
1725 this.data = data;
1726 return this;
1727 };
1728
1729 /**
1730 * Check if element supports one or more methods.
1731 *
1732 * @param {string|string[]} methods Method or list of methods to check
1733 * @return {boolean} All methods are supported
1734 */
1735 OO.ui.Element.prototype.supports = function ( methods ) {
1736 var i, len,
1737 support = 0;
1738
1739 methods = Array.isArray( methods ) ? methods : [ methods ];
1740 for ( i = 0, len = methods.length; i < len; i++ ) {
1741 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1742 support++;
1743 }
1744 }
1745
1746 return methods.length === support;
1747 };
1748
1749 /**
1750 * Update the theme-provided classes.
1751 *
1752 * @localdoc This is called in element mixins and widget classes any time state changes.
1753 * Updating is debounced, minimizing overhead of changing multiple attributes and
1754 * guaranteeing that theme updates do not occur within an element's constructor
1755 */
1756 OO.ui.Element.prototype.updateThemeClasses = function () {
1757 this.debouncedUpdateThemeClassesHandler();
1758 };
1759
1760 /**
1761 * @private
1762 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1763 * make them synchronous.
1764 */
1765 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1766 OO.ui.theme.updateElementClasses( this );
1767 };
1768
1769 /**
1770 * Get the HTML tag name.
1771 *
1772 * Override this method to base the result on instance information.
1773 *
1774 * @return {string} HTML tag name
1775 */
1776 OO.ui.Element.prototype.getTagName = function () {
1777 return this.constructor.static.tagName;
1778 };
1779
1780 /**
1781 * Check if the element is attached to the DOM
1782 * @return {boolean} The element is attached to the DOM
1783 */
1784 OO.ui.Element.prototype.isElementAttached = function () {
1785 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1786 };
1787
1788 /**
1789 * Get the DOM document.
1790 *
1791 * @return {HTMLDocument} Document object
1792 */
1793 OO.ui.Element.prototype.getElementDocument = function () {
1794 // Don't cache this in other ways either because subclasses could can change this.$element
1795 return OO.ui.Element.static.getDocument( this.$element );
1796 };
1797
1798 /**
1799 * Get the DOM window.
1800 *
1801 * @return {Window} Window object
1802 */
1803 OO.ui.Element.prototype.getElementWindow = function () {
1804 return OO.ui.Element.static.getWindow( this.$element );
1805 };
1806
1807 /**
1808 * Get closest scrollable container.
1809 */
1810 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1811 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1812 };
1813
1814 /**
1815 * Get group element is in.
1816 *
1817 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1818 */
1819 OO.ui.Element.prototype.getElementGroup = function () {
1820 return this.elementGroup;
1821 };
1822
1823 /**
1824 * Set group element is in.
1825 *
1826 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1827 * @chainable
1828 */
1829 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1830 this.elementGroup = group;
1831 return this;
1832 };
1833
1834 /**
1835 * Scroll element into view.
1836 *
1837 * @param {Object} [config] Configuration options
1838 */
1839 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1840 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1841 };
1842
1843 /**
1844 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1845 * (and its children) that represent an Element of the same type and configuration as the current
1846 * one, generated by the PHP implementation.
1847 *
1848 * This method is called just before `node` is detached from the DOM. The return value of this
1849 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1850 * DOM to replace `node`.
1851 *
1852 * @protected
1853 * @param {HTMLElement} node
1854 * @return {Object}
1855 */
1856 OO.ui.Element.prototype.gatherPreInfuseState = function () {
1857 return {};
1858 };
1859
1860 /**
1861 * Restore the pre-infusion dynamic state for this widget.
1862 *
1863 * This method is called after #$element has been inserted into DOM. The parameter is the return
1864 * value of #gatherPreInfuseState.
1865 *
1866 * @protected
1867 * @param {Object} state
1868 */
1869 OO.ui.Element.prototype.restorePreInfuseState = function () {
1870 };
1871
1872 /**
1873 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1874 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1875 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1876 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1877 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1878 *
1879 * @abstract
1880 * @class
1881 * @extends OO.ui.Element
1882 * @mixins OO.EventEmitter
1883 *
1884 * @constructor
1885 * @param {Object} [config] Configuration options
1886 */
1887 OO.ui.Layout = function OoUiLayout( config ) {
1888 // Configuration initialization
1889 config = config || {};
1890
1891 // Parent constructor
1892 OO.ui.Layout.parent.call( this, config );
1893
1894 // Mixin constructors
1895 OO.EventEmitter.call( this );
1896
1897 // Initialization
1898 this.$element.addClass( 'oo-ui-layout' );
1899 };
1900
1901 /* Setup */
1902
1903 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1904 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1905
1906 /**
1907 * Widgets are compositions of one or more OOjs UI elements that users can both view
1908 * and interact with. All widgets can be configured and modified via a standard API,
1909 * and their state can change dynamically according to a model.
1910 *
1911 * @abstract
1912 * @class
1913 * @extends OO.ui.Element
1914 * @mixins OO.EventEmitter
1915 *
1916 * @constructor
1917 * @param {Object} [config] Configuration options
1918 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1919 * appearance reflects this state.
1920 */
1921 OO.ui.Widget = function OoUiWidget( config ) {
1922 // Initialize config
1923 config = $.extend( { disabled: false }, config );
1924
1925 // Parent constructor
1926 OO.ui.Widget.parent.call( this, config );
1927
1928 // Mixin constructors
1929 OO.EventEmitter.call( this );
1930
1931 // Properties
1932 this.disabled = null;
1933 this.wasDisabled = null;
1934
1935 // Initialization
1936 this.$element.addClass( 'oo-ui-widget' );
1937 this.setDisabled( !!config.disabled );
1938 };
1939
1940 /* Setup */
1941
1942 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1943 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1944
1945 /* Static Properties */
1946
1947 /**
1948 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1949 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1950 * handling.
1951 *
1952 * @static
1953 * @inheritable
1954 * @property {boolean}
1955 */
1956 OO.ui.Widget.static.supportsSimpleLabel = false;
1957
1958 /* Events */
1959
1960 /**
1961 * @event disable
1962 *
1963 * A 'disable' event is emitted when a widget is disabled.
1964 *
1965 * @param {boolean} disabled Widget is disabled
1966 */
1967
1968 /**
1969 * @event toggle
1970 *
1971 * A 'toggle' event is emitted when the visibility of the widget changes.
1972 *
1973 * @param {boolean} visible Widget is visible
1974 */
1975
1976 /* Methods */
1977
1978 /**
1979 * Check if the widget is disabled.
1980 *
1981 * @return {boolean} Widget is disabled
1982 */
1983 OO.ui.Widget.prototype.isDisabled = function () {
1984 return this.disabled;
1985 };
1986
1987 /**
1988 * Set the 'disabled' state of the widget.
1989 *
1990 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1991 *
1992 * @param {boolean} disabled Disable widget
1993 * @chainable
1994 */
1995 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1996 var isDisabled;
1997
1998 this.disabled = !!disabled;
1999 isDisabled = this.isDisabled();
2000 if ( isDisabled !== this.wasDisabled ) {
2001 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
2002 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
2003 this.$element.attr( 'aria-disabled', isDisabled.toString() );
2004 this.emit( 'disable', isDisabled );
2005 this.updateThemeClasses();
2006 }
2007 this.wasDisabled = isDisabled;
2008
2009 return this;
2010 };
2011
2012 /**
2013 * Update the disabled state, in case of changes in parent widget.
2014 *
2015 * @chainable
2016 */
2017 OO.ui.Widget.prototype.updateDisabled = function () {
2018 this.setDisabled( this.disabled );
2019 return this;
2020 };
2021
2022 /**
2023 * A window is a container for elements that are in a child frame. They are used with
2024 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2025 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2026 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2027 * the window manager will choose a sensible fallback.
2028 *
2029 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2030 * different processes are executed:
2031 *
2032 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2033 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2034 * the window.
2035 *
2036 * - {@link #getSetupProcess} method is called and its result executed
2037 * - {@link #getReadyProcess} method is called and its result executed
2038 *
2039 * **opened**: The window is now open
2040 *
2041 * **closing**: The closing stage begins when the window manager's
2042 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2043 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2044 *
2045 * - {@link #getHoldProcess} method is called and its result executed
2046 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2047 *
2048 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2049 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2050 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2051 * processing can complete. Always assume window processes are executed asynchronously.
2052 *
2053 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2054 *
2055 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2056 *
2057 * @abstract
2058 * @class
2059 * @extends OO.ui.Element
2060 * @mixins OO.EventEmitter
2061 *
2062 * @constructor
2063 * @param {Object} [config] Configuration options
2064 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2065 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2066 */
2067 OO.ui.Window = function OoUiWindow( config ) {
2068 // Configuration initialization
2069 config = config || {};
2070
2071 // Parent constructor
2072 OO.ui.Window.parent.call( this, config );
2073
2074 // Mixin constructors
2075 OO.EventEmitter.call( this );
2076
2077 // Properties
2078 this.manager = null;
2079 this.size = config.size || this.constructor.static.size;
2080 this.$frame = $( '<div>' );
2081 this.$overlay = $( '<div>' );
2082 this.$content = $( '<div>' );
2083
2084 // Initialization
2085 this.$overlay.addClass( 'oo-ui-window-overlay' );
2086 this.$content
2087 .addClass( 'oo-ui-window-content' )
2088 .attr( 'tabindex', 0 );
2089 this.$frame
2090 .addClass( 'oo-ui-window-frame' )
2091 .append( this.$content );
2092
2093 this.$element
2094 .addClass( 'oo-ui-window' )
2095 .append( this.$frame, this.$overlay );
2096
2097 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2098 // that reference properties not initialized at that time of parent class construction
2099 // TODO: Find a better way to handle post-constructor setup
2100 this.visible = false;
2101 this.$element.addClass( 'oo-ui-element-hidden' );
2102 };
2103
2104 /* Setup */
2105
2106 OO.inheritClass( OO.ui.Window, OO.ui.Element );
2107 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
2108
2109 /* Static Properties */
2110
2111 /**
2112 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2113 *
2114 * The static size is used if no #size is configured during construction.
2115 *
2116 * @static
2117 * @inheritable
2118 * @property {string}
2119 */
2120 OO.ui.Window.static.size = 'medium';
2121
2122 /* Methods */
2123
2124 /**
2125 * Handle mouse down events.
2126 *
2127 * @private
2128 * @param {jQuery.Event} e Mouse down event
2129 */
2130 OO.ui.Window.prototype.onMouseDown = function ( e ) {
2131 // Prevent clicking on the click-block from stealing focus
2132 if ( e.target === this.$element[ 0 ] ) {
2133 return false;
2134 }
2135 };
2136
2137 /**
2138 * Check if the window has been initialized.
2139 *
2140 * Initialization occurs when a window is added to a manager.
2141 *
2142 * @return {boolean} Window has been initialized
2143 */
2144 OO.ui.Window.prototype.isInitialized = function () {
2145 return !!this.manager;
2146 };
2147
2148 /**
2149 * Check if the window is visible.
2150 *
2151 * @return {boolean} Window is visible
2152 */
2153 OO.ui.Window.prototype.isVisible = function () {
2154 return this.visible;
2155 };
2156
2157 /**
2158 * Check if the window is opening.
2159 *
2160 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2161 * method.
2162 *
2163 * @return {boolean} Window is opening
2164 */
2165 OO.ui.Window.prototype.isOpening = function () {
2166 return this.manager.isOpening( this );
2167 };
2168
2169 /**
2170 * Check if the window is closing.
2171 *
2172 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2173 *
2174 * @return {boolean} Window is closing
2175 */
2176 OO.ui.Window.prototype.isClosing = function () {
2177 return this.manager.isClosing( this );
2178 };
2179
2180 /**
2181 * Check if the window is opened.
2182 *
2183 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2184 *
2185 * @return {boolean} Window is opened
2186 */
2187 OO.ui.Window.prototype.isOpened = function () {
2188 return this.manager.isOpened( this );
2189 };
2190
2191 /**
2192 * Get the window manager.
2193 *
2194 * All windows must be attached to a window manager, which is used to open
2195 * and close the window and control its presentation.
2196 *
2197 * @return {OO.ui.WindowManager} Manager of window
2198 */
2199 OO.ui.Window.prototype.getManager = function () {
2200 return this.manager;
2201 };
2202
2203 /**
2204 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2205 *
2206 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2207 */
2208 OO.ui.Window.prototype.getSize = function () {
2209 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
2210 sizes = this.manager.constructor.static.sizes,
2211 size = this.size;
2212
2213 if ( !sizes[ size ] ) {
2214 size = this.manager.constructor.static.defaultSize;
2215 }
2216 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
2217 size = 'full';
2218 }
2219
2220 return size;
2221 };
2222
2223 /**
2224 * Get the size properties associated with the current window size
2225 *
2226 * @return {Object} Size properties
2227 */
2228 OO.ui.Window.prototype.getSizeProperties = function () {
2229 return this.manager.constructor.static.sizes[ this.getSize() ];
2230 };
2231
2232 /**
2233 * Disable transitions on window's frame for the duration of the callback function, then enable them
2234 * back.
2235 *
2236 * @private
2237 * @param {Function} callback Function to call while transitions are disabled
2238 */
2239 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2240 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2241 // Disable transitions first, otherwise we'll get values from when the window was animating.
2242 var oldTransition,
2243 styleObj = this.$frame[ 0 ].style;
2244 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
2245 styleObj.MozTransition || styleObj.WebkitTransition;
2246 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2247 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
2248 callback();
2249 // Force reflow to make sure the style changes done inside callback really are not transitioned
2250 this.$frame.height();
2251 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
2252 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
2253 };
2254
2255 /**
2256 * Get the height of the full window contents (i.e., the window head, body and foot together).
2257 *
2258 * What consistitutes the head, body, and foot varies depending on the window type.
2259 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2260 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2261 * and special actions in the head, and dialog content in the body.
2262 *
2263 * To get just the height of the dialog body, use the #getBodyHeight method.
2264 *
2265 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2266 */
2267 OO.ui.Window.prototype.getContentHeight = function () {
2268 var bodyHeight,
2269 win = this,
2270 bodyStyleObj = this.$body[ 0 ].style,
2271 frameStyleObj = this.$frame[ 0 ].style;
2272
2273 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2274 // Disable transitions first, otherwise we'll get values from when the window was animating.
2275 this.withoutSizeTransitions( function () {
2276 var oldHeight = frameStyleObj.height,
2277 oldPosition = bodyStyleObj.position;
2278 frameStyleObj.height = '1px';
2279 // Force body to resize to new width
2280 bodyStyleObj.position = 'relative';
2281 bodyHeight = win.getBodyHeight();
2282 frameStyleObj.height = oldHeight;
2283 bodyStyleObj.position = oldPosition;
2284 } );
2285
2286 return (
2287 // Add buffer for border
2288 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2289 // Use combined heights of children
2290 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2291 );
2292 };
2293
2294 /**
2295 * Get the height of the window body.
2296 *
2297 * To get the height of the full window contents (the window body, head, and foot together),
2298 * use #getContentHeight.
2299 *
2300 * When this function is called, the window will temporarily have been resized
2301 * to height=1px, so .scrollHeight measurements can be taken accurately.
2302 *
2303 * @return {number} Height of the window body in pixels
2304 */
2305 OO.ui.Window.prototype.getBodyHeight = function () {
2306 return this.$body[ 0 ].scrollHeight;
2307 };
2308
2309 /**
2310 * Get the directionality of the frame (right-to-left or left-to-right).
2311 *
2312 * @return {string} Directionality: `'ltr'` or `'rtl'`
2313 */
2314 OO.ui.Window.prototype.getDir = function () {
2315 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2316 };
2317
2318 /**
2319 * Get the 'setup' process.
2320 *
2321 * The setup process is used to set up a window for use in a particular context,
2322 * based on the `data` argument. This method is called during the opening phase of the window’s
2323 * lifecycle.
2324 *
2325 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2326 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2327 * of OO.ui.Process.
2328 *
2329 * To add window content that persists between openings, you may wish to use the #initialize method
2330 * instead.
2331 *
2332 * @abstract
2333 * @param {Object} [data] Window opening data
2334 * @return {OO.ui.Process} Setup process
2335 */
2336 OO.ui.Window.prototype.getSetupProcess = function () {
2337 return new OO.ui.Process();
2338 };
2339
2340 /**
2341 * Get the ‘ready’ process.
2342 *
2343 * The ready process is used to ready a window for use in a particular
2344 * context, based on the `data` argument. This method is called during the opening phase of
2345 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2346 *
2347 * Override this method to add additional steps to the ‘ready’ process the parent method
2348 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2349 * methods of OO.ui.Process.
2350 *
2351 * @abstract
2352 * @param {Object} [data] Window opening data
2353 * @return {OO.ui.Process} Ready process
2354 */
2355 OO.ui.Window.prototype.getReadyProcess = function () {
2356 return new OO.ui.Process();
2357 };
2358
2359 /**
2360 * Get the 'hold' process.
2361 *
2362 * The hold proccess is used to keep a window from being used in a particular context,
2363 * based on the `data` argument. This method is called during the closing phase of the window’s
2364 * lifecycle.
2365 *
2366 * Override this method to add additional steps to the 'hold' process the parent method provides
2367 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2368 * of OO.ui.Process.
2369 *
2370 * @abstract
2371 * @param {Object} [data] Window closing data
2372 * @return {OO.ui.Process} Hold process
2373 */
2374 OO.ui.Window.prototype.getHoldProcess = function () {
2375 return new OO.ui.Process();
2376 };
2377
2378 /**
2379 * Get the ‘teardown’ process.
2380 *
2381 * The teardown process is used to teardown a window after use. During teardown,
2382 * user interactions within the window are conveyed and the window is closed, based on the `data`
2383 * argument. This method is called during the closing phase of the window’s lifecycle.
2384 *
2385 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2386 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2387 * of OO.ui.Process.
2388 *
2389 * @abstract
2390 * @param {Object} [data] Window closing data
2391 * @return {OO.ui.Process} Teardown process
2392 */
2393 OO.ui.Window.prototype.getTeardownProcess = function () {
2394 return new OO.ui.Process();
2395 };
2396
2397 /**
2398 * Set the window manager.
2399 *
2400 * This will cause the window to initialize. Calling it more than once will cause an error.
2401 *
2402 * @param {OO.ui.WindowManager} manager Manager for this window
2403 * @throws {Error} An error is thrown if the method is called more than once
2404 * @chainable
2405 */
2406 OO.ui.Window.prototype.setManager = function ( manager ) {
2407 if ( this.manager ) {
2408 throw new Error( 'Cannot set window manager, window already has a manager' );
2409 }
2410
2411 this.manager = manager;
2412 this.initialize();
2413
2414 return this;
2415 };
2416
2417 /**
2418 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2419 *
2420 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2421 * `full`
2422 * @chainable
2423 */
2424 OO.ui.Window.prototype.setSize = function ( size ) {
2425 this.size = size;
2426 this.updateSize();
2427 return this;
2428 };
2429
2430 /**
2431 * Update the window size.
2432 *
2433 * @throws {Error} An error is thrown if the window is not attached to a window manager
2434 * @chainable
2435 */
2436 OO.ui.Window.prototype.updateSize = function () {
2437 if ( !this.manager ) {
2438 throw new Error( 'Cannot update window size, must be attached to a manager' );
2439 }
2440
2441 this.manager.updateWindowSize( this );
2442
2443 return this;
2444 };
2445
2446 /**
2447 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2448 * when the window is opening. In general, setDimensions should not be called directly.
2449 *
2450 * To set the size of the window, use the #setSize method.
2451 *
2452 * @param {Object} dim CSS dimension properties
2453 * @param {string|number} [dim.width] Width
2454 * @param {string|number} [dim.minWidth] Minimum width
2455 * @param {string|number} [dim.maxWidth] Maximum width
2456 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2457 * @param {string|number} [dim.minWidth] Minimum height
2458 * @param {string|number} [dim.maxWidth] Maximum height
2459 * @chainable
2460 */
2461 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2462 var height,
2463 win = this,
2464 styleObj = this.$frame[ 0 ].style;
2465
2466 // Calculate the height we need to set using the correct width
2467 if ( dim.height === undefined ) {
2468 this.withoutSizeTransitions( function () {
2469 var oldWidth = styleObj.width;
2470 win.$frame.css( 'width', dim.width || '' );
2471 height = win.getContentHeight();
2472 styleObj.width = oldWidth;
2473 } );
2474 } else {
2475 height = dim.height;
2476 }
2477
2478 this.$frame.css( {
2479 width: dim.width || '',
2480 minWidth: dim.minWidth || '',
2481 maxWidth: dim.maxWidth || '',
2482 height: height || '',
2483 minHeight: dim.minHeight || '',
2484 maxHeight: dim.maxHeight || ''
2485 } );
2486
2487 return this;
2488 };
2489
2490 /**
2491 * Initialize window contents.
2492 *
2493 * Before the window is opened for the first time, #initialize is called so that content that
2494 * persists between openings can be added to the window.
2495 *
2496 * To set up a window with new content each time the window opens, use #getSetupProcess.
2497 *
2498 * @throws {Error} An error is thrown if the window is not attached to a window manager
2499 * @chainable
2500 */
2501 OO.ui.Window.prototype.initialize = function () {
2502 if ( !this.manager ) {
2503 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2504 }
2505
2506 // Properties
2507 this.$head = $( '<div>' );
2508 this.$body = $( '<div>' );
2509 this.$foot = $( '<div>' );
2510 this.$document = $( this.getElementDocument() );
2511
2512 // Events
2513 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2514
2515 // Initialization
2516 this.$head.addClass( 'oo-ui-window-head' );
2517 this.$body.addClass( 'oo-ui-window-body' );
2518 this.$foot.addClass( 'oo-ui-window-foot' );
2519 this.$content.append( this.$head, this.$body, this.$foot );
2520
2521 return this;
2522 };
2523
2524 /**
2525 * Open the window.
2526 *
2527 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2528 * method, which returns a promise resolved when the window is done opening.
2529 *
2530 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2531 *
2532 * @param {Object} [data] Window opening data
2533 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2534 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2535 * value is a new promise, which is resolved when the window begins closing.
2536 * @throws {Error} An error is thrown if the window is not attached to a window manager
2537 */
2538 OO.ui.Window.prototype.open = function ( data ) {
2539 if ( !this.manager ) {
2540 throw new Error( 'Cannot open window, must be attached to a manager' );
2541 }
2542
2543 return this.manager.openWindow( this, data );
2544 };
2545
2546 /**
2547 * Close the window.
2548 *
2549 * This method is a wrapper around a call to the window
2550 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2551 * which returns a closing promise resolved when the window is done closing.
2552 *
2553 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2554 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2555 * the window closes.
2556 *
2557 * @param {Object} [data] Window closing data
2558 * @return {jQuery.Promise} Promise resolved when window is closed
2559 * @throws {Error} An error is thrown if the window is not attached to a window manager
2560 */
2561 OO.ui.Window.prototype.close = function ( data ) {
2562 if ( !this.manager ) {
2563 throw new Error( 'Cannot close window, must be attached to a manager' );
2564 }
2565
2566 return this.manager.closeWindow( this, data );
2567 };
2568
2569 /**
2570 * Setup window.
2571 *
2572 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2573 * by other systems.
2574 *
2575 * @param {Object} [data] Window opening data
2576 * @return {jQuery.Promise} Promise resolved when window is setup
2577 */
2578 OO.ui.Window.prototype.setup = function ( data ) {
2579 var win = this,
2580 deferred = $.Deferred();
2581
2582 this.toggle( true );
2583
2584 this.getSetupProcess( data ).execute().done( function () {
2585 // Force redraw by asking the browser to measure the elements' widths
2586 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2587 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2588 deferred.resolve();
2589 } );
2590
2591 return deferred.promise();
2592 };
2593
2594 /**
2595 * Ready window.
2596 *
2597 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2598 * by other systems.
2599 *
2600 * @param {Object} [data] Window opening data
2601 * @return {jQuery.Promise} Promise resolved when window is ready
2602 */
2603 OO.ui.Window.prototype.ready = function ( data ) {
2604 var win = this,
2605 deferred = $.Deferred();
2606
2607 this.$content.focus();
2608 this.getReadyProcess( data ).execute().done( function () {
2609 // Force redraw by asking the browser to measure the elements' widths
2610 win.$element.addClass( 'oo-ui-window-ready' ).width();
2611 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2612 deferred.resolve();
2613 } );
2614
2615 return deferred.promise();
2616 };
2617
2618 /**
2619 * Hold window.
2620 *
2621 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2622 * by other systems.
2623 *
2624 * @param {Object} [data] Window closing data
2625 * @return {jQuery.Promise} Promise resolved when window is held
2626 */
2627 OO.ui.Window.prototype.hold = function ( data ) {
2628 var win = this,
2629 deferred = $.Deferred();
2630
2631 this.getHoldProcess( data ).execute().done( function () {
2632 // Get the focused element within the window's content
2633 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2634
2635 // Blur the focused element
2636 if ( $focus.length ) {
2637 $focus[ 0 ].blur();
2638 }
2639
2640 // Force redraw by asking the browser to measure the elements' widths
2641 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2642 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2643 deferred.resolve();
2644 } );
2645
2646 return deferred.promise();
2647 };
2648
2649 /**
2650 * Teardown window.
2651 *
2652 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2653 * by other systems.
2654 *
2655 * @param {Object} [data] Window closing data
2656 * @return {jQuery.Promise} Promise resolved when window is torn down
2657 */
2658 OO.ui.Window.prototype.teardown = function ( data ) {
2659 var win = this;
2660
2661 return this.getTeardownProcess( data ).execute()
2662 .done( function () {
2663 // Force redraw by asking the browser to measure the elements' widths
2664 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2665 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2666 win.toggle( false );
2667 } );
2668 };
2669
2670 /**
2671 * The Dialog class serves as the base class for the other types of dialogs.
2672 * Unless extended to include controls, the rendered dialog box is a simple window
2673 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2674 * which opens, closes, and controls the presentation of the window. See the
2675 * [OOjs UI documentation on MediaWiki] [1] for more information.
2676 *
2677 * @example
2678 * // A simple dialog window.
2679 * function MyDialog( config ) {
2680 * MyDialog.parent.call( this, config );
2681 * }
2682 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2683 * MyDialog.prototype.initialize = function () {
2684 * MyDialog.parent.prototype.initialize.call( this );
2685 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2686 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2687 * this.$body.append( this.content.$element );
2688 * };
2689 * MyDialog.prototype.getBodyHeight = function () {
2690 * return this.content.$element.outerHeight( true );
2691 * };
2692 * var myDialog = new MyDialog( {
2693 * size: 'medium'
2694 * } );
2695 * // Create and append a window manager, which opens and closes the window.
2696 * var windowManager = new OO.ui.WindowManager();
2697 * $( 'body' ).append( windowManager.$element );
2698 * windowManager.addWindows( [ myDialog ] );
2699 * // Open the window!
2700 * windowManager.openWindow( myDialog );
2701 *
2702 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2703 *
2704 * @abstract
2705 * @class
2706 * @extends OO.ui.Window
2707 * @mixins OO.ui.mixin.PendingElement
2708 *
2709 * @constructor
2710 * @param {Object} [config] Configuration options
2711 */
2712 OO.ui.Dialog = function OoUiDialog( config ) {
2713 // Parent constructor
2714 OO.ui.Dialog.parent.call( this, config );
2715
2716 // Mixin constructors
2717 OO.ui.mixin.PendingElement.call( this );
2718
2719 // Properties
2720 this.actions = new OO.ui.ActionSet();
2721 this.attachedActions = [];
2722 this.currentAction = null;
2723 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2724
2725 // Events
2726 this.actions.connect( this, {
2727 click: 'onActionClick',
2728 resize: 'onActionResize',
2729 change: 'onActionsChange'
2730 } );
2731
2732 // Initialization
2733 this.$element
2734 .addClass( 'oo-ui-dialog' )
2735 .attr( 'role', 'dialog' );
2736 };
2737
2738 /* Setup */
2739
2740 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2741 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2742
2743 /* Static Properties */
2744
2745 /**
2746 * Symbolic name of dialog.
2747 *
2748 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2749 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2750 *
2751 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2752 *
2753 * @abstract
2754 * @static
2755 * @inheritable
2756 * @property {string}
2757 */
2758 OO.ui.Dialog.static.name = '';
2759
2760 /**
2761 * The dialog title.
2762 *
2763 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2764 * that will produce a Label node or string. The title can also be specified with data passed to the
2765 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2766 *
2767 * @abstract
2768 * @static
2769 * @inheritable
2770 * @property {jQuery|string|Function}
2771 */
2772 OO.ui.Dialog.static.title = '';
2773
2774 /**
2775 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2776 *
2777 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2778 * value will be overriden.
2779 *
2780 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2781 *
2782 * @static
2783 * @inheritable
2784 * @property {Object[]}
2785 */
2786 OO.ui.Dialog.static.actions = [];
2787
2788 /**
2789 * Close the dialog when the 'Esc' key is pressed.
2790 *
2791 * @static
2792 * @abstract
2793 * @inheritable
2794 * @property {boolean}
2795 */
2796 OO.ui.Dialog.static.escapable = true;
2797
2798 /* Methods */
2799
2800 /**
2801 * Handle frame document key down events.
2802 *
2803 * @private
2804 * @param {jQuery.Event} e Key down event
2805 */
2806 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2807 if ( e.which === OO.ui.Keys.ESCAPE ) {
2808 this.close();
2809 e.preventDefault();
2810 e.stopPropagation();
2811 }
2812 };
2813
2814 /**
2815 * Handle action resized events.
2816 *
2817 * @private
2818 * @param {OO.ui.ActionWidget} action Action that was resized
2819 */
2820 OO.ui.Dialog.prototype.onActionResize = function () {
2821 // Override in subclass
2822 };
2823
2824 /**
2825 * Handle action click events.
2826 *
2827 * @private
2828 * @param {OO.ui.ActionWidget} action Action that was clicked
2829 */
2830 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2831 if ( !this.isPending() ) {
2832 this.executeAction( action.getAction() );
2833 }
2834 };
2835
2836 /**
2837 * Handle actions change event.
2838 *
2839 * @private
2840 */
2841 OO.ui.Dialog.prototype.onActionsChange = function () {
2842 this.detachActions();
2843 if ( !this.isClosing() ) {
2844 this.attachActions();
2845 }
2846 };
2847
2848 /**
2849 * Get the set of actions used by the dialog.
2850 *
2851 * @return {OO.ui.ActionSet}
2852 */
2853 OO.ui.Dialog.prototype.getActions = function () {
2854 return this.actions;
2855 };
2856
2857 /**
2858 * Get a process for taking action.
2859 *
2860 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2861 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2862 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2863 *
2864 * @abstract
2865 * @param {string} [action] Symbolic name of action
2866 * @return {OO.ui.Process} Action process
2867 */
2868 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2869 return new OO.ui.Process()
2870 .next( function () {
2871 if ( !action ) {
2872 // An empty action always closes the dialog without data, which should always be
2873 // safe and make no changes
2874 this.close();
2875 }
2876 }, this );
2877 };
2878
2879 /**
2880 * @inheritdoc
2881 *
2882 * @param {Object} [data] Dialog opening data
2883 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2884 * the {@link #static-title static title}
2885 * @param {Object[]} [data.actions] List of configuration options for each
2886 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2887 */
2888 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2889 data = data || {};
2890
2891 // Parent method
2892 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2893 .next( function () {
2894 var config = this.constructor.static,
2895 actions = data.actions !== undefined ? data.actions : config.actions;
2896
2897 this.title.setLabel(
2898 data.title !== undefined ? data.title : this.constructor.static.title
2899 );
2900 this.actions.add( this.getActionWidgets( actions ) );
2901
2902 if ( this.constructor.static.escapable ) {
2903 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2904 }
2905 }, this );
2906 };
2907
2908 /**
2909 * @inheritdoc
2910 */
2911 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2912 // Parent method
2913 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2914 .first( function () {
2915 if ( this.constructor.static.escapable ) {
2916 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2917 }
2918
2919 this.actions.clear();
2920 this.currentAction = null;
2921 }, this );
2922 };
2923
2924 /**
2925 * @inheritdoc
2926 */
2927 OO.ui.Dialog.prototype.initialize = function () {
2928 var titleId;
2929
2930 // Parent method
2931 OO.ui.Dialog.parent.prototype.initialize.call( this );
2932
2933 titleId = OO.ui.generateElementId();
2934
2935 // Properties
2936 this.title = new OO.ui.LabelWidget( {
2937 id: titleId
2938 } );
2939
2940 // Initialization
2941 this.$content.addClass( 'oo-ui-dialog-content' );
2942 this.$element.attr( 'aria-labelledby', titleId );
2943 this.setPendingElement( this.$head );
2944 };
2945
2946 /**
2947 * Get action widgets from a list of configs
2948 *
2949 * @param {Object[]} actions Action widget configs
2950 * @return {OO.ui.ActionWidget[]} Action widgets
2951 */
2952 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2953 var i, len, widgets = [];
2954 for ( i = 0, len = actions.length; i < len; i++ ) {
2955 widgets.push(
2956 new OO.ui.ActionWidget( actions[ i ] )
2957 );
2958 }
2959 return widgets;
2960 };
2961
2962 /**
2963 * Attach action actions.
2964 *
2965 * @protected
2966 */
2967 OO.ui.Dialog.prototype.attachActions = function () {
2968 // Remember the list of potentially attached actions
2969 this.attachedActions = this.actions.get();
2970 };
2971
2972 /**
2973 * Detach action actions.
2974 *
2975 * @protected
2976 * @chainable
2977 */
2978 OO.ui.Dialog.prototype.detachActions = function () {
2979 var i, len;
2980
2981 // Detach all actions that may have been previously attached
2982 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2983 this.attachedActions[ i ].$element.detach();
2984 }
2985 this.attachedActions = [];
2986 };
2987
2988 /**
2989 * Execute an action.
2990 *
2991 * @param {string} action Symbolic name of action to execute
2992 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2993 */
2994 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2995 this.pushPending();
2996 this.currentAction = action;
2997 return this.getActionProcess( action ).execute()
2998 .always( this.popPending.bind( this ) );
2999 };
3000
3001 /**
3002 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3003 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3004 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3005 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3006 * pertinent data and reused.
3007 *
3008 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3009 * `opened`, and `closing`, which represent the primary stages of the cycle:
3010 *
3011 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3012 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3013 *
3014 * - an `opening` event is emitted with an `opening` promise
3015 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3016 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3017 * window and its result executed
3018 * - a `setup` progress notification is emitted from the `opening` promise
3019 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3020 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3021 * window and its result executed
3022 * - a `ready` progress notification is emitted from the `opening` promise
3023 * - the `opening` promise is resolved with an `opened` promise
3024 *
3025 * **Opened**: the window is now open.
3026 *
3027 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3028 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3029 * to close the window.
3030 *
3031 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3032 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3033 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3034 * window and its result executed
3035 * - a `hold` progress notification is emitted from the `closing` promise
3036 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3037 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3038 * window and its result executed
3039 * - a `teardown` progress notification is emitted from the `closing` promise
3040 * - the `closing` promise is resolved. The window is now closed
3041 *
3042 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3043 *
3044 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3045 *
3046 * @class
3047 * @extends OO.ui.Element
3048 * @mixins OO.EventEmitter
3049 *
3050 * @constructor
3051 * @param {Object} [config] Configuration options
3052 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3053 * Note that window classes that are instantiated with a factory must have
3054 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3055 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3056 */
3057 OO.ui.WindowManager = function OoUiWindowManager( config ) {
3058 // Configuration initialization
3059 config = config || {};
3060
3061 // Parent constructor
3062 OO.ui.WindowManager.parent.call( this, config );
3063
3064 // Mixin constructors
3065 OO.EventEmitter.call( this );
3066
3067 // Properties
3068 this.factory = config.factory;
3069 this.modal = config.modal === undefined || !!config.modal;
3070 this.windows = {};
3071 this.opening = null;
3072 this.opened = null;
3073 this.closing = null;
3074 this.preparingToOpen = null;
3075 this.preparingToClose = null;
3076 this.currentWindow = null;
3077 this.globalEvents = false;
3078 this.$ariaHidden = null;
3079 this.onWindowResizeTimeout = null;
3080 this.onWindowResizeHandler = this.onWindowResize.bind( this );
3081 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
3082
3083 // Initialization
3084 this.$element
3085 .addClass( 'oo-ui-windowManager' )
3086 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
3087 };
3088
3089 /* Setup */
3090
3091 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
3092 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
3093
3094 /* Events */
3095
3096 /**
3097 * An 'opening' event is emitted when the window begins to be opened.
3098 *
3099 * @event opening
3100 * @param {OO.ui.Window} win Window that's being opened
3101 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3102 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3103 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3104 * @param {Object} data Window opening data
3105 */
3106
3107 /**
3108 * A 'closing' event is emitted when the window begins to be closed.
3109 *
3110 * @event closing
3111 * @param {OO.ui.Window} win Window that's being closed
3112 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3113 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3114 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3115 * is the closing data.
3116 * @param {Object} data Window closing data
3117 */
3118
3119 /**
3120 * A 'resize' event is emitted when a window is resized.
3121 *
3122 * @event resize
3123 * @param {OO.ui.Window} win Window that was resized
3124 */
3125
3126 /* Static Properties */
3127
3128 /**
3129 * Map of the symbolic name of each window size and its CSS properties.
3130 *
3131 * @static
3132 * @inheritable
3133 * @property {Object}
3134 */
3135 OO.ui.WindowManager.static.sizes = {
3136 small: {
3137 width: 300
3138 },
3139 medium: {
3140 width: 500
3141 },
3142 large: {
3143 width: 700
3144 },
3145 larger: {
3146 width: 900
3147 },
3148 full: {
3149 // These can be non-numeric because they are never used in calculations
3150 width: '100%',
3151 height: '100%'
3152 }
3153 };
3154
3155 /**
3156 * Symbolic name of the default window size.
3157 *
3158 * The default size is used if the window's requested size is not recognized.
3159 *
3160 * @static
3161 * @inheritable
3162 * @property {string}
3163 */
3164 OO.ui.WindowManager.static.defaultSize = 'medium';
3165
3166 /* Methods */
3167
3168 /**
3169 * Handle window resize events.
3170 *
3171 * @private
3172 * @param {jQuery.Event} e Window resize event
3173 */
3174 OO.ui.WindowManager.prototype.onWindowResize = function () {
3175 clearTimeout( this.onWindowResizeTimeout );
3176 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
3177 };
3178
3179 /**
3180 * Handle window resize events.
3181 *
3182 * @private
3183 * @param {jQuery.Event} e Window resize event
3184 */
3185 OO.ui.WindowManager.prototype.afterWindowResize = function () {
3186 if ( this.currentWindow ) {
3187 this.updateWindowSize( this.currentWindow );
3188 }
3189 };
3190
3191 /**
3192 * Check if window is opening.
3193 *
3194 * @return {boolean} Window is opening
3195 */
3196 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
3197 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
3198 };
3199
3200 /**
3201 * Check if window is closing.
3202 *
3203 * @return {boolean} Window is closing
3204 */
3205 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
3206 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
3207 };
3208
3209 /**
3210 * Check if window is opened.
3211 *
3212 * @return {boolean} Window is opened
3213 */
3214 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
3215 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
3216 };
3217
3218 /**
3219 * Check if a window is being managed.
3220 *
3221 * @param {OO.ui.Window} win Window to check
3222 * @return {boolean} Window is being managed
3223 */
3224 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
3225 var name;
3226
3227 for ( name in this.windows ) {
3228 if ( this.windows[ name ] === win ) {
3229 return true;
3230 }
3231 }
3232
3233 return false;
3234 };
3235
3236 /**
3237 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3238 *
3239 * @param {OO.ui.Window} win Window being opened
3240 * @param {Object} [data] Window opening data
3241 * @return {number} Milliseconds to wait
3242 */
3243 OO.ui.WindowManager.prototype.getSetupDelay = function () {
3244 return 0;
3245 };
3246
3247 /**
3248 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3249 *
3250 * @param {OO.ui.Window} win Window being opened
3251 * @param {Object} [data] Window opening data
3252 * @return {number} Milliseconds to wait
3253 */
3254 OO.ui.WindowManager.prototype.getReadyDelay = function () {
3255 return 0;
3256 };
3257
3258 /**
3259 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3260 *
3261 * @param {OO.ui.Window} win Window being closed
3262 * @param {Object} [data] Window closing data
3263 * @return {number} Milliseconds to wait
3264 */
3265 OO.ui.WindowManager.prototype.getHoldDelay = function () {
3266 return 0;
3267 };
3268
3269 /**
3270 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3271 * executing the ‘teardown’ process.
3272 *
3273 * @param {OO.ui.Window} win Window being closed
3274 * @param {Object} [data] Window closing data
3275 * @return {number} Milliseconds to wait
3276 */
3277 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3278 return this.modal ? 250 : 0;
3279 };
3280
3281 /**
3282 * Get a window by its symbolic name.
3283 *
3284 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3285 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3286 * for more information about using factories.
3287 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3288 *
3289 * @param {string} name Symbolic name of the window
3290 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3291 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3292 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3293 */
3294 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3295 var deferred = $.Deferred(),
3296 win = this.windows[ name ];
3297
3298 if ( !( win instanceof OO.ui.Window ) ) {
3299 if ( this.factory ) {
3300 if ( !this.factory.lookup( name ) ) {
3301 deferred.reject( new OO.ui.Error(
3302 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3303 ) );
3304 } else {
3305 win = this.factory.create( name );
3306 this.addWindows( [ win ] );
3307 deferred.resolve( win );
3308 }
3309 } else {
3310 deferred.reject( new OO.ui.Error(
3311 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3312 ) );
3313 }
3314 } else {
3315 deferred.resolve( win );
3316 }
3317
3318 return deferred.promise();
3319 };
3320
3321 /**
3322 * Get current window.
3323 *
3324 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3325 */
3326 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3327 return this.currentWindow;
3328 };
3329
3330 /**
3331 * Open a window.
3332 *
3333 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3334 * @param {Object} [data] Window opening data
3335 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3336 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3337 * @fires opening
3338 */
3339 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3340 var manager = this,
3341 opening = $.Deferred();
3342
3343 // Argument handling
3344 if ( typeof win === 'string' ) {
3345 return this.getWindow( win ).then( function ( win ) {
3346 return manager.openWindow( win, data );
3347 } );
3348 }
3349
3350 // Error handling
3351 if ( !this.hasWindow( win ) ) {
3352 opening.reject( new OO.ui.Error(
3353 'Cannot open window: window is not attached to manager'
3354 ) );
3355 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3356 opening.reject( new OO.ui.Error(
3357 'Cannot open window: another window is opening or open'
3358 ) );
3359 }
3360
3361 // Window opening
3362 if ( opening.state() !== 'rejected' ) {
3363 // If a window is currently closing, wait for it to complete
3364 this.preparingToOpen = $.when( this.closing );
3365 // Ensure handlers get called after preparingToOpen is set
3366 this.preparingToOpen.done( function () {
3367 if ( manager.modal ) {
3368 manager.toggleGlobalEvents( true );
3369 manager.toggleAriaIsolation( true );
3370 }
3371 manager.currentWindow = win;
3372 manager.opening = opening;
3373 manager.preparingToOpen = null;
3374 manager.emit( 'opening', win, opening, data );
3375 setTimeout( function () {
3376 win.setup( data ).then( function () {
3377 manager.updateWindowSize( win );
3378 manager.opening.notify( { state: 'setup' } );
3379 setTimeout( function () {
3380 win.ready( data ).then( function () {
3381 manager.opening.notify( { state: 'ready' } );
3382 manager.opening = null;
3383 manager.opened = $.Deferred();
3384 opening.resolve( manager.opened.promise(), data );
3385 } );
3386 }, manager.getReadyDelay() );
3387 } );
3388 }, manager.getSetupDelay() );
3389 } );
3390 }
3391
3392 return opening.promise();
3393 };
3394
3395 /**
3396 * Close a window.
3397 *
3398 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3399 * @param {Object} [data] Window closing data
3400 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3401 * See {@link #event-closing 'closing' event} for more information about closing promises.
3402 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3403 * @fires closing
3404 */
3405 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3406 var manager = this,
3407 closing = $.Deferred(),
3408 opened;
3409
3410 // Argument handling
3411 if ( typeof win === 'string' ) {
3412 win = this.windows[ win ];
3413 } else if ( !this.hasWindow( win ) ) {
3414 win = null;
3415 }
3416
3417 // Error handling
3418 if ( !win ) {
3419 closing.reject( new OO.ui.Error(
3420 'Cannot close window: window is not attached to manager'
3421 ) );
3422 } else if ( win !== this.currentWindow ) {
3423 closing.reject( new OO.ui.Error(
3424 'Cannot close window: window already closed with different data'
3425 ) );
3426 } else if ( this.preparingToClose || this.closing ) {
3427 closing.reject( new OO.ui.Error(
3428 'Cannot close window: window already closing with different data'
3429 ) );
3430 }
3431
3432 // Window closing
3433 if ( closing.state() !== 'rejected' ) {
3434 // If the window is currently opening, close it when it's done
3435 this.preparingToClose = $.when( this.opening );
3436 // Ensure handlers get called after preparingToClose is set
3437 this.preparingToClose.done( function () {
3438 manager.closing = closing;
3439 manager.preparingToClose = null;
3440 manager.emit( 'closing', win, closing, data );
3441 opened = manager.opened;
3442 manager.opened = null;
3443 opened.resolve( closing.promise(), data );
3444 setTimeout( function () {
3445 win.hold( data ).then( function () {
3446 closing.notify( { state: 'hold' } );
3447 setTimeout( function () {
3448 win.teardown( data ).then( function () {
3449 closing.notify( { state: 'teardown' } );
3450 if ( manager.modal ) {
3451 manager.toggleGlobalEvents( false );
3452 manager.toggleAriaIsolation( false );
3453 }
3454 manager.closing = null;
3455 manager.currentWindow = null;
3456 closing.resolve( data );
3457 } );
3458 }, manager.getTeardownDelay() );
3459 } );
3460 }, manager.getHoldDelay() );
3461 } );
3462 }
3463
3464 return closing.promise();
3465 };
3466
3467 /**
3468 * Add windows to the window manager.
3469 *
3470 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3471 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3472 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3473 *
3474 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3475 * by reference, symbolic name, or explicitly defined symbolic names.
3476 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3477 * explicit nor a statically configured symbolic name.
3478 */
3479 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3480 var i, len, win, name, list;
3481
3482 if ( Array.isArray( windows ) ) {
3483 // Convert to map of windows by looking up symbolic names from static configuration
3484 list = {};
3485 for ( i = 0, len = windows.length; i < len; i++ ) {
3486 name = windows[ i ].constructor.static.name;
3487 if ( typeof name !== 'string' ) {
3488 throw new Error( 'Cannot add window' );
3489 }
3490 list[ name ] = windows[ i ];
3491 }
3492 } else if ( OO.isPlainObject( windows ) ) {
3493 list = windows;
3494 }
3495
3496 // Add windows
3497 for ( name in list ) {
3498 win = list[ name ];
3499 this.windows[ name ] = win.toggle( false );
3500 this.$element.append( win.$element );
3501 win.setManager( this );
3502 }
3503 };
3504
3505 /**
3506 * Remove the specified windows from the windows manager.
3507 *
3508 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3509 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3510 * longer listens to events, use the #destroy method.
3511 *
3512 * @param {string[]} names Symbolic names of windows to remove
3513 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3514 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3515 */
3516 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3517 var i, len, win, name, cleanupWindow,
3518 manager = this,
3519 promises = [],
3520 cleanup = function ( name, win ) {
3521 delete manager.windows[ name ];
3522 win.$element.detach();
3523 };
3524
3525 for ( i = 0, len = names.length; i < len; i++ ) {
3526 name = names[ i ];
3527 win = this.windows[ name ];
3528 if ( !win ) {
3529 throw new Error( 'Cannot remove window' );
3530 }
3531 cleanupWindow = cleanup.bind( null, name, win );
3532 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3533 }
3534
3535 return $.when.apply( $, promises );
3536 };
3537
3538 /**
3539 * Remove all windows from the window manager.
3540 *
3541 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3542 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3543 * To remove just a subset of windows, use the #removeWindows method.
3544 *
3545 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3546 */
3547 OO.ui.WindowManager.prototype.clearWindows = function () {
3548 return this.removeWindows( Object.keys( this.windows ) );
3549 };
3550
3551 /**
3552 * Set dialog size. In general, this method should not be called directly.
3553 *
3554 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3555 *
3556 * @chainable
3557 */
3558 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3559 var isFullscreen;
3560
3561 // Bypass for non-current, and thus invisible, windows
3562 if ( win !== this.currentWindow ) {
3563 return;
3564 }
3565
3566 isFullscreen = win.getSize() === 'full';
3567
3568 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
3569 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
3570 win.setDimensions( win.getSizeProperties() );
3571
3572 this.emit( 'resize', win );
3573
3574 return this;
3575 };
3576
3577 /**
3578 * Bind or unbind global events for scrolling.
3579 *
3580 * @private
3581 * @param {boolean} [on] Bind global events
3582 * @chainable
3583 */
3584 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3585 var scrollWidth, bodyMargin,
3586 $body = $( this.getElementDocument().body ),
3587 // We could have multiple window managers open so only modify
3588 // the body css at the bottom of the stack
3589 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3590
3591 on = on === undefined ? !!this.globalEvents : !!on;
3592
3593 if ( on ) {
3594 if ( !this.globalEvents ) {
3595 $( this.getElementWindow() ).on( {
3596 // Start listening for top-level window dimension changes
3597 'orientationchange resize': this.onWindowResizeHandler
3598 } );
3599 if ( stackDepth === 0 ) {
3600 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3601 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3602 $body.css( {
3603 overflow: 'hidden',
3604 'margin-right': bodyMargin + scrollWidth
3605 } );
3606 }
3607 stackDepth++;
3608 this.globalEvents = true;
3609 }
3610 } else if ( this.globalEvents ) {
3611 $( this.getElementWindow() ).off( {
3612 // Stop listening for top-level window dimension changes
3613 'orientationchange resize': this.onWindowResizeHandler
3614 } );
3615 stackDepth--;
3616 if ( stackDepth === 0 ) {
3617 $body.css( {
3618 overflow: '',
3619 'margin-right': ''
3620 } );
3621 }
3622 this.globalEvents = false;
3623 }
3624 $body.data( 'windowManagerGlobalEvents', stackDepth );
3625
3626 return this;
3627 };
3628
3629 /**
3630 * Toggle screen reader visibility of content other than the window manager.
3631 *
3632 * @private
3633 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3634 * @chainable
3635 */
3636 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3637 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3638
3639 if ( isolate ) {
3640 if ( !this.$ariaHidden ) {
3641 // Hide everything other than the window manager from screen readers
3642 this.$ariaHidden = $( 'body' )
3643 .children()
3644 .not( this.$element.parentsUntil( 'body' ).last() )
3645 .attr( 'aria-hidden', '' );
3646 }
3647 } else if ( this.$ariaHidden ) {
3648 // Restore screen reader visibility
3649 this.$ariaHidden.removeAttr( 'aria-hidden' );
3650 this.$ariaHidden = null;
3651 }
3652
3653 return this;
3654 };
3655
3656 /**
3657 * Destroy the window manager.
3658 *
3659 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3660 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3661 * instead.
3662 */
3663 OO.ui.WindowManager.prototype.destroy = function () {
3664 this.toggleGlobalEvents( false );
3665 this.toggleAriaIsolation( false );
3666 this.clearWindows();
3667 this.$element.remove();
3668 };
3669
3670 /**
3671 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3672 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3673 * appearance and functionality of the error interface.
3674 *
3675 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3676 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3677 * that initiated the failed process will be disabled.
3678 *
3679 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3680 * process again.
3681 *
3682 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3683 *
3684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3685 *
3686 * @class
3687 *
3688 * @constructor
3689 * @param {string|jQuery} message Description of error
3690 * @param {Object} [config] Configuration options
3691 * @cfg {boolean} [recoverable=true] Error is recoverable.
3692 * By default, errors are recoverable, and users can try the process again.
3693 * @cfg {boolean} [warning=false] Error is a warning.
3694 * If the error is a warning, the error interface will include a
3695 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3696 * is not triggered a second time if the user chooses to continue.
3697 */
3698 OO.ui.Error = function OoUiError( message, config ) {
3699 // Allow passing positional parameters inside the config object
3700 if ( OO.isPlainObject( message ) && config === undefined ) {
3701 config = message;
3702 message = config.message;
3703 }
3704
3705 // Configuration initialization
3706 config = config || {};
3707
3708 // Properties
3709 this.message = message instanceof jQuery ? message : String( message );
3710 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3711 this.warning = !!config.warning;
3712 };
3713
3714 /* Setup */
3715
3716 OO.initClass( OO.ui.Error );
3717
3718 /* Methods */
3719
3720 /**
3721 * Check if the error is recoverable.
3722 *
3723 * If the error is recoverable, users are able to try the process again.
3724 *
3725 * @return {boolean} Error is recoverable
3726 */
3727 OO.ui.Error.prototype.isRecoverable = function () {
3728 return this.recoverable;
3729 };
3730
3731 /**
3732 * Check if the error is a warning.
3733 *
3734 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3735 *
3736 * @return {boolean} Error is warning
3737 */
3738 OO.ui.Error.prototype.isWarning = function () {
3739 return this.warning;
3740 };
3741
3742 /**
3743 * Get error message as DOM nodes.
3744 *
3745 * @return {jQuery} Error message in DOM nodes
3746 */
3747 OO.ui.Error.prototype.getMessage = function () {
3748 return this.message instanceof jQuery ?
3749 this.message.clone() :
3750 $( '<div>' ).text( this.message ).contents();
3751 };
3752
3753 /**
3754 * Get the error message text.
3755 *
3756 * @return {string} Error message
3757 */
3758 OO.ui.Error.prototype.getMessageText = function () {
3759 return this.message instanceof jQuery ? this.message.text() : this.message;
3760 };
3761
3762 /**
3763 * Wraps an HTML snippet for use with configuration values which default
3764 * to strings. This bypasses the default html-escaping done to string
3765 * values.
3766 *
3767 * @class
3768 *
3769 * @constructor
3770 * @param {string} [content] HTML content
3771 */
3772 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3773 // Properties
3774 this.content = content;
3775 };
3776
3777 /* Setup */
3778
3779 OO.initClass( OO.ui.HtmlSnippet );
3780
3781 /* Methods */
3782
3783 /**
3784 * Render into HTML.
3785 *
3786 * @return {string} Unchanged HTML snippet.
3787 */
3788 OO.ui.HtmlSnippet.prototype.toString = function () {
3789 return this.content;
3790 };
3791
3792 /**
3793 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3794 * or a function:
3795 *
3796 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3797 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3798 * or stop if the promise is rejected.
3799 * - **function**: the process will execute the function. The process will stop if the function returns
3800 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3801 * will wait for that number of milliseconds before proceeding.
3802 *
3803 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3804 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3805 * its remaining steps will not be performed.
3806 *
3807 * @class
3808 *
3809 * @constructor
3810 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3811 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3812 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3813 * a number or promise.
3814 * @return {Object} Step object, with `callback` and `context` properties
3815 */
3816 OO.ui.Process = function ( step, context ) {
3817 // Properties
3818 this.steps = [];
3819
3820 // Initialization
3821 if ( step !== undefined ) {
3822 this.next( step, context );
3823 }
3824 };
3825
3826 /* Setup */
3827
3828 OO.initClass( OO.ui.Process );
3829
3830 /* Methods */
3831
3832 /**
3833 * Start the process.
3834 *
3835 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3836 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3837 * and any remaining steps are not performed.
3838 */
3839 OO.ui.Process.prototype.execute = function () {
3840 var i, len, promise;
3841
3842 /**
3843 * Continue execution.
3844 *
3845 * @ignore
3846 * @param {Array} step A function and the context it should be called in
3847 * @return {Function} Function that continues the process
3848 */
3849 function proceed( step ) {
3850 return function () {
3851 // Execute step in the correct context
3852 var deferred,
3853 result = step.callback.call( step.context );
3854
3855 if ( result === false ) {
3856 // Use rejected promise for boolean false results
3857 return $.Deferred().reject( [] ).promise();
3858 }
3859 if ( typeof result === 'number' ) {
3860 if ( result < 0 ) {
3861 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3862 }
3863 // Use a delayed promise for numbers, expecting them to be in milliseconds
3864 deferred = $.Deferred();
3865 setTimeout( deferred.resolve, result );
3866 return deferred.promise();
3867 }
3868 if ( result instanceof OO.ui.Error ) {
3869 // Use rejected promise for error
3870 return $.Deferred().reject( [ result ] ).promise();
3871 }
3872 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3873 // Use rejected promise for list of errors
3874 return $.Deferred().reject( result ).promise();
3875 }
3876 // Duck-type the object to see if it can produce a promise
3877 if ( result && $.isFunction( result.promise ) ) {
3878 // Use a promise generated from the result
3879 return result.promise();
3880 }
3881 // Use resolved promise for other results
3882 return $.Deferred().resolve().promise();
3883 };
3884 }
3885
3886 if ( this.steps.length ) {
3887 // Generate a chain reaction of promises
3888 promise = proceed( this.steps[ 0 ] )();
3889 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3890 promise = promise.then( proceed( this.steps[ i ] ) );
3891 }
3892 } else {
3893 promise = $.Deferred().resolve().promise();
3894 }
3895
3896 return promise;
3897 };
3898
3899 /**
3900 * Create a process step.
3901 *
3902 * @private
3903 * @param {number|jQuery.Promise|Function} step
3904 *
3905 * - Number of milliseconds to wait before proceeding
3906 * - Promise that must be resolved before proceeding
3907 * - Function to execute
3908 * - If the function returns a boolean false the process will stop
3909 * - If the function returns a promise, the process will continue to the next
3910 * step when the promise is resolved or stop if the promise is rejected
3911 * - If the function returns a number, the process will wait for that number of
3912 * milliseconds before proceeding
3913 * @param {Object} [context=null] Execution context of the function. The context is
3914 * ignored if the step is a number or promise.
3915 * @return {Object} Step object, with `callback` and `context` properties
3916 */
3917 OO.ui.Process.prototype.createStep = function ( step, context ) {
3918 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3919 return {
3920 callback: function () {
3921 return step;
3922 },
3923 context: null
3924 };
3925 }
3926 if ( $.isFunction( step ) ) {
3927 return {
3928 callback: step,
3929 context: context
3930 };
3931 }
3932 throw new Error( 'Cannot create process step: number, promise or function expected' );
3933 };
3934
3935 /**
3936 * Add step to the beginning of the process.
3937 *
3938 * @inheritdoc #createStep
3939 * @return {OO.ui.Process} this
3940 * @chainable
3941 */
3942 OO.ui.Process.prototype.first = function ( step, context ) {
3943 this.steps.unshift( this.createStep( step, context ) );
3944 return this;
3945 };
3946
3947 /**
3948 * Add step to the end of the process.
3949 *
3950 * @inheritdoc #createStep
3951 * @return {OO.ui.Process} this
3952 * @chainable
3953 */
3954 OO.ui.Process.prototype.next = function ( step, context ) {
3955 this.steps.push( this.createStep( step, context ) );
3956 return this;
3957 };
3958
3959 /**
3960 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3961 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3962 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3963 *
3964 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3965 *
3966 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3967 *
3968 * @class
3969 * @extends OO.Factory
3970 * @constructor
3971 */
3972 OO.ui.ToolFactory = function OoUiToolFactory() {
3973 // Parent constructor
3974 OO.ui.ToolFactory.parent.call( this );
3975 };
3976
3977 /* Setup */
3978
3979 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3980
3981 /* Methods */
3982
3983 /**
3984 * Get tools from the factory
3985 *
3986 * @param {Array} include Included tools
3987 * @param {Array} exclude Excluded tools
3988 * @param {Array} promote Promoted tools
3989 * @param {Array} demote Demoted tools
3990 * @return {string[]} List of tools
3991 */
3992 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3993 var i, len, included, promoted, demoted,
3994 auto = [],
3995 used = {};
3996
3997 // Collect included and not excluded tools
3998 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3999
4000 // Promotion
4001 promoted = this.extract( promote, used );
4002 demoted = this.extract( demote, used );
4003
4004 // Auto
4005 for ( i = 0, len = included.length; i < len; i++ ) {
4006 if ( !used[ included[ i ] ] ) {
4007 auto.push( included[ i ] );
4008 }
4009 }
4010
4011 return promoted.concat( auto ).concat( demoted );
4012 };
4013
4014 /**
4015 * Get a flat list of names from a list of names or groups.
4016 *
4017 * Tools can be specified in the following ways:
4018 *
4019 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4020 * - All tools in a group: `{ group: 'group-name' }`
4021 * - All tools: `'*'`
4022 *
4023 * @private
4024 * @param {Array|string} collection List of tools
4025 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4026 * names will be added as properties
4027 * @return {string[]} List of extracted names
4028 */
4029 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
4030 var i, len, item, name, tool,
4031 names = [];
4032
4033 if ( collection === '*' ) {
4034 for ( name in this.registry ) {
4035 tool = this.registry[ name ];
4036 if (
4037 // Only add tools by group name when auto-add is enabled
4038 tool.static.autoAddToCatchall &&
4039 // Exclude already used tools
4040 ( !used || !used[ name ] )
4041 ) {
4042 names.push( name );
4043 if ( used ) {
4044 used[ name ] = true;
4045 }
4046 }
4047 }
4048 } else if ( Array.isArray( collection ) ) {
4049 for ( i = 0, len = collection.length; i < len; i++ ) {
4050 item = collection[ i ];
4051 // Allow plain strings as shorthand for named tools
4052 if ( typeof item === 'string' ) {
4053 item = { name: item };
4054 }
4055 if ( OO.isPlainObject( item ) ) {
4056 if ( item.group ) {
4057 for ( name in this.registry ) {
4058 tool = this.registry[ name ];
4059 if (
4060 // Include tools with matching group
4061 tool.static.group === item.group &&
4062 // Only add tools by group name when auto-add is enabled
4063 tool.static.autoAddToGroup &&
4064 // Exclude already used tools
4065 ( !used || !used[ name ] )
4066 ) {
4067 names.push( name );
4068 if ( used ) {
4069 used[ name ] = true;
4070 }
4071 }
4072 }
4073 // Include tools with matching name and exclude already used tools
4074 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
4075 names.push( item.name );
4076 if ( used ) {
4077 used[ item.name ] = true;
4078 }
4079 }
4080 }
4081 }
4082 }
4083 return names;
4084 };
4085
4086 /**
4087 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4088 * specify a symbolic name and be registered with the factory. The following classes are registered by
4089 * default:
4090 *
4091 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4092 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4093 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4094 *
4095 * See {@link OO.ui.Toolbar toolbars} for an example.
4096 *
4097 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4098 *
4099 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4100 * @class
4101 * @extends OO.Factory
4102 * @constructor
4103 */
4104 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
4105 var i, l, defaultClasses;
4106 // Parent constructor
4107 OO.Factory.call( this );
4108
4109 defaultClasses = this.constructor.static.getDefaultClasses();
4110
4111 // Register default toolgroups
4112 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
4113 this.register( defaultClasses[ i ] );
4114 }
4115 };
4116
4117 /* Setup */
4118
4119 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
4120
4121 /* Static Methods */
4122
4123 /**
4124 * Get a default set of classes to be registered on construction.
4125 *
4126 * @return {Function[]} Default classes
4127 */
4128 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
4129 return [
4130 OO.ui.BarToolGroup,
4131 OO.ui.ListToolGroup,
4132 OO.ui.MenuToolGroup
4133 ];
4134 };
4135
4136 /**
4137 * Theme logic.
4138 *
4139 * @abstract
4140 * @class
4141 *
4142 * @constructor
4143 * @param {Object} [config] Configuration options
4144 */
4145 OO.ui.Theme = function OoUiTheme( config ) {
4146 // Configuration initialization
4147 config = config || {};
4148 };
4149
4150 /* Setup */
4151
4152 OO.initClass( OO.ui.Theme );
4153
4154 /* Methods */
4155
4156 /**
4157 * Get a list of classes to be applied to a widget.
4158 *
4159 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4160 * otherwise state transitions will not work properly.
4161 *
4162 * @param {OO.ui.Element} element Element for which to get classes
4163 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4164 */
4165 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
4166 return { on: [], off: [] };
4167 };
4168
4169 /**
4170 * Update CSS classes provided by the theme.
4171 *
4172 * For elements with theme logic hooks, this should be called any time there's a state change.
4173 *
4174 * @param {OO.ui.Element} element Element for which to update classes
4175 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4176 */
4177 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
4178 var $elements = $( [] ),
4179 classes = this.getElementClasses( element );
4180
4181 if ( element.$icon ) {
4182 $elements = $elements.add( element.$icon );
4183 }
4184 if ( element.$indicator ) {
4185 $elements = $elements.add( element.$indicator );
4186 }
4187
4188 $elements
4189 .removeClass( classes.off.join( ' ' ) )
4190 .addClass( classes.on.join( ' ' ) );
4191 };
4192
4193 /**
4194 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4195 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4196 * order in which users will navigate through the focusable elements via the "tab" key.
4197 *
4198 * @example
4199 * // TabIndexedElement is mixed into the ButtonWidget class
4200 * // to provide a tabIndex property.
4201 * var button1 = new OO.ui.ButtonWidget( {
4202 * label: 'fourth',
4203 * tabIndex: 4
4204 * } );
4205 * var button2 = new OO.ui.ButtonWidget( {
4206 * label: 'second',
4207 * tabIndex: 2
4208 * } );
4209 * var button3 = new OO.ui.ButtonWidget( {
4210 * label: 'third',
4211 * tabIndex: 3
4212 * } );
4213 * var button4 = new OO.ui.ButtonWidget( {
4214 * label: 'first',
4215 * tabIndex: 1
4216 * } );
4217 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4218 *
4219 * @abstract
4220 * @class
4221 *
4222 * @constructor
4223 * @param {Object} [config] Configuration options
4224 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4225 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4226 * functionality will be applied to it instead.
4227 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4228 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4229 * to remove the element from the tab-navigation flow.
4230 */
4231 OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) {
4232 // Configuration initialization
4233 config = $.extend( { tabIndex: 0 }, config );
4234
4235 // Properties
4236 this.$tabIndexed = null;
4237 this.tabIndex = null;
4238
4239 // Events
4240 this.connect( this, { disable: 'onTabIndexedElementDisable' } );
4241
4242 // Initialization
4243 this.setTabIndex( config.tabIndex );
4244 this.setTabIndexedElement( config.$tabIndexed || this.$element );
4245 };
4246
4247 /* Setup */
4248
4249 OO.initClass( OO.ui.mixin.TabIndexedElement );
4250
4251 /* Methods */
4252
4253 /**
4254 * Set the element that should use the tabindex functionality.
4255 *
4256 * This method is used to retarget a tabindex mixin so that its functionality applies
4257 * to the specified element. If an element is currently using the functionality, the mixin’s
4258 * effect on that element is removed before the new element is set up.
4259 *
4260 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4261 * @chainable
4262 */
4263 OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
4264 var tabIndex = this.tabIndex;
4265 // Remove attributes from old $tabIndexed
4266 this.setTabIndex( null );
4267 // Force update of new $tabIndexed
4268 this.$tabIndexed = $tabIndexed;
4269 this.tabIndex = tabIndex;
4270 return this.updateTabIndex();
4271 };
4272
4273 /**
4274 * Set the value of the tabindex.
4275 *
4276 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4277 * @chainable
4278 */
4279 OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
4280 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
4281
4282 if ( this.tabIndex !== tabIndex ) {
4283 this.tabIndex = tabIndex;
4284 this.updateTabIndex();
4285 }
4286
4287 return this;
4288 };
4289
4290 /**
4291 * Update the `tabindex` attribute, in case of changes to tab index or
4292 * disabled state.
4293 *
4294 * @private
4295 * @chainable
4296 */
4297 OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () {
4298 if ( this.$tabIndexed ) {
4299 if ( this.tabIndex !== null ) {
4300 // Do not index over disabled elements
4301 this.$tabIndexed.attr( {
4302 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4303 // Support: ChromeVox and NVDA
4304 // These do not seem to inherit aria-disabled from parent elements
4305 'aria-disabled': this.isDisabled().toString()
4306 } );
4307 } else {
4308 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4309 }
4310 }
4311 return this;
4312 };
4313
4314 /**
4315 * Handle disable events.
4316 *
4317 * @private
4318 * @param {boolean} disabled Element is disabled
4319 */
4320 OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () {
4321 this.updateTabIndex();
4322 };
4323
4324 /**
4325 * Get the value of the tabindex.
4326 *
4327 * @return {number|null} Tabindex value
4328 */
4329 OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () {
4330 return this.tabIndex;
4331 };
4332
4333 /**
4334 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4335 * interface element that can be configured with access keys for accessibility.
4336 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4337 *
4338 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4339 * @abstract
4340 * @class
4341 *
4342 * @constructor
4343 * @param {Object} [config] Configuration options
4344 * @cfg {jQuery} [$button] The button element created by the class.
4345 * If this configuration is omitted, the button element will use a generated `<a>`.
4346 * @cfg {boolean} [framed=true] Render the button with a frame
4347 */
4348 OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) {
4349 // Configuration initialization
4350 config = config || {};
4351
4352 // Properties
4353 this.$button = null;
4354 this.framed = null;
4355 this.active = false;
4356 this.onMouseUpHandler = this.onMouseUp.bind( this );
4357 this.onMouseDownHandler = this.onMouseDown.bind( this );
4358 this.onKeyDownHandler = this.onKeyDown.bind( this );
4359 this.onKeyUpHandler = this.onKeyUp.bind( this );
4360 this.onClickHandler = this.onClick.bind( this );
4361 this.onKeyPressHandler = this.onKeyPress.bind( this );
4362
4363 // Initialization
4364 this.$element.addClass( 'oo-ui-buttonElement' );
4365 this.toggleFramed( config.framed === undefined || config.framed );
4366 this.setButtonElement( config.$button || $( '<a>' ) );
4367 };
4368
4369 /* Setup */
4370
4371 OO.initClass( OO.ui.mixin.ButtonElement );
4372
4373 /* Static Properties */
4374
4375 /**
4376 * Cancel mouse down events.
4377 *
4378 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4379 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4380 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4381 * parent widget.
4382 *
4383 * @static
4384 * @inheritable
4385 * @property {boolean}
4386 */
4387 OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true;
4388
4389 /* Events */
4390
4391 /**
4392 * A 'click' event is emitted when the button element is clicked.
4393 *
4394 * @event click
4395 */
4396
4397 /* Methods */
4398
4399 /**
4400 * Set the button element.
4401 *
4402 * This method is used to retarget a button mixin so that its functionality applies to
4403 * the specified button element instead of the one created by the class. If a button element
4404 * is already set, the method will remove the mixin’s effect on that element.
4405 *
4406 * @param {jQuery} $button Element to use as button
4407 */
4408 OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) {
4409 if ( this.$button ) {
4410 this.$button
4411 .removeClass( 'oo-ui-buttonElement-button' )
4412 .removeAttr( 'role accesskey' )
4413 .off( {
4414 mousedown: this.onMouseDownHandler,
4415 keydown: this.onKeyDownHandler,
4416 click: this.onClickHandler,
4417 keypress: this.onKeyPressHandler
4418 } );
4419 }
4420
4421 this.$button = $button
4422 .addClass( 'oo-ui-buttonElement-button' )
4423 .attr( { role: 'button' } )
4424 .on( {
4425 mousedown: this.onMouseDownHandler,
4426 keydown: this.onKeyDownHandler,
4427 click: this.onClickHandler,
4428 keypress: this.onKeyPressHandler
4429 } );
4430 };
4431
4432 /**
4433 * Handles mouse down events.
4434 *
4435 * @protected
4436 * @param {jQuery.Event} e Mouse down event
4437 */
4438 OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) {
4439 if ( this.isDisabled() || e.which !== 1 ) {
4440 return;
4441 }
4442 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4443 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4444 // reliably remove the pressed class
4445 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4446 // Prevent change of focus unless specifically configured otherwise
4447 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4448 return false;
4449 }
4450 };
4451
4452 /**
4453 * Handles mouse up events.
4454 *
4455 * @protected
4456 * @param {jQuery.Event} e Mouse up event
4457 */
4458 OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) {
4459 if ( this.isDisabled() || e.which !== 1 ) {
4460 return;
4461 }
4462 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4463 // Stop listening for mouseup, since we only needed this once
4464 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler );
4465 };
4466
4467 /**
4468 * Handles mouse click events.
4469 *
4470 * @protected
4471 * @param {jQuery.Event} e Mouse click event
4472 * @fires click
4473 */
4474 OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) {
4475 if ( !this.isDisabled() && e.which === 1 ) {
4476 if ( this.emit( 'click' ) ) {
4477 return false;
4478 }
4479 }
4480 };
4481
4482 /**
4483 * Handles key down events.
4484 *
4485 * @protected
4486 * @param {jQuery.Event} e Key down event
4487 */
4488 OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) {
4489 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4490 return;
4491 }
4492 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4493 // Run the keyup handler no matter where the key is when the button is let go, so we can
4494 // reliably remove the pressed class
4495 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4496 };
4497
4498 /**
4499 * Handles key up events.
4500 *
4501 * @protected
4502 * @param {jQuery.Event} e Key up event
4503 */
4504 OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) {
4505 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4506 return;
4507 }
4508 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4509 // Stop listening for keyup, since we only needed this once
4510 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler );
4511 };
4512
4513 /**
4514 * Handles key press events.
4515 *
4516 * @protected
4517 * @param {jQuery.Event} e Key press event
4518 * @fires click
4519 */
4520 OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) {
4521 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4522 if ( this.emit( 'click' ) ) {
4523 return false;
4524 }
4525 }
4526 };
4527
4528 /**
4529 * Check if button has a frame.
4530 *
4531 * @return {boolean} Button is framed
4532 */
4533 OO.ui.mixin.ButtonElement.prototype.isFramed = function () {
4534 return this.framed;
4535 };
4536
4537 /**
4538 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4539 *
4540 * @param {boolean} [framed] Make button framed, omit to toggle
4541 * @chainable
4542 */
4543 OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) {
4544 framed = framed === undefined ? !this.framed : !!framed;
4545 if ( framed !== this.framed ) {
4546 this.framed = framed;
4547 this.$element
4548 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4549 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4550 this.updateThemeClasses();
4551 }
4552
4553 return this;
4554 };
4555
4556 /**
4557 * Set the button to its 'active' state.
4558 *
4559 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4560 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4561 * for other button types.
4562 *
4563 * @param {boolean} [value] Make button active
4564 * @chainable
4565 */
4566 OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) {
4567 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4568 return this;
4569 };
4570
4571 /**
4572 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4573 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4574 * items from the group is done through the interface the class provides.
4575 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4576 *
4577 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4578 *
4579 * @abstract
4580 * @class
4581 *
4582 * @constructor
4583 * @param {Object} [config] Configuration options
4584 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4585 * is omitted, the group element will use a generated `<div>`.
4586 */
4587 OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) {
4588 // Configuration initialization
4589 config = config || {};
4590
4591 // Properties
4592 this.$group = null;
4593 this.items = [];
4594 this.aggregateItemEvents = {};
4595
4596 // Initialization
4597 this.setGroupElement( config.$group || $( '<div>' ) );
4598 };
4599
4600 /* Methods */
4601
4602 /**
4603 * Set the group element.
4604 *
4605 * If an element is already set, items will be moved to the new element.
4606 *
4607 * @param {jQuery} $group Element to use as group
4608 */
4609 OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) {
4610 var i, len;
4611
4612 this.$group = $group;
4613 for ( i = 0, len = this.items.length; i < len; i++ ) {
4614 this.$group.append( this.items[ i ].$element );
4615 }
4616 };
4617
4618 /**
4619 * Check if a group contains no items.
4620 *
4621 * @return {boolean} Group is empty
4622 */
4623 OO.ui.mixin.GroupElement.prototype.isEmpty = function () {
4624 return !this.items.length;
4625 };
4626
4627 /**
4628 * Get all items in the group.
4629 *
4630 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4631 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4632 * from a group).
4633 *
4634 * @return {OO.ui.Element[]} An array of items.
4635 */
4636 OO.ui.mixin.GroupElement.prototype.getItems = function () {
4637 return this.items.slice( 0 );
4638 };
4639
4640 /**
4641 * Get an item by its data.
4642 *
4643 * Only the first item with matching data will be returned. To return all matching items,
4644 * use the #getItemsFromData method.
4645 *
4646 * @param {Object} data Item data to search for
4647 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4648 */
4649 OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) {
4650 var i, len, item,
4651 hash = OO.getHash( data );
4652
4653 for ( i = 0, len = this.items.length; i < len; i++ ) {
4654 item = this.items[ i ];
4655 if ( hash === OO.getHash( item.getData() ) ) {
4656 return item;
4657 }
4658 }
4659
4660 return null;
4661 };
4662
4663 /**
4664 * Get items by their data.
4665 *
4666 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4667 *
4668 * @param {Object} data Item data to search for
4669 * @return {OO.ui.Element[]} Items with equivalent data
4670 */
4671 OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) {
4672 var i, len, item,
4673 hash = OO.getHash( data ),
4674 items = [];
4675
4676 for ( i = 0, len = this.items.length; i < len; i++ ) {
4677 item = this.items[ i ];
4678 if ( hash === OO.getHash( item.getData() ) ) {
4679 items.push( item );
4680 }
4681 }
4682
4683 return items;
4684 };
4685
4686 /**
4687 * Aggregate the events emitted by the group.
4688 *
4689 * When events are aggregated, the group will listen to all contained items for the event,
4690 * and then emit the event under a new name. The new event will contain an additional leading
4691 * parameter containing the item that emitted the original event. Other arguments emitted from
4692 * the original event are passed through.
4693 *
4694 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4695 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4696 * A `null` value will remove aggregated events.
4697
4698 * @throws {Error} An error is thrown if aggregation already exists.
4699 */
4700 OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) {
4701 var i, len, item, add, remove, itemEvent, groupEvent;
4702
4703 for ( itemEvent in events ) {
4704 groupEvent = events[ itemEvent ];
4705
4706 // Remove existing aggregated event
4707 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4708 // Don't allow duplicate aggregations
4709 if ( groupEvent ) {
4710 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4711 }
4712 // Remove event aggregation from existing items
4713 for ( i = 0, len = this.items.length; i < len; i++ ) {
4714 item = this.items[ i ];
4715 if ( item.connect && item.disconnect ) {
4716 remove = {};
4717 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4718 item.disconnect( this, remove );
4719 }
4720 }
4721 // Prevent future items from aggregating event
4722 delete this.aggregateItemEvents[ itemEvent ];
4723 }
4724
4725 // Add new aggregate event
4726 if ( groupEvent ) {
4727 // Make future items aggregate event
4728 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4729 // Add event aggregation to existing items
4730 for ( i = 0, len = this.items.length; i < len; i++ ) {
4731 item = this.items[ i ];
4732 if ( item.connect && item.disconnect ) {
4733 add = {};
4734 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4735 item.connect( this, add );
4736 }
4737 }
4738 }
4739 }
4740 };
4741
4742 /**
4743 * Add items to the group.
4744 *
4745 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4746 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4747 *
4748 * @param {OO.ui.Element[]} items An array of items to add to the group
4749 * @param {number} [index] Index of the insertion point
4750 * @chainable
4751 */
4752 OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) {
4753 var i, len, item, event, events, currentIndex,
4754 itemElements = [];
4755
4756 for ( i = 0, len = items.length; i < len; i++ ) {
4757 item = items[ i ];
4758
4759 // Check if item exists then remove it first, effectively "moving" it
4760 currentIndex = this.items.indexOf( item );
4761 if ( currentIndex >= 0 ) {
4762 this.removeItems( [ item ] );
4763 // Adjust index to compensate for removal
4764 if ( currentIndex < index ) {
4765 index--;
4766 }
4767 }
4768 // Add the item
4769 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4770 events = {};
4771 for ( event in this.aggregateItemEvents ) {
4772 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4773 }
4774 item.connect( this, events );
4775 }
4776 item.setElementGroup( this );
4777 itemElements.push( item.$element.get( 0 ) );
4778 }
4779
4780 if ( index === undefined || index < 0 || index >= this.items.length ) {
4781 this.$group.append( itemElements );
4782 this.items.push.apply( this.items, items );
4783 } else if ( index === 0 ) {
4784 this.$group.prepend( itemElements );
4785 this.items.unshift.apply( this.items, items );
4786 } else {
4787 this.items[ index ].$element.before( itemElements );
4788 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4789 }
4790
4791 return this;
4792 };
4793
4794 /**
4795 * Remove the specified items from a group.
4796 *
4797 * Removed items are detached (not removed) from the DOM so that they may be reused.
4798 * To remove all items from a group, you may wish to use the #clearItems method instead.
4799 *
4800 * @param {OO.ui.Element[]} items An array of items to remove
4801 * @chainable
4802 */
4803 OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) {
4804 var i, len, item, index, remove, itemEvent;
4805
4806 // Remove specific items
4807 for ( i = 0, len = items.length; i < len; i++ ) {
4808 item = items[ i ];
4809 index = this.items.indexOf( item );
4810 if ( index !== -1 ) {
4811 if (
4812 item.connect && item.disconnect &&
4813 !$.isEmptyObject( this.aggregateItemEvents )
4814 ) {
4815 remove = {};
4816 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4817 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4818 }
4819 item.disconnect( this, remove );
4820 }
4821 item.setElementGroup( null );
4822 this.items.splice( index, 1 );
4823 item.$element.detach();
4824 }
4825 }
4826
4827 return this;
4828 };
4829
4830 /**
4831 * Clear all items from the group.
4832 *
4833 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4834 * To remove only a subset of items from a group, use the #removeItems method.
4835 *
4836 * @chainable
4837 */
4838 OO.ui.mixin.GroupElement.prototype.clearItems = function () {
4839 var i, len, item, remove, itemEvent;
4840
4841 // Remove all items
4842 for ( i = 0, len = this.items.length; i < len; i++ ) {
4843 item = this.items[ i ];
4844 if (
4845 item.connect && item.disconnect &&
4846 !$.isEmptyObject( this.aggregateItemEvents )
4847 ) {
4848 remove = {};
4849 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4850 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4851 }
4852 item.disconnect( this, remove );
4853 }
4854 item.setElementGroup( null );
4855 item.$element.detach();
4856 }
4857
4858 this.items = [];
4859 return this;
4860 };
4861
4862 /**
4863 * DraggableElement is a mixin class used to create elements that can be clicked
4864 * and dragged by a mouse to a new position within a group. This class must be used
4865 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4866 * the draggable elements.
4867 *
4868 * @abstract
4869 * @class
4870 *
4871 * @constructor
4872 */
4873 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement() {
4874 // Properties
4875 this.index = null;
4876
4877 // Initialize and events
4878 this.$element
4879 .attr( 'draggable', true )
4880 .addClass( 'oo-ui-draggableElement' )
4881 .on( {
4882 dragstart: this.onDragStart.bind( this ),
4883 dragover: this.onDragOver.bind( this ),
4884 dragend: this.onDragEnd.bind( this ),
4885 drop: this.onDrop.bind( this )
4886 } );
4887 };
4888
4889 OO.initClass( OO.ui.mixin.DraggableElement );
4890
4891 /* Events */
4892
4893 /**
4894 * @event dragstart
4895 *
4896 * A dragstart event is emitted when the user clicks and begins dragging an item.
4897 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4898 */
4899
4900 /**
4901 * @event dragend
4902 * A dragend event is emitted when the user drags an item and releases the mouse,
4903 * thus terminating the drag operation.
4904 */
4905
4906 /**
4907 * @event drop
4908 * A drop event is emitted when the user drags an item and then releases the mouse button
4909 * over a valid target.
4910 */
4911
4912 /* Static Properties */
4913
4914 /**
4915 * @inheritdoc OO.ui.mixin.ButtonElement
4916 */
4917 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
4918
4919 /* Methods */
4920
4921 /**
4922 * Respond to dragstart event.
4923 *
4924 * @private
4925 * @param {jQuery.Event} event jQuery event
4926 * @fires dragstart
4927 */
4928 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
4929 var dataTransfer = e.originalEvent.dataTransfer;
4930 // Define drop effect
4931 dataTransfer.dropEffect = 'none';
4932 dataTransfer.effectAllowed = 'move';
4933 // Support: Firefox
4934 // We must set up a dataTransfer data property or Firefox seems to
4935 // ignore the fact the element is draggable.
4936 try {
4937 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4938 } catch ( err ) {
4939 // The above is only for Firefox. Move on if it fails.
4940 }
4941 // Add dragging class
4942 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4943 // Emit event
4944 this.emit( 'dragstart', this );
4945 return true;
4946 };
4947
4948 /**
4949 * Respond to dragend event.
4950 *
4951 * @private
4952 * @fires dragend
4953 */
4954 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
4955 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4956 this.emit( 'dragend' );
4957 };
4958
4959 /**
4960 * Handle drop event.
4961 *
4962 * @private
4963 * @param {jQuery.Event} event jQuery event
4964 * @fires drop
4965 */
4966 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
4967 e.preventDefault();
4968 this.emit( 'drop', e );
4969 };
4970
4971 /**
4972 * In order for drag/drop to work, the dragover event must
4973 * return false and stop propogation.
4974 *
4975 * @private
4976 */
4977 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
4978 e.preventDefault();
4979 };
4980
4981 /**
4982 * Set item index.
4983 * Store it in the DOM so we can access from the widget drag event
4984 *
4985 * @private
4986 * @param {number} Item index
4987 */
4988 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
4989 if ( this.index !== index ) {
4990 this.index = index;
4991 this.$element.data( 'index', index );
4992 }
4993 };
4994
4995 /**
4996 * Get item index
4997 *
4998 * @private
4999 * @return {number} Item index
5000 */
5001 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
5002 return this.index;
5003 };
5004
5005 /**
5006 * DraggableGroupElement is a mixin class used to create a group element to
5007 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5008 * The class is used with OO.ui.mixin.DraggableElement.
5009 *
5010 * @abstract
5011 * @class
5012 * @mixins OO.ui.mixin.GroupElement
5013 *
5014 * @constructor
5015 * @param {Object} [config] Configuration options
5016 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5017 * should match the layout of the items. Items displayed in a single row
5018 * or in several rows should use horizontal orientation. The vertical orientation should only be
5019 * used when the items are displayed in a single column. Defaults to 'vertical'
5020 */
5021 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
5022 // Configuration initialization
5023 config = config || {};
5024
5025 // Parent constructor
5026 OO.ui.mixin.GroupElement.call( this, config );
5027
5028 // Properties
5029 this.orientation = config.orientation || 'vertical';
5030 this.dragItem = null;
5031 this.itemDragOver = null;
5032 this.itemKeys = {};
5033 this.sideInsertion = '';
5034
5035 // Events
5036 this.aggregate( {
5037 dragstart: 'itemDragStart',
5038 dragend: 'itemDragEnd',
5039 drop: 'itemDrop'
5040 } );
5041 this.connect( this, {
5042 itemDragStart: 'onItemDragStart',
5043 itemDrop: 'onItemDrop',
5044 itemDragEnd: 'onItemDragEnd'
5045 } );
5046 this.$element.on( {
5047 dragover: this.onDragOver.bind( this ),
5048 dragleave: this.onDragLeave.bind( this )
5049 } );
5050
5051 // Initialize
5052 if ( Array.isArray( config.items ) ) {
5053 this.addItems( config.items );
5054 }
5055 this.$placeholder = $( '<div>' )
5056 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5057 this.$element
5058 .addClass( 'oo-ui-draggableGroupElement' )
5059 .append( this.$status )
5060 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
5061 .prepend( this.$placeholder );
5062 };
5063
5064 /* Setup */
5065 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
5066
5067 /* Events */
5068
5069 /**
5070 * A 'reorder' event is emitted when the order of items in the group changes.
5071 *
5072 * @event reorder
5073 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5074 * @param {number} [newIndex] New index for the item
5075 */
5076
5077 /* Methods */
5078
5079 /**
5080 * Respond to item drag start event
5081 *
5082 * @private
5083 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5084 */
5085 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
5086 var i, len;
5087
5088 // Map the index of each object
5089 for ( i = 0, len = this.items.length; i < len; i++ ) {
5090 this.items[ i ].setIndex( i );
5091 }
5092
5093 if ( this.orientation === 'horizontal' ) {
5094 // Set the height of the indicator
5095 this.$placeholder.css( {
5096 height: item.$element.outerHeight(),
5097 width: 2
5098 } );
5099 } else {
5100 // Set the width of the indicator
5101 this.$placeholder.css( {
5102 height: 2,
5103 width: item.$element.outerWidth()
5104 } );
5105 }
5106 this.setDragItem( item );
5107 };
5108
5109 /**
5110 * Respond to item drag end event
5111 *
5112 * @private
5113 */
5114 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragEnd = function () {
5115 this.unsetDragItem();
5116 return false;
5117 };
5118
5119 /**
5120 * Handle drop event and switch the order of the items accordingly
5121 *
5122 * @private
5123 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5124 * @fires reorder
5125 */
5126 OO.ui.mixin.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
5127 var toIndex = item.getIndex();
5128 // Check if the dropped item is from the current group
5129 // TODO: Figure out a way to configure a list of legally droppable
5130 // elements even if they are not yet in the list
5131 if ( this.getDragItem() ) {
5132 // If the insertion point is 'after', the insertion index
5133 // is shifted to the right (or to the left in RTL, hence 'after')
5134 if ( this.sideInsertion === 'after' ) {
5135 toIndex++;
5136 }
5137 // Emit change event
5138 this.emit( 'reorder', this.getDragItem(), toIndex );
5139 }
5140 this.unsetDragItem();
5141 // Return false to prevent propogation
5142 return false;
5143 };
5144
5145 /**
5146 * Handle dragleave event.
5147 *
5148 * @private
5149 */
5150 OO.ui.mixin.DraggableGroupElement.prototype.onDragLeave = function () {
5151 // This means the item was dragged outside the widget
5152 this.$placeholder
5153 .css( 'left', 0 )
5154 .addClass( 'oo-ui-element-hidden' );
5155 };
5156
5157 /**
5158 * Respond to dragover event
5159 *
5160 * @private
5161 * @param {jQuery.Event} event Event details
5162 */
5163 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
5164 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
5165 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
5166 clientX = e.originalEvent.clientX,
5167 clientY = e.originalEvent.clientY;
5168
5169 // Get the OptionWidget item we are dragging over
5170 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
5171 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
5172 if ( $optionWidget[ 0 ] ) {
5173 itemOffset = $optionWidget.offset();
5174 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
5175 itemPosition = $optionWidget.position();
5176 itemIndex = $optionWidget.data( 'index' );
5177 }
5178
5179 if (
5180 itemOffset &&
5181 this.isDragging() &&
5182 itemIndex !== this.getDragItem().getIndex()
5183 ) {
5184 if ( this.orientation === 'horizontal' ) {
5185 // Calculate where the mouse is relative to the item width
5186 itemSize = itemBoundingRect.width;
5187 itemMidpoint = itemBoundingRect.left + itemSize / 2;
5188 dragPosition = clientX;
5189 // Which side of the item we hover over will dictate
5190 // where the placeholder will appear, on the left or
5191 // on the right
5192 cssOutput = {
5193 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
5194 top: itemPosition.top
5195 };
5196 } else {
5197 // Calculate where the mouse is relative to the item height
5198 itemSize = itemBoundingRect.height;
5199 itemMidpoint = itemBoundingRect.top + itemSize / 2;
5200 dragPosition = clientY;
5201 // Which side of the item we hover over will dictate
5202 // where the placeholder will appear, on the top or
5203 // on the bottom
5204 cssOutput = {
5205 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
5206 left: itemPosition.left
5207 };
5208 }
5209 // Store whether we are before or after an item to rearrange
5210 // For horizontal layout, we need to account for RTL, as this is flipped
5211 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
5212 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
5213 } else {
5214 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
5215 }
5216 // Add drop indicator between objects
5217 this.$placeholder
5218 .css( cssOutput )
5219 .removeClass( 'oo-ui-element-hidden' );
5220 } else {
5221 // This means the item was dragged outside the widget
5222 this.$placeholder
5223 .css( 'left', 0 )
5224 .addClass( 'oo-ui-element-hidden' );
5225 }
5226 // Prevent default
5227 e.preventDefault();
5228 };
5229
5230 /**
5231 * Set a dragged item
5232 *
5233 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5234 */
5235 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
5236 this.dragItem = item;
5237 };
5238
5239 /**
5240 * Unset the current dragged item
5241 */
5242 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
5243 this.dragItem = null;
5244 this.itemDragOver = null;
5245 this.$placeholder.addClass( 'oo-ui-element-hidden' );
5246 this.sideInsertion = '';
5247 };
5248
5249 /**
5250 * Get the item that is currently being dragged.
5251 *
5252 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5253 */
5254 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
5255 return this.dragItem;
5256 };
5257
5258 /**
5259 * Check if an item in the group is currently being dragged.
5260 *
5261 * @return {Boolean} Item is being dragged
5262 */
5263 OO.ui.mixin.DraggableGroupElement.prototype.isDragging = function () {
5264 return this.getDragItem() !== null;
5265 };
5266
5267 /**
5268 * IconElement is often mixed into other classes to generate an icon.
5269 * Icons are graphics, about the size of normal text. They are used to aid the user
5270 * in locating a control or to convey information in a space-efficient way. See the
5271 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5272 * included in the library.
5273 *
5274 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5275 *
5276 * @abstract
5277 * @class
5278 *
5279 * @constructor
5280 * @param {Object} [config] Configuration options
5281 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5282 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5283 * the icon element be set to an existing icon instead of the one generated by this class, set a
5284 * value using a jQuery selection. For example:
5285 *
5286 * // Use a <div> tag instead of a <span>
5287 * $icon: $("<div>")
5288 * // Use an existing icon element instead of the one generated by the class
5289 * $icon: this.$element
5290 * // Use an icon element from a child widget
5291 * $icon: this.childwidget.$element
5292 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5293 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5294 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5295 * by the user's language.
5296 *
5297 * Example of an i18n map:
5298 *
5299 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5300 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5301 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5302 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5303 * text. The icon title is displayed when users move the mouse over the icon.
5304 */
5305 OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) {
5306 // Configuration initialization
5307 config = config || {};
5308
5309 // Properties
5310 this.$icon = null;
5311 this.icon = null;
5312 this.iconTitle = null;
5313
5314 // Initialization
5315 this.setIcon( config.icon || this.constructor.static.icon );
5316 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5317 this.setIconElement( config.$icon || $( '<span>' ) );
5318 };
5319
5320 /* Setup */
5321
5322 OO.initClass( OO.ui.mixin.IconElement );
5323
5324 /* Static Properties */
5325
5326 /**
5327 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5328 * for i18n purposes and contains a `default` icon name and additional names keyed by
5329 * language code. The `default` name is used when no icon is keyed by the user's language.
5330 *
5331 * Example of an i18n map:
5332 *
5333 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5334 *
5335 * Note: the static property will be overridden if the #icon configuration is used.
5336 *
5337 * @static
5338 * @inheritable
5339 * @property {Object|string}
5340 */
5341 OO.ui.mixin.IconElement.static.icon = null;
5342
5343 /**
5344 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5345 * function that returns title text, or `null` for no title.
5346 *
5347 * The static property will be overridden if the #iconTitle configuration is used.
5348 *
5349 * @static
5350 * @inheritable
5351 * @property {string|Function|null}
5352 */
5353 OO.ui.mixin.IconElement.static.iconTitle = null;
5354
5355 /* Methods */
5356
5357 /**
5358 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5359 * applies to the specified icon element instead of the one created by the class. If an icon
5360 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5361 * and mixin methods will no longer affect the element.
5362 *
5363 * @param {jQuery} $icon Element to use as icon
5364 */
5365 OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) {
5366 if ( this.$icon ) {
5367 this.$icon
5368 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5369 .removeAttr( 'title' );
5370 }
5371
5372 this.$icon = $icon
5373 .addClass( 'oo-ui-iconElement-icon' )
5374 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5375 if ( this.iconTitle !== null ) {
5376 this.$icon.attr( 'title', this.iconTitle );
5377 }
5378
5379 this.updateThemeClasses();
5380 };
5381
5382 /**
5383 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5384 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5385 * for an example.
5386 *
5387 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5388 * by language code, or `null` to remove the icon.
5389 * @chainable
5390 */
5391 OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) {
5392 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5393 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5394
5395 if ( this.icon !== icon ) {
5396 if ( this.$icon ) {
5397 if ( this.icon !== null ) {
5398 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5399 }
5400 if ( icon !== null ) {
5401 this.$icon.addClass( 'oo-ui-icon-' + icon );
5402 }
5403 }
5404 this.icon = icon;
5405 }
5406
5407 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5408 this.updateThemeClasses();
5409
5410 return this;
5411 };
5412
5413 /**
5414 * Set the icon title. Use `null` to remove the title.
5415 *
5416 * @param {string|Function|null} iconTitle A text string used as the icon title,
5417 * a function that returns title text, or `null` for no title.
5418 * @chainable
5419 */
5420 OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5421 iconTitle = typeof iconTitle === 'function' ||
5422 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5423 OO.ui.resolveMsg( iconTitle ) : null;
5424
5425 if ( this.iconTitle !== iconTitle ) {
5426 this.iconTitle = iconTitle;
5427 if ( this.$icon ) {
5428 if ( this.iconTitle !== null ) {
5429 this.$icon.attr( 'title', iconTitle );
5430 } else {
5431 this.$icon.removeAttr( 'title' );
5432 }
5433 }
5434 }
5435
5436 return this;
5437 };
5438
5439 /**
5440 * Get the symbolic name of the icon.
5441 *
5442 * @return {string} Icon name
5443 */
5444 OO.ui.mixin.IconElement.prototype.getIcon = function () {
5445 return this.icon;
5446 };
5447
5448 /**
5449 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5450 *
5451 * @return {string} Icon title text
5452 */
5453 OO.ui.mixin.IconElement.prototype.getIconTitle = function () {
5454 return this.iconTitle;
5455 };
5456
5457 /**
5458 * IndicatorElement is often mixed into other classes to generate an indicator.
5459 * Indicators are small graphics that are generally used in two ways:
5460 *
5461 * - To draw attention to the status of an item. For example, an indicator might be
5462 * used to show that an item in a list has errors that need to be resolved.
5463 * - To clarify the function of a control that acts in an exceptional way (a button
5464 * that opens a menu instead of performing an action directly, for example).
5465 *
5466 * For a list of indicators included in the library, please see the
5467 * [OOjs UI documentation on MediaWiki] [1].
5468 *
5469 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5470 *
5471 * @abstract
5472 * @class
5473 *
5474 * @constructor
5475 * @param {Object} [config] Configuration options
5476 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5477 * configuration is omitted, the indicator element will use a generated `<span>`.
5478 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5479 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5480 * in the library.
5481 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5482 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5483 * or a function that returns title text. The indicator title is displayed when users move
5484 * the mouse over the indicator.
5485 */
5486 OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) {
5487 // Configuration initialization
5488 config = config || {};
5489
5490 // Properties
5491 this.$indicator = null;
5492 this.indicator = null;
5493 this.indicatorTitle = null;
5494
5495 // Initialization
5496 this.setIndicator( config.indicator || this.constructor.static.indicator );
5497 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5498 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5499 };
5500
5501 /* Setup */
5502
5503 OO.initClass( OO.ui.mixin.IndicatorElement );
5504
5505 /* Static Properties */
5506
5507 /**
5508 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5509 * The static property will be overridden if the #indicator configuration is used.
5510 *
5511 * @static
5512 * @inheritable
5513 * @property {string|null}
5514 */
5515 OO.ui.mixin.IndicatorElement.static.indicator = null;
5516
5517 /**
5518 * A text string used as the indicator title, a function that returns title text, or `null`
5519 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5520 *
5521 * @static
5522 * @inheritable
5523 * @property {string|Function|null}
5524 */
5525 OO.ui.mixin.IndicatorElement.static.indicatorTitle = null;
5526
5527 /* Methods */
5528
5529 /**
5530 * Set the indicator element.
5531 *
5532 * If an element is already set, it will be cleaned up before setting up the new element.
5533 *
5534 * @param {jQuery} $indicator Element to use as indicator
5535 */
5536 OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5537 if ( this.$indicator ) {
5538 this.$indicator
5539 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5540 .removeAttr( 'title' );
5541 }
5542
5543 this.$indicator = $indicator
5544 .addClass( 'oo-ui-indicatorElement-indicator' )
5545 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5546 if ( this.indicatorTitle !== null ) {
5547 this.$indicator.attr( 'title', this.indicatorTitle );
5548 }
5549
5550 this.updateThemeClasses();
5551 };
5552
5553 /**
5554 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5555 *
5556 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5557 * @chainable
5558 */
5559 OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5560 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5561
5562 if ( this.indicator !== indicator ) {
5563 if ( this.$indicator ) {
5564 if ( this.indicator !== null ) {
5565 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5566 }
5567 if ( indicator !== null ) {
5568 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5569 }
5570 }
5571 this.indicator = indicator;
5572 }
5573
5574 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5575 this.updateThemeClasses();
5576
5577 return this;
5578 };
5579
5580 /**
5581 * Set the indicator title.
5582 *
5583 * The title is displayed when a user moves the mouse over the indicator.
5584 *
5585 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5586 * `null` for no indicator title
5587 * @chainable
5588 */
5589 OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5590 indicatorTitle = typeof indicatorTitle === 'function' ||
5591 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5592 OO.ui.resolveMsg( indicatorTitle ) : null;
5593
5594 if ( this.indicatorTitle !== indicatorTitle ) {
5595 this.indicatorTitle = indicatorTitle;
5596 if ( this.$indicator ) {
5597 if ( this.indicatorTitle !== null ) {
5598 this.$indicator.attr( 'title', indicatorTitle );
5599 } else {
5600 this.$indicator.removeAttr( 'title' );
5601 }
5602 }
5603 }
5604
5605 return this;
5606 };
5607
5608 /**
5609 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5610 *
5611 * @return {string} Symbolic name of indicator
5612 */
5613 OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () {
5614 return this.indicator;
5615 };
5616
5617 /**
5618 * Get the indicator title.
5619 *
5620 * The title is displayed when a user moves the mouse over the indicator.
5621 *
5622 * @return {string} Indicator title text
5623 */
5624 OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () {
5625 return this.indicatorTitle;
5626 };
5627
5628 /**
5629 * LabelElement is often mixed into other classes to generate a label, which
5630 * helps identify the function of an interface element.
5631 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5632 *
5633 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5634 *
5635 * @abstract
5636 * @class
5637 *
5638 * @constructor
5639 * @param {Object} [config] Configuration options
5640 * @cfg {jQuery} [$label] The label element created by the class. If this
5641 * configuration is omitted, the label element will use a generated `<span>`.
5642 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5643 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5644 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5645 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5646 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5647 * The label will be truncated to fit if necessary.
5648 */
5649 OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) {
5650 // Configuration initialization
5651 config = config || {};
5652
5653 // Properties
5654 this.$label = null;
5655 this.label = null;
5656 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5657
5658 // Initialization
5659 this.setLabel( config.label || this.constructor.static.label );
5660 this.setLabelElement( config.$label || $( '<span>' ) );
5661 };
5662
5663 /* Setup */
5664
5665 OO.initClass( OO.ui.mixin.LabelElement );
5666
5667 /* Events */
5668
5669 /**
5670 * @event labelChange
5671 * @param {string} value
5672 */
5673
5674 /* Static Properties */
5675
5676 /**
5677 * The label text. The label can be specified as a plaintext string, a function that will
5678 * produce a string in the future, or `null` for no label. The static value will
5679 * be overridden if a label is specified with the #label config option.
5680 *
5681 * @static
5682 * @inheritable
5683 * @property {string|Function|null}
5684 */
5685 OO.ui.mixin.LabelElement.static.label = null;
5686
5687 /* Methods */
5688
5689 /**
5690 * Set the label element.
5691 *
5692 * If an element is already set, it will be cleaned up before setting up the new element.
5693 *
5694 * @param {jQuery} $label Element to use as label
5695 */
5696 OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) {
5697 if ( this.$label ) {
5698 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5699 }
5700
5701 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5702 this.setLabelContent( this.label );
5703 };
5704
5705 /**
5706 * Set the label.
5707 *
5708 * An empty string will result in the label being hidden. A string containing only whitespace will
5709 * be converted to a single `&nbsp;`.
5710 *
5711 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5712 * text; or null for no label
5713 * @chainable
5714 */
5715 OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) {
5716 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5717 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5718
5719 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5720
5721 if ( this.label !== label ) {
5722 if ( this.$label ) {
5723 this.setLabelContent( label );
5724 }
5725 this.label = label;
5726 this.emit( 'labelChange' );
5727 }
5728
5729 return this;
5730 };
5731
5732 /**
5733 * Get the label.
5734 *
5735 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5736 * text; or null for no label
5737 */
5738 OO.ui.mixin.LabelElement.prototype.getLabel = function () {
5739 return this.label;
5740 };
5741
5742 /**
5743 * Fit the label.
5744 *
5745 * @chainable
5746 */
5747 OO.ui.mixin.LabelElement.prototype.fitLabel = function () {
5748 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5749 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5750 }
5751
5752 return this;
5753 };
5754
5755 /**
5756 * Set the content of the label.
5757 *
5758 * Do not call this method until after the label element has been set by #setLabelElement.
5759 *
5760 * @private
5761 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5762 * text; or null for no label
5763 */
5764 OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) {
5765 if ( typeof label === 'string' ) {
5766 if ( label.match( /^\s*$/ ) ) {
5767 // Convert whitespace only string to a single non-breaking space
5768 this.$label.html( '&nbsp;' );
5769 } else {
5770 this.$label.text( label );
5771 }
5772 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5773 this.$label.html( label.toString() );
5774 } else if ( label instanceof jQuery ) {
5775 this.$label.empty().append( label );
5776 } else {
5777 this.$label.empty();
5778 }
5779 };
5780
5781 /**
5782 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5783 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5784 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5785 * from the lookup menu, that value becomes the value of the input field.
5786 *
5787 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5788 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5789 * re-enable lookups.
5790 *
5791 * See the [OOjs UI demos][1] for an example.
5792 *
5793 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5794 *
5795 * @class
5796 * @abstract
5797 *
5798 * @constructor
5799 * @param {Object} [config] Configuration options
5800 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5801 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5802 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5803 * By default, the lookup menu is not generated and displayed until the user begins to type.
5804 */
5805 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
5806 // Configuration initialization
5807 config = config || {};
5808
5809 // Properties
5810 this.$overlay = config.$overlay || this.$element;
5811 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
5812 widget: this,
5813 input: this,
5814 $container: config.$container || this.$element
5815 } );
5816
5817 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5818
5819 this.lookupCache = {};
5820 this.lookupQuery = null;
5821 this.lookupRequest = null;
5822 this.lookupsDisabled = false;
5823 this.lookupInputFocused = false;
5824
5825 // Events
5826 this.$input.on( {
5827 focus: this.onLookupInputFocus.bind( this ),
5828 blur: this.onLookupInputBlur.bind( this ),
5829 mousedown: this.onLookupInputMouseDown.bind( this )
5830 } );
5831 this.connect( this, { change: 'onLookupInputChange' } );
5832 this.lookupMenu.connect( this, {
5833 toggle: 'onLookupMenuToggle',
5834 choose: 'onLookupMenuItemChoose'
5835 } );
5836
5837 // Initialization
5838 this.$element.addClass( 'oo-ui-lookupElement' );
5839 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5840 this.$overlay.append( this.lookupMenu.$element );
5841 };
5842
5843 /* Methods */
5844
5845 /**
5846 * Handle input focus event.
5847 *
5848 * @protected
5849 * @param {jQuery.Event} e Input focus event
5850 */
5851 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
5852 this.lookupInputFocused = true;
5853 this.populateLookupMenu();
5854 };
5855
5856 /**
5857 * Handle input blur event.
5858 *
5859 * @protected
5860 * @param {jQuery.Event} e Input blur event
5861 */
5862 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
5863 this.closeLookupMenu();
5864 this.lookupInputFocused = false;
5865 };
5866
5867 /**
5868 * Handle input mouse down event.
5869 *
5870 * @protected
5871 * @param {jQuery.Event} e Input mouse down event
5872 */
5873 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
5874 // Only open the menu if the input was already focused.
5875 // This way we allow the user to open the menu again after closing it with Esc
5876 // by clicking in the input. Opening (and populating) the menu when initially
5877 // clicking into the input is handled by the focus handler.
5878 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5879 this.populateLookupMenu();
5880 }
5881 };
5882
5883 /**
5884 * Handle input change event.
5885 *
5886 * @protected
5887 * @param {string} value New input value
5888 */
5889 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
5890 if ( this.lookupInputFocused ) {
5891 this.populateLookupMenu();
5892 }
5893 };
5894
5895 /**
5896 * Handle the lookup menu being shown/hidden.
5897 *
5898 * @protected
5899 * @param {boolean} visible Whether the lookup menu is now visible.
5900 */
5901 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5902 if ( !visible ) {
5903 // When the menu is hidden, abort any active request and clear the menu.
5904 // This has to be done here in addition to closeLookupMenu(), because
5905 // MenuSelectWidget will close itself when the user presses Esc.
5906 this.abortLookupRequest();
5907 this.lookupMenu.clearItems();
5908 }
5909 };
5910
5911 /**
5912 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5913 *
5914 * @protected
5915 * @param {OO.ui.MenuOptionWidget} item Selected item
5916 */
5917 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5918 this.setValue( item.getData() );
5919 };
5920
5921 /**
5922 * Get lookup menu.
5923 *
5924 * @private
5925 * @return {OO.ui.FloatingMenuSelectWidget}
5926 */
5927 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
5928 return this.lookupMenu;
5929 };
5930
5931 /**
5932 * Disable or re-enable lookups.
5933 *
5934 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5935 *
5936 * @param {boolean} disabled Disable lookups
5937 */
5938 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5939 this.lookupsDisabled = !!disabled;
5940 };
5941
5942 /**
5943 * Open the menu. If there are no entries in the menu, this does nothing.
5944 *
5945 * @private
5946 * @chainable
5947 */
5948 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
5949 if ( !this.lookupMenu.isEmpty() ) {
5950 this.lookupMenu.toggle( true );
5951 }
5952 return this;
5953 };
5954
5955 /**
5956 * Close the menu, empty it, and abort any pending request.
5957 *
5958 * @private
5959 * @chainable
5960 */
5961 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
5962 this.lookupMenu.toggle( false );
5963 this.abortLookupRequest();
5964 this.lookupMenu.clearItems();
5965 return this;
5966 };
5967
5968 /**
5969 * Request menu items based on the input's current value, and when they arrive,
5970 * populate the menu with these items and show the menu.
5971 *
5972 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5973 *
5974 * @private
5975 * @chainable
5976 */
5977 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
5978 var widget = this,
5979 value = this.getValue();
5980
5981 if ( this.lookupsDisabled || this.isReadOnly() ) {
5982 return;
5983 }
5984
5985 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5986 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5987 this.closeLookupMenu();
5988 // Skip population if there is already a request pending for the current value
5989 } else if ( value !== this.lookupQuery ) {
5990 this.getLookupMenuItems()
5991 .done( function ( items ) {
5992 widget.lookupMenu.clearItems();
5993 if ( items.length ) {
5994 widget.lookupMenu
5995 .addItems( items )
5996 .toggle( true );
5997 widget.initializeLookupMenuSelection();
5998 } else {
5999 widget.lookupMenu.toggle( false );
6000 }
6001 } )
6002 .fail( function () {
6003 widget.lookupMenu.clearItems();
6004 } );
6005 }
6006
6007 return this;
6008 };
6009
6010 /**
6011 * Highlight the first selectable item in the menu.
6012 *
6013 * @private
6014 * @chainable
6015 */
6016 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
6017 if ( !this.lookupMenu.getSelectedItem() ) {
6018 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
6019 }
6020 };
6021
6022 /**
6023 * Get lookup menu items for the current query.
6024 *
6025 * @private
6026 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6027 * the done event. If the request was aborted to make way for a subsequent request, this promise
6028 * will not be rejected: it will remain pending forever.
6029 */
6030 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
6031 var widget = this,
6032 value = this.getValue(),
6033 deferred = $.Deferred(),
6034 ourRequest;
6035
6036 this.abortLookupRequest();
6037 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
6038 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
6039 } else {
6040 this.pushPending();
6041 this.lookupQuery = value;
6042 ourRequest = this.lookupRequest = this.getLookupRequest();
6043 ourRequest
6044 .always( function () {
6045 // We need to pop pending even if this is an old request, otherwise
6046 // the widget will remain pending forever.
6047 // TODO: this assumes that an aborted request will fail or succeed soon after
6048 // being aborted, or at least eventually. It would be nice if we could popPending()
6049 // at abort time, but only if we knew that we hadn't already called popPending()
6050 // for that request.
6051 widget.popPending();
6052 } )
6053 .done( function ( response ) {
6054 // If this is an old request (and aborting it somehow caused it to still succeed),
6055 // ignore its success completely
6056 if ( ourRequest === widget.lookupRequest ) {
6057 widget.lookupQuery = null;
6058 widget.lookupRequest = null;
6059 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
6060 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
6061 }
6062 } )
6063 .fail( function () {
6064 // If this is an old request (or a request failing because it's being aborted),
6065 // ignore its failure completely
6066 if ( ourRequest === widget.lookupRequest ) {
6067 widget.lookupQuery = null;
6068 widget.lookupRequest = null;
6069 deferred.reject();
6070 }
6071 } );
6072 }
6073 return deferred.promise();
6074 };
6075
6076 /**
6077 * Abort the currently pending lookup request, if any.
6078 *
6079 * @private
6080 */
6081 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
6082 var oldRequest = this.lookupRequest;
6083 if ( oldRequest ) {
6084 // First unset this.lookupRequest to the fail handler will notice
6085 // that the request is no longer current
6086 this.lookupRequest = null;
6087 this.lookupQuery = null;
6088 oldRequest.abort();
6089 }
6090 };
6091
6092 /**
6093 * Get a new request object of the current lookup query value.
6094 *
6095 * @protected
6096 * @abstract
6097 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6098 */
6099 OO.ui.mixin.LookupElement.prototype.getLookupRequest = function () {
6100 // Stub, implemented in subclass
6101 return null;
6102 };
6103
6104 /**
6105 * Pre-process data returned by the request from #getLookupRequest.
6106 *
6107 * The return value of this function will be cached, and any further queries for the given value
6108 * will use the cache rather than doing API requests.
6109 *
6110 * @protected
6111 * @abstract
6112 * @param {Mixed} response Response from server
6113 * @return {Mixed} Cached result data
6114 */
6115 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
6116 // Stub, implemented in subclass
6117 return [];
6118 };
6119
6120 /**
6121 * Get a list of menu option widgets from the (possibly cached) data returned by
6122 * #getLookupCacheDataFromResponse.
6123 *
6124 * @protected
6125 * @abstract
6126 * @param {Mixed} data Cached result data, usually an array
6127 * @return {OO.ui.MenuOptionWidget[]} Menu items
6128 */
6129 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
6130 // Stub, implemented in subclass
6131 return [];
6132 };
6133
6134 /**
6135 * Set the read-only state of the widget.
6136 *
6137 * This will also disable/enable the lookups functionality.
6138 *
6139 * @param {boolean} readOnly Make input read-only
6140 * @chainable
6141 */
6142 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
6143 // Parent method
6144 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6145 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
6146
6147 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6148 if ( this.isReadOnly() && this.lookupMenu ) {
6149 this.closeLookupMenu();
6150 }
6151
6152 return this;
6153 };
6154
6155 /**
6156 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6157 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6158 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6159 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6160 *
6161 * @abstract
6162 * @class
6163 *
6164 * @constructor
6165 * @param {Object} [config] Configuration options
6166 * @cfg {Object} [popup] Configuration to pass to popup
6167 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6168 */
6169 OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) {
6170 // Configuration initialization
6171 config = config || {};
6172
6173 // Properties
6174 this.popup = new OO.ui.PopupWidget( $.extend(
6175 { autoClose: true },
6176 config.popup,
6177 { $autoCloseIgnore: this.$element }
6178 ) );
6179 };
6180
6181 /* Methods */
6182
6183 /**
6184 * Get popup.
6185 *
6186 * @return {OO.ui.PopupWidget} Popup widget
6187 */
6188 OO.ui.mixin.PopupElement.prototype.getPopup = function () {
6189 return this.popup;
6190 };
6191
6192 /**
6193 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6194 * additional functionality to an element created by another class. The class provides
6195 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6196 * which are used to customize the look and feel of a widget to better describe its
6197 * importance and functionality.
6198 *
6199 * The library currently contains the following styling flags for general use:
6200 *
6201 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6202 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6203 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6204 *
6205 * The flags affect the appearance of the buttons:
6206 *
6207 * @example
6208 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6209 * var button1 = new OO.ui.ButtonWidget( {
6210 * label: 'Constructive',
6211 * flags: 'constructive'
6212 * } );
6213 * var button2 = new OO.ui.ButtonWidget( {
6214 * label: 'Destructive',
6215 * flags: 'destructive'
6216 * } );
6217 * var button3 = new OO.ui.ButtonWidget( {
6218 * label: 'Progressive',
6219 * flags: 'progressive'
6220 * } );
6221 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6222 *
6223 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6224 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6225 *
6226 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6227 *
6228 * @abstract
6229 * @class
6230 *
6231 * @constructor
6232 * @param {Object} [config] Configuration options
6233 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6234 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6235 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6236 * @cfg {jQuery} [$flagged] The flagged element. By default,
6237 * the flagged functionality is applied to the element created by the class ($element).
6238 * If a different element is specified, the flagged functionality will be applied to it instead.
6239 */
6240 OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) {
6241 // Configuration initialization
6242 config = config || {};
6243
6244 // Properties
6245 this.flags = {};
6246 this.$flagged = null;
6247
6248 // Initialization
6249 this.setFlags( config.flags );
6250 this.setFlaggedElement( config.$flagged || this.$element );
6251 };
6252
6253 /* Events */
6254
6255 /**
6256 * @event flag
6257 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6258 * parameter contains the name of each modified flag and indicates whether it was
6259 * added or removed.
6260 *
6261 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6262 * that the flag was added, `false` that the flag was removed.
6263 */
6264
6265 /* Methods */
6266
6267 /**
6268 * Set the flagged element.
6269 *
6270 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6271 * If an element is already set, the method will remove the mixin’s effect on that element.
6272 *
6273 * @param {jQuery} $flagged Element that should be flagged
6274 */
6275 OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
6276 var classNames = Object.keys( this.flags ).map( function ( flag ) {
6277 return 'oo-ui-flaggedElement-' + flag;
6278 } ).join( ' ' );
6279
6280 if ( this.$flagged ) {
6281 this.$flagged.removeClass( classNames );
6282 }
6283
6284 this.$flagged = $flagged.addClass( classNames );
6285 };
6286
6287 /**
6288 * Check if the specified flag is set.
6289 *
6290 * @param {string} flag Name of flag
6291 * @return {boolean} The flag is set
6292 */
6293 OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) {
6294 // This may be called before the constructor, thus before this.flags is set
6295 return this.flags && ( flag in this.flags );
6296 };
6297
6298 /**
6299 * Get the names of all flags set.
6300 *
6301 * @return {string[]} Flag names
6302 */
6303 OO.ui.mixin.FlaggedElement.prototype.getFlags = function () {
6304 // This may be called before the constructor, thus before this.flags is set
6305 return Object.keys( this.flags || {} );
6306 };
6307
6308 /**
6309 * Clear all flags.
6310 *
6311 * @chainable
6312 * @fires flag
6313 */
6314 OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () {
6315 var flag, className,
6316 changes = {},
6317 remove = [],
6318 classPrefix = 'oo-ui-flaggedElement-';
6319
6320 for ( flag in this.flags ) {
6321 className = classPrefix + flag;
6322 changes[ flag ] = false;
6323 delete this.flags[ flag ];
6324 remove.push( className );
6325 }
6326
6327 if ( this.$flagged ) {
6328 this.$flagged.removeClass( remove.join( ' ' ) );
6329 }
6330
6331 this.updateThemeClasses();
6332 this.emit( 'flag', changes );
6333
6334 return this;
6335 };
6336
6337 /**
6338 * Add one or more flags.
6339 *
6340 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6341 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6342 * be added (`true`) or removed (`false`).
6343 * @chainable
6344 * @fires flag
6345 */
6346 OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) {
6347 var i, len, flag, className,
6348 changes = {},
6349 add = [],
6350 remove = [],
6351 classPrefix = 'oo-ui-flaggedElement-';
6352
6353 if ( typeof flags === 'string' ) {
6354 className = classPrefix + flags;
6355 // Set
6356 if ( !this.flags[ flags ] ) {
6357 this.flags[ flags ] = true;
6358 add.push( className );
6359 }
6360 } else if ( Array.isArray( flags ) ) {
6361 for ( i = 0, len = flags.length; i < len; i++ ) {
6362 flag = flags[ i ];
6363 className = classPrefix + flag;
6364 // Set
6365 if ( !this.flags[ flag ] ) {
6366 changes[ flag ] = true;
6367 this.flags[ flag ] = true;
6368 add.push( className );
6369 }
6370 }
6371 } else if ( OO.isPlainObject( flags ) ) {
6372 for ( flag in flags ) {
6373 className = classPrefix + flag;
6374 if ( flags[ flag ] ) {
6375 // Set
6376 if ( !this.flags[ flag ] ) {
6377 changes[ flag ] = true;
6378 this.flags[ flag ] = true;
6379 add.push( className );
6380 }
6381 } else {
6382 // Remove
6383 if ( this.flags[ flag ] ) {
6384 changes[ flag ] = false;
6385 delete this.flags[ flag ];
6386 remove.push( className );
6387 }
6388 }
6389 }
6390 }
6391
6392 if ( this.$flagged ) {
6393 this.$flagged
6394 .addClass( add.join( ' ' ) )
6395 .removeClass( remove.join( ' ' ) );
6396 }
6397
6398 this.updateThemeClasses();
6399 this.emit( 'flag', changes );
6400
6401 return this;
6402 };
6403
6404 /**
6405 * TitledElement is mixed into other classes to provide a `title` attribute.
6406 * Titles are rendered by the browser and are made visible when the user moves
6407 * the mouse over the element. Titles are not visible on touch devices.
6408 *
6409 * @example
6410 * // TitledElement provides a 'title' attribute to the
6411 * // ButtonWidget class
6412 * var button = new OO.ui.ButtonWidget( {
6413 * label: 'Button with Title',
6414 * title: 'I am a button'
6415 * } );
6416 * $( 'body' ).append( button.$element );
6417 *
6418 * @abstract
6419 * @class
6420 *
6421 * @constructor
6422 * @param {Object} [config] Configuration options
6423 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6424 * If this config is omitted, the title functionality is applied to $element, the
6425 * element created by the class.
6426 * @cfg {string|Function} [title] The title text or a function that returns text. If
6427 * this config is omitted, the value of the {@link #static-title static title} property is used.
6428 */
6429 OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) {
6430 // Configuration initialization
6431 config = config || {};
6432
6433 // Properties
6434 this.$titled = null;
6435 this.title = null;
6436
6437 // Initialization
6438 this.setTitle( config.title || this.constructor.static.title );
6439 this.setTitledElement( config.$titled || this.$element );
6440 };
6441
6442 /* Setup */
6443
6444 OO.initClass( OO.ui.mixin.TitledElement );
6445
6446 /* Static Properties */
6447
6448 /**
6449 * The title text, a function that returns text, or `null` for no title. The value of the static property
6450 * is overridden if the #title config option is used.
6451 *
6452 * @static
6453 * @inheritable
6454 * @property {string|Function|null}
6455 */
6456 OO.ui.mixin.TitledElement.static.title = null;
6457
6458 /* Methods */
6459
6460 /**
6461 * Set the titled element.
6462 *
6463 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6464 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6465 *
6466 * @param {jQuery} $titled Element that should use the 'titled' functionality
6467 */
6468 OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) {
6469 if ( this.$titled ) {
6470 this.$titled.removeAttr( 'title' );
6471 }
6472
6473 this.$titled = $titled;
6474 if ( this.title ) {
6475 this.$titled.attr( 'title', this.title );
6476 }
6477 };
6478
6479 /**
6480 * Set title.
6481 *
6482 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6483 * @chainable
6484 */
6485 OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) {
6486 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6487
6488 if ( this.title !== title ) {
6489 if ( this.$titled ) {
6490 if ( title !== null ) {
6491 this.$titled.attr( 'title', title );
6492 } else {
6493 this.$titled.removeAttr( 'title' );
6494 }
6495 }
6496 this.title = title;
6497 }
6498
6499 return this;
6500 };
6501
6502 /**
6503 * Get title.
6504 *
6505 * @return {string} Title string
6506 */
6507 OO.ui.mixin.TitledElement.prototype.getTitle = function () {
6508 return this.title;
6509 };
6510
6511 /**
6512 * Element that can be automatically clipped to visible boundaries.
6513 *
6514 * Whenever the element's natural height changes, you have to call
6515 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6516 * clipping correctly.
6517 *
6518 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6519 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6520 * then #$clippable will be given a fixed reduced height and/or width and will be made
6521 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6522 * but you can build a static footer by setting #$clippableContainer to an element that contains
6523 * #$clippable and the footer.
6524 *
6525 * @abstract
6526 * @class
6527 *
6528 * @constructor
6529 * @param {Object} [config] Configuration options
6530 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6531 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6532 * omit to use #$clippable
6533 */
6534 OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) {
6535 // Configuration initialization
6536 config = config || {};
6537
6538 // Properties
6539 this.$clippable = null;
6540 this.$clippableContainer = null;
6541 this.clipping = false;
6542 this.clippedHorizontally = false;
6543 this.clippedVertically = false;
6544 this.$clippableScrollableContainer = null;
6545 this.$clippableScroller = null;
6546 this.$clippableWindow = null;
6547 this.idealWidth = null;
6548 this.idealHeight = null;
6549 this.onClippableScrollHandler = this.clip.bind( this );
6550 this.onClippableWindowResizeHandler = this.clip.bind( this );
6551
6552 // Initialization
6553 if ( config.$clippableContainer ) {
6554 this.setClippableContainer( config.$clippableContainer );
6555 }
6556 this.setClippableElement( config.$clippable || this.$element );
6557 };
6558
6559 /* Methods */
6560
6561 /**
6562 * Set clippable element.
6563 *
6564 * If an element is already set, it will be cleaned up before setting up the new element.
6565 *
6566 * @param {jQuery} $clippable Element to make clippable
6567 */
6568 OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6569 if ( this.$clippable ) {
6570 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6571 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6572 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6573 }
6574
6575 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6576 this.clip();
6577 };
6578
6579 /**
6580 * Set clippable container.
6581 *
6582 * This is the container that will be measured when deciding whether to clip. When clipping,
6583 * #$clippable will be resized in order to keep the clippable container fully visible.
6584 *
6585 * If the clippable container is unset, #$clippable will be used.
6586 *
6587 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6588 */
6589 OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) {
6590 this.$clippableContainer = $clippableContainer;
6591 if ( this.$clippable ) {
6592 this.clip();
6593 }
6594 };
6595
6596 /**
6597 * Toggle clipping.
6598 *
6599 * Do not turn clipping on until after the element is attached to the DOM and visible.
6600 *
6601 * @param {boolean} [clipping] Enable clipping, omit to toggle
6602 * @chainable
6603 */
6604 OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6605 clipping = clipping === undefined ? !this.clipping : !!clipping;
6606
6607 if ( this.clipping !== clipping ) {
6608 this.clipping = clipping;
6609 if ( clipping ) {
6610 this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() );
6611 // If the clippable container is the root, we have to listen to scroll events and check
6612 // jQuery.scrollTop on the window because of browser inconsistencies
6613 this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ?
6614 $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) :
6615 this.$clippableScrollableContainer;
6616 this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler );
6617 this.$clippableWindow = $( this.getElementWindow() )
6618 .on( 'resize', this.onClippableWindowResizeHandler );
6619 // Initial clip after visible
6620 this.clip();
6621 } else {
6622 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6623 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6624
6625 this.$clippableScrollableContainer = null;
6626 this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler );
6627 this.$clippableScroller = null;
6628 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6629 this.$clippableWindow = null;
6630 }
6631 }
6632
6633 return this;
6634 };
6635
6636 /**
6637 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6638 *
6639 * @return {boolean} Element will be clipped to the visible area
6640 */
6641 OO.ui.mixin.ClippableElement.prototype.isClipping = function () {
6642 return this.clipping;
6643 };
6644
6645 /**
6646 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6647 *
6648 * @return {boolean} Part of the element is being clipped
6649 */
6650 OO.ui.mixin.ClippableElement.prototype.isClipped = function () {
6651 return this.clippedHorizontally || this.clippedVertically;
6652 };
6653
6654 /**
6655 * Check if the right of the element is being clipped by the nearest scrollable container.
6656 *
6657 * @return {boolean} Part of the element is being clipped
6658 */
6659 OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () {
6660 return this.clippedHorizontally;
6661 };
6662
6663 /**
6664 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6665 *
6666 * @return {boolean} Part of the element is being clipped
6667 */
6668 OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () {
6669 return this.clippedVertically;
6670 };
6671
6672 /**
6673 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6674 *
6675 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6676 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6677 */
6678 OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6679 this.idealWidth = width;
6680 this.idealHeight = height;
6681
6682 if ( !this.clipping ) {
6683 // Update dimensions
6684 this.$clippable.css( { width: width, height: height } );
6685 }
6686 // While clipping, idealWidth and idealHeight are not considered
6687 };
6688
6689 /**
6690 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6691 * the element's natural height changes.
6692 *
6693 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6694 * overlapped by, the visible area of the nearest scrollable container.
6695 *
6696 * @chainable
6697 */
6698 OO.ui.mixin.ClippableElement.prototype.clip = function () {
6699 var $container, extraHeight, extraWidth, ccOffset,
6700 $scrollableContainer, scOffset, scHeight, scWidth,
6701 ccWidth, scrollerIsWindow, scrollTop, scrollLeft,
6702 desiredWidth, desiredHeight, allotedWidth, allotedHeight,
6703 naturalWidth, naturalHeight, clipWidth, clipHeight,
6704 buffer = 7; // Chosen by fair dice roll
6705
6706 if ( !this.clipping ) {
6707 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6708 return this;
6709 }
6710
6711 $container = this.$clippableContainer || this.$clippable;
6712 extraHeight = $container.outerHeight() - this.$clippable.outerHeight();
6713 extraWidth = $container.outerWidth() - this.$clippable.outerWidth();
6714 ccOffset = $container.offset();
6715 $scrollableContainer = this.$clippableScrollableContainer.is( 'html, body' ) ?
6716 this.$clippableWindow : this.$clippableScrollableContainer;
6717 scOffset = $scrollableContainer.offset() || { top: 0, left: 0 };
6718 scHeight = $scrollableContainer.innerHeight() - buffer;
6719 scWidth = $scrollableContainer.innerWidth() - buffer;
6720 ccWidth = $container.outerWidth() + buffer;
6721 scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ];
6722 scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0;
6723 scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0;
6724 desiredWidth = ccOffset.left < 0 ?
6725 ccWidth + ccOffset.left :
6726 ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left;
6727 desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top;
6728 allotedWidth = desiredWidth - extraWidth;
6729 allotedHeight = desiredHeight - extraHeight;
6730 naturalWidth = this.$clippable.prop( 'scrollWidth' );
6731 naturalHeight = this.$clippable.prop( 'scrollHeight' );
6732 clipWidth = allotedWidth < naturalWidth;
6733 clipHeight = allotedHeight < naturalHeight;
6734
6735 if ( clipWidth ) {
6736 this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ) } );
6737 } else {
6738 this.$clippable.css( { width: this.idealWidth ? this.idealWidth - extraWidth : '', overflowX: '' } );
6739 }
6740 if ( clipHeight ) {
6741 this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ) } );
6742 } else {
6743 this.$clippable.css( { height: this.idealHeight ? this.idealHeight - extraHeight : '', overflowY: '' } );
6744 }
6745
6746 // If we stopped clipping in at least one of the dimensions
6747 if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) {
6748 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6749 }
6750
6751 this.clippedHorizontally = clipWidth;
6752 this.clippedVertically = clipHeight;
6753
6754 return this;
6755 };
6756
6757 /**
6758 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6759 * Accesskeys allow an user to go to a specific element by using
6760 * a shortcut combination of a browser specific keys + the key
6761 * set to the field.
6762 *
6763 * @example
6764 * // AccessKeyedElement provides an 'accesskey' attribute to the
6765 * // ButtonWidget class
6766 * var button = new OO.ui.ButtonWidget( {
6767 * label: 'Button with Accesskey',
6768 * accessKey: 'k'
6769 * } );
6770 * $( 'body' ).append( button.$element );
6771 *
6772 * @abstract
6773 * @class
6774 *
6775 * @constructor
6776 * @param {Object} [config] Configuration options
6777 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
6778 * If this config is omitted, the accesskey functionality is applied to $element, the
6779 * element created by the class.
6780 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
6781 * this config is omitted, no accesskey will be added.
6782 */
6783 OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) {
6784 // Configuration initialization
6785 config = config || {};
6786
6787 // Properties
6788 this.$accessKeyed = null;
6789 this.accessKey = null;
6790
6791 // Initialization
6792 this.setAccessKey( config.accessKey || null );
6793 this.setAccessKeyedElement( config.$accessKeyed || this.$element );
6794 };
6795
6796 /* Setup */
6797
6798 OO.initClass( OO.ui.mixin.AccessKeyedElement );
6799
6800 /* Static Properties */
6801
6802 /**
6803 * The access key, a function that returns a key, or `null` for no accesskey.
6804 *
6805 * @static
6806 * @inheritable
6807 * @property {string|Function|null}
6808 */
6809 OO.ui.mixin.AccessKeyedElement.static.accessKey = null;
6810
6811 /* Methods */
6812
6813 /**
6814 * Set the accesskeyed element.
6815 *
6816 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
6817 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
6818 *
6819 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
6820 */
6821 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) {
6822 if ( this.$accessKeyed ) {
6823 this.$accessKeyed.removeAttr( 'accesskey' );
6824 }
6825
6826 this.$accessKeyed = $accessKeyed;
6827 if ( this.accessKey ) {
6828 this.$accessKeyed.attr( 'accesskey', this.accessKey );
6829 }
6830 };
6831
6832 /**
6833 * Set accesskey.
6834 *
6835 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
6836 * @chainable
6837 */
6838 OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) {
6839 accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null;
6840
6841 if ( this.accessKey !== accessKey ) {
6842 if ( this.$accessKeyed ) {
6843 if ( accessKey !== null ) {
6844 this.$accessKeyed.attr( 'accesskey', accessKey );
6845 } else {
6846 this.$accessKeyed.removeAttr( 'accesskey' );
6847 }
6848 }
6849 this.accessKey = accessKey;
6850 }
6851
6852 return this;
6853 };
6854
6855 /**
6856 * Get accesskey.
6857 *
6858 * @return {string} accessKey string
6859 */
6860 OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () {
6861 return this.accessKey;
6862 };
6863
6864 /**
6865 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6866 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6867 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6868 * which creates the tools on demand.
6869 *
6870 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6871 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6872 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6873 *
6874 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6875 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6876 *
6877 * @abstract
6878 * @class
6879 * @extends OO.ui.Widget
6880 * @mixins OO.ui.mixin.IconElement
6881 * @mixins OO.ui.mixin.FlaggedElement
6882 * @mixins OO.ui.mixin.TabIndexedElement
6883 *
6884 * @constructor
6885 * @param {OO.ui.ToolGroup} toolGroup
6886 * @param {Object} [config] Configuration options
6887 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6888 * the {@link #static-title static title} property is used.
6889 *
6890 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6891 * 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
6892 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6893 *
6894 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6895 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6896 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6897 */
6898 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6899 // Allow passing positional parameters inside the config object
6900 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6901 config = toolGroup;
6902 toolGroup = config.toolGroup;
6903 }
6904
6905 // Configuration initialization
6906 config = config || {};
6907
6908 // Parent constructor
6909 OO.ui.Tool.parent.call( this, config );
6910
6911 // Properties
6912 this.toolGroup = toolGroup;
6913 this.toolbar = this.toolGroup.getToolbar();
6914 this.active = false;
6915 this.$title = $( '<span>' );
6916 this.$accel = $( '<span>' );
6917 this.$link = $( '<a>' );
6918 this.title = null;
6919
6920 // Mixin constructors
6921 OO.ui.mixin.IconElement.call( this, config );
6922 OO.ui.mixin.FlaggedElement.call( this, config );
6923 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
6924
6925 // Events
6926 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6927
6928 // Initialization
6929 this.$title.addClass( 'oo-ui-tool-title' );
6930 this.$accel
6931 .addClass( 'oo-ui-tool-accel' )
6932 .prop( {
6933 // This may need to be changed if the key names are ever localized,
6934 // but for now they are essentially written in English
6935 dir: 'ltr',
6936 lang: 'en'
6937 } );
6938 this.$link
6939 .addClass( 'oo-ui-tool-link' )
6940 .append( this.$icon, this.$title, this.$accel )
6941 .attr( 'role', 'button' );
6942 this.$element
6943 .data( 'oo-ui-tool', this )
6944 .addClass(
6945 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6946 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6947 )
6948 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
6949 .append( this.$link );
6950 this.setTitle( config.title || this.constructor.static.title );
6951 };
6952
6953 /* Setup */
6954
6955 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6956 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
6957 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
6958 OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
6959
6960 /* Static Properties */
6961
6962 /**
6963 * @static
6964 * @inheritdoc
6965 */
6966 OO.ui.Tool.static.tagName = 'span';
6967
6968 /**
6969 * Symbolic name of tool.
6970 *
6971 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6972 * also be used when adding tools to toolgroups.
6973 *
6974 * @abstract
6975 * @static
6976 * @inheritable
6977 * @property {string}
6978 */
6979 OO.ui.Tool.static.name = '';
6980
6981 /**
6982 * Symbolic name of the group.
6983 *
6984 * The group name is used to associate tools with each other so that they can be selected later by
6985 * a {@link OO.ui.ToolGroup toolgroup}.
6986 *
6987 * @abstract
6988 * @static
6989 * @inheritable
6990 * @property {string}
6991 */
6992 OO.ui.Tool.static.group = '';
6993
6994 /**
6995 * 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.
6996 *
6997 * @abstract
6998 * @static
6999 * @inheritable
7000 * @property {string|Function}
7001 */
7002 OO.ui.Tool.static.title = '';
7003
7004 /**
7005 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7006 * Normally only the icon is displayed, or only the label if no icon is given.
7007 *
7008 * @static
7009 * @inheritable
7010 * @property {boolean}
7011 */
7012 OO.ui.Tool.static.displayBothIconAndLabel = false;
7013
7014 /**
7015 * Add tool to catch-all groups automatically.
7016 *
7017 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7018 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7019 *
7020 * @static
7021 * @inheritable
7022 * @property {boolean}
7023 */
7024 OO.ui.Tool.static.autoAddToCatchall = true;
7025
7026 /**
7027 * Add tool to named groups automatically.
7028 *
7029 * By default, tools that are configured with a static ‘group’ property are added
7030 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7031 * toolgroups include tools by group name).
7032 *
7033 * @static
7034 * @property {boolean}
7035 * @inheritable
7036 */
7037 OO.ui.Tool.static.autoAddToGroup = true;
7038
7039 /**
7040 * Check if this tool is compatible with given data.
7041 *
7042 * This is a stub that can be overriden to provide support for filtering tools based on an
7043 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7044 * must also call this method so that the compatibility check can be performed.
7045 *
7046 * @static
7047 * @inheritable
7048 * @param {Mixed} data Data to check
7049 * @return {boolean} Tool can be used with data
7050 */
7051 OO.ui.Tool.static.isCompatibleWith = function () {
7052 return false;
7053 };
7054
7055 /* Methods */
7056
7057 /**
7058 * Handle the toolbar state being updated.
7059 *
7060 * This is an abstract method that must be overridden in a concrete subclass.
7061 *
7062 * @protected
7063 * @abstract
7064 */
7065 OO.ui.Tool.prototype.onUpdateState = function () {
7066 throw new Error(
7067 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7068 );
7069 };
7070
7071 /**
7072 * Handle the tool being selected.
7073 *
7074 * This is an abstract method that must be overridden in a concrete subclass.
7075 *
7076 * @protected
7077 * @abstract
7078 */
7079 OO.ui.Tool.prototype.onSelect = function () {
7080 throw new Error(
7081 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7082 );
7083 };
7084
7085 /**
7086 * Check if the tool is active.
7087 *
7088 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7089 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7090 *
7091 * @return {boolean} Tool is active
7092 */
7093 OO.ui.Tool.prototype.isActive = function () {
7094 return this.active;
7095 };
7096
7097 /**
7098 * Make the tool appear active or inactive.
7099 *
7100 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7101 * appear pressed or not.
7102 *
7103 * @param {boolean} state Make tool appear active
7104 */
7105 OO.ui.Tool.prototype.setActive = function ( state ) {
7106 this.active = !!state;
7107 if ( this.active ) {
7108 this.$element.addClass( 'oo-ui-tool-active' );
7109 } else {
7110 this.$element.removeClass( 'oo-ui-tool-active' );
7111 }
7112 };
7113
7114 /**
7115 * Set the tool #title.
7116 *
7117 * @param {string|Function} title Title text or a function that returns text
7118 * @chainable
7119 */
7120 OO.ui.Tool.prototype.setTitle = function ( title ) {
7121 this.title = OO.ui.resolveMsg( title );
7122 this.updateTitle();
7123 return this;
7124 };
7125
7126 /**
7127 * Get the tool #title.
7128 *
7129 * @return {string} Title text
7130 */
7131 OO.ui.Tool.prototype.getTitle = function () {
7132 return this.title;
7133 };
7134
7135 /**
7136 * Get the tool's symbolic name.
7137 *
7138 * @return {string} Symbolic name of tool
7139 */
7140 OO.ui.Tool.prototype.getName = function () {
7141 return this.constructor.static.name;
7142 };
7143
7144 /**
7145 * Update the title.
7146 */
7147 OO.ui.Tool.prototype.updateTitle = function () {
7148 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
7149 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
7150 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
7151 tooltipParts = [];
7152
7153 this.$title.text( this.title );
7154 this.$accel.text( accel );
7155
7156 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
7157 tooltipParts.push( this.title );
7158 }
7159 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
7160 tooltipParts.push( accel );
7161 }
7162 if ( tooltipParts.length ) {
7163 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
7164 } else {
7165 this.$link.removeAttr( 'title' );
7166 }
7167 };
7168
7169 /**
7170 * Destroy tool.
7171 *
7172 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7173 * Call this method whenever you are done using a tool.
7174 */
7175 OO.ui.Tool.prototype.destroy = function () {
7176 this.toolbar.disconnect( this );
7177 this.$element.remove();
7178 };
7179
7180 /**
7181 * Toolbars are complex interface components that permit users to easily access a variety
7182 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7183 * part of the toolbar, but not configured as tools.
7184 *
7185 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7186 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7187 * picture’), and an icon.
7188 *
7189 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7190 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7191 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7192 * any order, but each can only appear once in the toolbar.
7193 *
7194 * The following is an example of a basic toolbar.
7195 *
7196 * @example
7197 * // Example of a toolbar
7198 * // Create the toolbar
7199 * var toolFactory = new OO.ui.ToolFactory();
7200 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7201 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7202 *
7203 * // We will be placing status text in this element when tools are used
7204 * var $area = $( '<p>' ).text( 'Toolbar example' );
7205 *
7206 * // Define the tools that we're going to place in our toolbar
7207 *
7208 * // Create a class inheriting from OO.ui.Tool
7209 * function PictureTool() {
7210 * PictureTool.parent.apply( this, arguments );
7211 * }
7212 * OO.inheritClass( PictureTool, OO.ui.Tool );
7213 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7214 * // of 'icon' and 'title' (displayed icon and text).
7215 * PictureTool.static.name = 'picture';
7216 * PictureTool.static.icon = 'picture';
7217 * PictureTool.static.title = 'Insert picture';
7218 * // Defines the action that will happen when this tool is selected (clicked).
7219 * PictureTool.prototype.onSelect = function () {
7220 * $area.text( 'Picture tool clicked!' );
7221 * // Never display this tool as "active" (selected).
7222 * this.setActive( false );
7223 * };
7224 * // Make this tool available in our toolFactory and thus our toolbar
7225 * toolFactory.register( PictureTool );
7226 *
7227 * // Register two more tools, nothing interesting here
7228 * function SettingsTool() {
7229 * SettingsTool.parent.apply( this, arguments );
7230 * }
7231 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7232 * SettingsTool.static.name = 'settings';
7233 * SettingsTool.static.icon = 'settings';
7234 * SettingsTool.static.title = 'Change settings';
7235 * SettingsTool.prototype.onSelect = function () {
7236 * $area.text( 'Settings tool clicked!' );
7237 * this.setActive( false );
7238 * };
7239 * toolFactory.register( SettingsTool );
7240 *
7241 * // Register two more tools, nothing interesting here
7242 * function StuffTool() {
7243 * StuffTool.parent.apply( this, arguments );
7244 * }
7245 * OO.inheritClass( StuffTool, OO.ui.Tool );
7246 * StuffTool.static.name = 'stuff';
7247 * StuffTool.static.icon = 'ellipsis';
7248 * StuffTool.static.title = 'More stuff';
7249 * StuffTool.prototype.onSelect = function () {
7250 * $area.text( 'More stuff tool clicked!' );
7251 * this.setActive( false );
7252 * };
7253 * toolFactory.register( StuffTool );
7254 *
7255 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7256 * // little popup window (a PopupWidget).
7257 * function HelpTool( toolGroup, config ) {
7258 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7259 * padded: true,
7260 * label: 'Help',
7261 * head: true
7262 * } }, config ) );
7263 * this.popup.$body.append( '<p>I am helpful!</p>' );
7264 * }
7265 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7266 * HelpTool.static.name = 'help';
7267 * HelpTool.static.icon = 'help';
7268 * HelpTool.static.title = 'Help';
7269 * toolFactory.register( HelpTool );
7270 *
7271 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7272 * // used once (but not all defined tools must be used).
7273 * toolbar.setup( [
7274 * {
7275 * // 'bar' tool groups display tools' icons only, side-by-side.
7276 * type: 'bar',
7277 * include: [ 'picture', 'help' ]
7278 * },
7279 * {
7280 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7281 * type: 'list',
7282 * indicator: 'down',
7283 * label: 'More',
7284 * include: [ 'settings', 'stuff' ]
7285 * }
7286 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7287 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7288 * // since it's more complicated to use. (See the next example snippet on this page.)
7289 * ] );
7290 *
7291 * // Create some UI around the toolbar and place it in the document
7292 * var frame = new OO.ui.PanelLayout( {
7293 * expanded: false,
7294 * framed: true
7295 * } );
7296 * var contentFrame = new OO.ui.PanelLayout( {
7297 * expanded: false,
7298 * padded: true
7299 * } );
7300 * frame.$element.append(
7301 * toolbar.$element,
7302 * contentFrame.$element.append( $area )
7303 * );
7304 * $( 'body' ).append( frame.$element );
7305 *
7306 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7307 * // document.
7308 * toolbar.initialize();
7309 *
7310 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7311 * 'updateState' event.
7312 *
7313 * @example
7314 * // Create the toolbar
7315 * var toolFactory = new OO.ui.ToolFactory();
7316 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7317 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7318 *
7319 * // We will be placing status text in this element when tools are used
7320 * var $area = $( '<p>' ).text( 'Toolbar example' );
7321 *
7322 * // Define the tools that we're going to place in our toolbar
7323 *
7324 * // Create a class inheriting from OO.ui.Tool
7325 * function PictureTool() {
7326 * PictureTool.parent.apply( this, arguments );
7327 * }
7328 * OO.inheritClass( PictureTool, OO.ui.Tool );
7329 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7330 * // of 'icon' and 'title' (displayed icon and text).
7331 * PictureTool.static.name = 'picture';
7332 * PictureTool.static.icon = 'picture';
7333 * PictureTool.static.title = 'Insert picture';
7334 * // Defines the action that will happen when this tool is selected (clicked).
7335 * PictureTool.prototype.onSelect = function () {
7336 * $area.text( 'Picture tool clicked!' );
7337 * // Never display this tool as "active" (selected).
7338 * this.setActive( false );
7339 * };
7340 * // The toolbar can be synchronized with the state of some external stuff, like a text
7341 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7342 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7343 * PictureTool.prototype.onUpdateState = function () {
7344 * };
7345 * // Make this tool available in our toolFactory and thus our toolbar
7346 * toolFactory.register( PictureTool );
7347 *
7348 * // Register two more tools, nothing interesting here
7349 * function SettingsTool() {
7350 * SettingsTool.parent.apply( this, arguments );
7351 * this.reallyActive = false;
7352 * }
7353 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7354 * SettingsTool.static.name = 'settings';
7355 * SettingsTool.static.icon = 'settings';
7356 * SettingsTool.static.title = 'Change settings';
7357 * SettingsTool.prototype.onSelect = function () {
7358 * $area.text( 'Settings tool clicked!' );
7359 * // Toggle the active state on each click
7360 * this.reallyActive = !this.reallyActive;
7361 * this.setActive( this.reallyActive );
7362 * // To update the menu label
7363 * this.toolbar.emit( 'updateState' );
7364 * };
7365 * SettingsTool.prototype.onUpdateState = function () {
7366 * };
7367 * toolFactory.register( SettingsTool );
7368 *
7369 * // Register two more tools, nothing interesting here
7370 * function StuffTool() {
7371 * StuffTool.parent.apply( this, arguments );
7372 * this.reallyActive = false;
7373 * }
7374 * OO.inheritClass( StuffTool, OO.ui.Tool );
7375 * StuffTool.static.name = 'stuff';
7376 * StuffTool.static.icon = 'ellipsis';
7377 * StuffTool.static.title = 'More stuff';
7378 * StuffTool.prototype.onSelect = function () {
7379 * $area.text( 'More stuff tool clicked!' );
7380 * // Toggle the active state on each click
7381 * this.reallyActive = !this.reallyActive;
7382 * this.setActive( this.reallyActive );
7383 * // To update the menu label
7384 * this.toolbar.emit( 'updateState' );
7385 * };
7386 * StuffTool.prototype.onUpdateState = function () {
7387 * };
7388 * toolFactory.register( StuffTool );
7389 *
7390 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7391 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7392 * function HelpTool( toolGroup, config ) {
7393 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7394 * padded: true,
7395 * label: 'Help',
7396 * head: true
7397 * } }, config ) );
7398 * this.popup.$body.append( '<p>I am helpful!</p>' );
7399 * }
7400 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7401 * HelpTool.static.name = 'help';
7402 * HelpTool.static.icon = 'help';
7403 * HelpTool.static.title = 'Help';
7404 * toolFactory.register( HelpTool );
7405 *
7406 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7407 * // used once (but not all defined tools must be used).
7408 * toolbar.setup( [
7409 * {
7410 * // 'bar' tool groups display tools' icons only, side-by-side.
7411 * type: 'bar',
7412 * include: [ 'picture', 'help' ]
7413 * },
7414 * {
7415 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7416 * // Menu label indicates which items are selected.
7417 * type: 'menu',
7418 * indicator: 'down',
7419 * include: [ 'settings', 'stuff' ]
7420 * }
7421 * ] );
7422 *
7423 * // Create some UI around the toolbar and place it in the document
7424 * var frame = new OO.ui.PanelLayout( {
7425 * expanded: false,
7426 * framed: true
7427 * } );
7428 * var contentFrame = new OO.ui.PanelLayout( {
7429 * expanded: false,
7430 * padded: true
7431 * } );
7432 * frame.$element.append(
7433 * toolbar.$element,
7434 * contentFrame.$element.append( $area )
7435 * );
7436 * $( 'body' ).append( frame.$element );
7437 *
7438 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7439 * // document.
7440 * toolbar.initialize();
7441 * toolbar.emit( 'updateState' );
7442 *
7443 * @class
7444 * @extends OO.ui.Element
7445 * @mixins OO.EventEmitter
7446 * @mixins OO.ui.mixin.GroupElement
7447 *
7448 * @constructor
7449 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7450 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7451 * @param {Object} [config] Configuration options
7452 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7453 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7454 * the toolbar.
7455 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7456 */
7457 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
7458 // Allow passing positional parameters inside the config object
7459 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
7460 config = toolFactory;
7461 toolFactory = config.toolFactory;
7462 toolGroupFactory = config.toolGroupFactory;
7463 }
7464
7465 // Configuration initialization
7466 config = config || {};
7467
7468 // Parent constructor
7469 OO.ui.Toolbar.parent.call( this, config );
7470
7471 // Mixin constructors
7472 OO.EventEmitter.call( this );
7473 OO.ui.mixin.GroupElement.call( this, config );
7474
7475 // Properties
7476 this.toolFactory = toolFactory;
7477 this.toolGroupFactory = toolGroupFactory;
7478 this.groups = [];
7479 this.tools = {};
7480 this.$bar = $( '<div>' );
7481 this.$actions = $( '<div>' );
7482 this.initialized = false;
7483 this.onWindowResizeHandler = this.onWindowResize.bind( this );
7484
7485 // Events
7486 this.$element
7487 .add( this.$bar ).add( this.$group ).add( this.$actions )
7488 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7489
7490 // Initialization
7491 this.$group.addClass( 'oo-ui-toolbar-tools' );
7492 if ( config.actions ) {
7493 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7494 }
7495 this.$bar
7496 .addClass( 'oo-ui-toolbar-bar' )
7497 .append( this.$group, '<div style="clear:both"></div>' );
7498 if ( config.shadow ) {
7499 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7500 }
7501 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7502 };
7503
7504 /* Setup */
7505
7506 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7507 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7508 OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
7509
7510 /* Methods */
7511
7512 /**
7513 * Get the tool factory.
7514 *
7515 * @return {OO.ui.ToolFactory} Tool factory
7516 */
7517 OO.ui.Toolbar.prototype.getToolFactory = function () {
7518 return this.toolFactory;
7519 };
7520
7521 /**
7522 * Get the toolgroup factory.
7523 *
7524 * @return {OO.Factory} Toolgroup factory
7525 */
7526 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7527 return this.toolGroupFactory;
7528 };
7529
7530 /**
7531 * Handles mouse down events.
7532 *
7533 * @private
7534 * @param {jQuery.Event} e Mouse down event
7535 */
7536 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7537 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7538 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7539 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7540 return false;
7541 }
7542 };
7543
7544 /**
7545 * Handle window resize event.
7546 *
7547 * @private
7548 * @param {jQuery.Event} e Window resize event
7549 */
7550 OO.ui.Toolbar.prototype.onWindowResize = function () {
7551 this.$element.toggleClass(
7552 'oo-ui-toolbar-narrow',
7553 this.$bar.width() <= this.narrowThreshold
7554 );
7555 };
7556
7557 /**
7558 * Sets up handles and preloads required information for the toolbar to work.
7559 * This must be called after it is attached to a visible document and before doing anything else.
7560 */
7561 OO.ui.Toolbar.prototype.initialize = function () {
7562 if ( !this.initialized ) {
7563 this.initialized = true;
7564 this.narrowThreshold = this.$group.width() + this.$actions.width();
7565 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7566 this.onWindowResize();
7567 }
7568 };
7569
7570 /**
7571 * Set up the toolbar.
7572 *
7573 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7574 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7575 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7576 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7577 *
7578 * @param {Object.<string,Array>} groups List of toolgroup configurations
7579 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7580 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7581 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7582 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7583 */
7584 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7585 var i, len, type, group,
7586 items = [],
7587 defaultType = 'bar';
7588
7589 // Cleanup previous groups
7590 this.reset();
7591
7592 // Build out new groups
7593 for ( i = 0, len = groups.length; i < len; i++ ) {
7594 group = groups[ i ];
7595 if ( group.include === '*' ) {
7596 // Apply defaults to catch-all groups
7597 if ( group.type === undefined ) {
7598 group.type = 'list';
7599 }
7600 if ( group.label === undefined ) {
7601 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7602 }
7603 }
7604 // Check type has been registered
7605 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7606 items.push(
7607 this.getToolGroupFactory().create( type, this, group )
7608 );
7609 }
7610 this.addItems( items );
7611 };
7612
7613 /**
7614 * Remove all tools and toolgroups from the toolbar.
7615 */
7616 OO.ui.Toolbar.prototype.reset = function () {
7617 var i, len;
7618
7619 this.groups = [];
7620 this.tools = {};
7621 for ( i = 0, len = this.items.length; i < len; i++ ) {
7622 this.items[ i ].destroy();
7623 }
7624 this.clearItems();
7625 };
7626
7627 /**
7628 * Destroy the toolbar.
7629 *
7630 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7631 * this method whenever you are done using a toolbar.
7632 */
7633 OO.ui.Toolbar.prototype.destroy = function () {
7634 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7635 this.reset();
7636 this.$element.remove();
7637 };
7638
7639 /**
7640 * Check if the tool is available.
7641 *
7642 * Available tools are ones that have not yet been added to the toolbar.
7643 *
7644 * @param {string} name Symbolic name of tool
7645 * @return {boolean} Tool is available
7646 */
7647 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7648 return !this.tools[ name ];
7649 };
7650
7651 /**
7652 * Prevent tool from being used again.
7653 *
7654 * @param {OO.ui.Tool} tool Tool to reserve
7655 */
7656 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7657 this.tools[ tool.getName() ] = tool;
7658 };
7659
7660 /**
7661 * Allow tool to be used again.
7662 *
7663 * @param {OO.ui.Tool} tool Tool to release
7664 */
7665 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7666 delete this.tools[ tool.getName() ];
7667 };
7668
7669 /**
7670 * Get accelerator label for tool.
7671 *
7672 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7673 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7674 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7675 *
7676 * @param {string} name Symbolic name of tool
7677 * @return {string|undefined} Tool accelerator label if available
7678 */
7679 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7680 return undefined;
7681 };
7682
7683 /**
7684 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7685 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7686 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7687 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7688 *
7689 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7690 *
7691 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7692 *
7693 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7694 *
7695 * 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.)
7696 *
7697 * include: [ { group: 'group-name' } ]
7698 *
7699 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7700 *
7701 * include: '*'
7702 *
7703 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7704 * please see the [OOjs UI documentation on MediaWiki][1].
7705 *
7706 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7707 *
7708 * @abstract
7709 * @class
7710 * @extends OO.ui.Widget
7711 * @mixins OO.ui.mixin.GroupElement
7712 *
7713 * @constructor
7714 * @param {OO.ui.Toolbar} toolbar
7715 * @param {Object} [config] Configuration options
7716 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7717 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7718 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7719 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7720 * This setting is particularly useful when tools have been added to the toolgroup
7721 * en masse (e.g., via the catch-all selector).
7722 */
7723 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7724 // Allow passing positional parameters inside the config object
7725 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7726 config = toolbar;
7727 toolbar = config.toolbar;
7728 }
7729
7730 // Configuration initialization
7731 config = config || {};
7732
7733 // Parent constructor
7734 OO.ui.ToolGroup.parent.call( this, config );
7735
7736 // Mixin constructors
7737 OO.ui.mixin.GroupElement.call( this, config );
7738
7739 // Properties
7740 this.toolbar = toolbar;
7741 this.tools = {};
7742 this.pressed = null;
7743 this.autoDisabled = false;
7744 this.include = config.include || [];
7745 this.exclude = config.exclude || [];
7746 this.promote = config.promote || [];
7747 this.demote = config.demote || [];
7748 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7749
7750 // Events
7751 this.$element.on( {
7752 mousedown: this.onMouseKeyDown.bind( this ),
7753 mouseup: this.onMouseKeyUp.bind( this ),
7754 keydown: this.onMouseKeyDown.bind( this ),
7755 keyup: this.onMouseKeyUp.bind( this ),
7756 focus: this.onMouseOverFocus.bind( this ),
7757 blur: this.onMouseOutBlur.bind( this ),
7758 mouseover: this.onMouseOverFocus.bind( this ),
7759 mouseout: this.onMouseOutBlur.bind( this )
7760 } );
7761 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7762 this.aggregate( { disable: 'itemDisable' } );
7763 this.connect( this, { itemDisable: 'updateDisabled' } );
7764
7765 // Initialization
7766 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7767 this.$element
7768 .addClass( 'oo-ui-toolGroup' )
7769 .append( this.$group );
7770 this.populate();
7771 };
7772
7773 /* Setup */
7774
7775 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7776 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
7777
7778 /* Events */
7779
7780 /**
7781 * @event update
7782 */
7783
7784 /* Static Properties */
7785
7786 /**
7787 * Show labels in tooltips.
7788 *
7789 * @static
7790 * @inheritable
7791 * @property {boolean}
7792 */
7793 OO.ui.ToolGroup.static.titleTooltips = false;
7794
7795 /**
7796 * Show acceleration labels in tooltips.
7797 *
7798 * Note: The OOjs UI library does not include an accelerator system, but does contain
7799 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7800 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7801 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7802 *
7803 * @static
7804 * @inheritable
7805 * @property {boolean}
7806 */
7807 OO.ui.ToolGroup.static.accelTooltips = false;
7808
7809 /**
7810 * Automatically disable the toolgroup when all tools are disabled
7811 *
7812 * @static
7813 * @inheritable
7814 * @property {boolean}
7815 */
7816 OO.ui.ToolGroup.static.autoDisable = true;
7817
7818 /* Methods */
7819
7820 /**
7821 * @inheritdoc
7822 */
7823 OO.ui.ToolGroup.prototype.isDisabled = function () {
7824 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
7825 };
7826
7827 /**
7828 * @inheritdoc
7829 */
7830 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7831 var i, item, allDisabled = true;
7832
7833 if ( this.constructor.static.autoDisable ) {
7834 for ( i = this.items.length - 1; i >= 0; i-- ) {
7835 item = this.items[ i ];
7836 if ( !item.isDisabled() ) {
7837 allDisabled = false;
7838 break;
7839 }
7840 }
7841 this.autoDisabled = allDisabled;
7842 }
7843 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
7844 };
7845
7846 /**
7847 * Handle mouse down and key down events.
7848 *
7849 * @protected
7850 * @param {jQuery.Event} e Mouse down or key down event
7851 */
7852 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7853 if (
7854 !this.isDisabled() &&
7855 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7856 ) {
7857 this.pressed = this.getTargetTool( e );
7858 if ( this.pressed ) {
7859 this.pressed.setActive( true );
7860 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7861 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7862 }
7863 return false;
7864 }
7865 };
7866
7867 /**
7868 * Handle captured mouse up and key up events.
7869 *
7870 * @protected
7871 * @param {Event} e Mouse up or key up event
7872 */
7873 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7874 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7875 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7876 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7877 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7878 this.onMouseKeyUp( e );
7879 };
7880
7881 /**
7882 * Handle mouse up and key up events.
7883 *
7884 * @protected
7885 * @param {jQuery.Event} e Mouse up or key up event
7886 */
7887 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7888 var tool = this.getTargetTool( e );
7889
7890 if (
7891 !this.isDisabled() && this.pressed && this.pressed === tool &&
7892 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7893 ) {
7894 this.pressed.onSelect();
7895 this.pressed = null;
7896 return false;
7897 }
7898
7899 this.pressed = null;
7900 };
7901
7902 /**
7903 * Handle mouse over and focus events.
7904 *
7905 * @protected
7906 * @param {jQuery.Event} e Mouse over or focus event
7907 */
7908 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7909 var tool = this.getTargetTool( e );
7910
7911 if ( this.pressed && this.pressed === tool ) {
7912 this.pressed.setActive( true );
7913 }
7914 };
7915
7916 /**
7917 * Handle mouse out and blur events.
7918 *
7919 * @protected
7920 * @param {jQuery.Event} e Mouse out or blur event
7921 */
7922 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7923 var tool = this.getTargetTool( e );
7924
7925 if ( this.pressed && this.pressed === tool ) {
7926 this.pressed.setActive( false );
7927 }
7928 };
7929
7930 /**
7931 * Get the closest tool to a jQuery.Event.
7932 *
7933 * Only tool links are considered, which prevents other elements in the tool such as popups from
7934 * triggering tool group interactions.
7935 *
7936 * @private
7937 * @param {jQuery.Event} e
7938 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7939 */
7940 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7941 var tool,
7942 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7943
7944 if ( $item.length ) {
7945 tool = $item.parent().data( 'oo-ui-tool' );
7946 }
7947
7948 return tool && !tool.isDisabled() ? tool : null;
7949 };
7950
7951 /**
7952 * Handle tool registry register events.
7953 *
7954 * If a tool is registered after the group is created, we must repopulate the list to account for:
7955 *
7956 * - a tool being added that may be included
7957 * - a tool already included being overridden
7958 *
7959 * @protected
7960 * @param {string} name Symbolic name of tool
7961 */
7962 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7963 this.populate();
7964 };
7965
7966 /**
7967 * Get the toolbar that contains the toolgroup.
7968 *
7969 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7970 */
7971 OO.ui.ToolGroup.prototype.getToolbar = function () {
7972 return this.toolbar;
7973 };
7974
7975 /**
7976 * Add and remove tools based on configuration.
7977 */
7978 OO.ui.ToolGroup.prototype.populate = function () {
7979 var i, len, name, tool,
7980 toolFactory = this.toolbar.getToolFactory(),
7981 names = {},
7982 add = [],
7983 remove = [],
7984 list = this.toolbar.getToolFactory().getTools(
7985 this.include, this.exclude, this.promote, this.demote
7986 );
7987
7988 // Build a list of needed tools
7989 for ( i = 0, len = list.length; i < len; i++ ) {
7990 name = list[ i ];
7991 if (
7992 // Tool exists
7993 toolFactory.lookup( name ) &&
7994 // Tool is available or is already in this group
7995 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7996 ) {
7997 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7998 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7999 this.toolbar.tools[ name ] = true;
8000 tool = this.tools[ name ];
8001 if ( !tool ) {
8002 // Auto-initialize tools on first use
8003 this.tools[ name ] = tool = toolFactory.create( name, this );
8004 tool.updateTitle();
8005 }
8006 this.toolbar.reserveTool( tool );
8007 add.push( tool );
8008 names[ name ] = true;
8009 }
8010 }
8011 // Remove tools that are no longer needed
8012 for ( name in this.tools ) {
8013 if ( !names[ name ] ) {
8014 this.tools[ name ].destroy();
8015 this.toolbar.releaseTool( this.tools[ name ] );
8016 remove.push( this.tools[ name ] );
8017 delete this.tools[ name ];
8018 }
8019 }
8020 if ( remove.length ) {
8021 this.removeItems( remove );
8022 }
8023 // Update emptiness state
8024 if ( add.length ) {
8025 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8026 } else {
8027 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8028 }
8029 // Re-add tools (moving existing ones to new locations)
8030 this.addItems( add );
8031 // Disabled state may depend on items
8032 this.updateDisabled();
8033 };
8034
8035 /**
8036 * Destroy toolgroup.
8037 */
8038 OO.ui.ToolGroup.prototype.destroy = function () {
8039 var name;
8040
8041 this.clearItems();
8042 this.toolbar.getToolFactory().disconnect( this );
8043 for ( name in this.tools ) {
8044 this.toolbar.releaseTool( this.tools[ name ] );
8045 this.tools[ name ].disconnect( this ).destroy();
8046 delete this.tools[ name ];
8047 }
8048 this.$element.remove();
8049 };
8050
8051 /**
8052 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8053 * consists of a header that contains the dialog title, a body with the message, and a footer that
8054 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8055 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8056 *
8057 * There are two basic types of message dialogs, confirmation and alert:
8058 *
8059 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8060 * more details about the consequences.
8061 * - **alert**: the dialog title describes which event occurred and the message provides more information
8062 * about why the event occurred.
8063 *
8064 * The MessageDialog class specifies two actions: ‘accept’, the primary
8065 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8066 * passing along the selected action.
8067 *
8068 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8069 *
8070 * @example
8071 * // Example: Creating and opening a message dialog window.
8072 * var messageDialog = new OO.ui.MessageDialog();
8073 *
8074 * // Create and append a window manager.
8075 * var windowManager = new OO.ui.WindowManager();
8076 * $( 'body' ).append( windowManager.$element );
8077 * windowManager.addWindows( [ messageDialog ] );
8078 * // Open the window.
8079 * windowManager.openWindow( messageDialog, {
8080 * title: 'Basic message dialog',
8081 * message: 'This is the message'
8082 * } );
8083 *
8084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8085 *
8086 * @class
8087 * @extends OO.ui.Dialog
8088 *
8089 * @constructor
8090 * @param {Object} [config] Configuration options
8091 */
8092 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8093 // Parent constructor
8094 OO.ui.MessageDialog.parent.call( this, config );
8095
8096 // Properties
8097 this.verticalActionLayout = null;
8098
8099 // Initialization
8100 this.$element.addClass( 'oo-ui-messageDialog' );
8101 };
8102
8103 /* Setup */
8104
8105 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8106
8107 /* Static Properties */
8108
8109 OO.ui.MessageDialog.static.name = 'message';
8110
8111 OO.ui.MessageDialog.static.size = 'small';
8112
8113 OO.ui.MessageDialog.static.verbose = false;
8114
8115 /**
8116 * Dialog title.
8117 *
8118 * The title of a confirmation dialog describes what a progressive action will do. The
8119 * title of an alert dialog describes which event occurred.
8120 *
8121 * @static
8122 * @inheritable
8123 * @property {jQuery|string|Function|null}
8124 */
8125 OO.ui.MessageDialog.static.title = null;
8126
8127 /**
8128 * The message displayed in the dialog body.
8129 *
8130 * A confirmation message describes the consequences of a progressive action. An alert
8131 * message describes why an event occurred.
8132 *
8133 * @static
8134 * @inheritable
8135 * @property {jQuery|string|Function|null}
8136 */
8137 OO.ui.MessageDialog.static.message = null;
8138
8139 OO.ui.MessageDialog.static.actions = [
8140 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8141 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8142 ];
8143
8144 /* Methods */
8145
8146 /**
8147 * @inheritdoc
8148 */
8149 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8150 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8151
8152 // Events
8153 this.manager.connect( this, {
8154 resize: 'onResize'
8155 } );
8156
8157 return this;
8158 };
8159
8160 /**
8161 * @inheritdoc
8162 */
8163 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8164 this.fitActions();
8165 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8166 };
8167
8168 /**
8169 * Handle window resized events.
8170 *
8171 * @private
8172 */
8173 OO.ui.MessageDialog.prototype.onResize = function () {
8174 var dialog = this;
8175 dialog.fitActions();
8176 // Wait for CSS transition to finish and do it again :(
8177 setTimeout( function () {
8178 dialog.fitActions();
8179 }, 300 );
8180 };
8181
8182 /**
8183 * Toggle action layout between vertical and horizontal.
8184 *
8185 *
8186 * @private
8187 * @param {boolean} [value] Layout actions vertically, omit to toggle
8188 * @chainable
8189 */
8190 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8191 value = value === undefined ? !this.verticalActionLayout : !!value;
8192
8193 if ( value !== this.verticalActionLayout ) {
8194 this.verticalActionLayout = value;
8195 this.$actions
8196 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8197 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8198 }
8199
8200 return this;
8201 };
8202
8203 /**
8204 * @inheritdoc
8205 */
8206 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8207 if ( action ) {
8208 return new OO.ui.Process( function () {
8209 this.close( { action: action } );
8210 }, this );
8211 }
8212 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8213 };
8214
8215 /**
8216 * @inheritdoc
8217 *
8218 * @param {Object} [data] Dialog opening data
8219 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8220 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8221 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8222 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8223 * action item
8224 */
8225 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8226 data = data || {};
8227
8228 // Parent method
8229 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8230 .next( function () {
8231 this.title.setLabel(
8232 data.title !== undefined ? data.title : this.constructor.static.title
8233 );
8234 this.message.setLabel(
8235 data.message !== undefined ? data.message : this.constructor.static.message
8236 );
8237 this.message.$element.toggleClass(
8238 'oo-ui-messageDialog-message-verbose',
8239 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8240 );
8241 }, this );
8242 };
8243
8244 /**
8245 * @inheritdoc
8246 */
8247 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8248 data = data || {};
8249
8250 // Parent method
8251 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8252 .next( function () {
8253 // Focus the primary action button
8254 var actions = this.actions.get();
8255 actions = actions.filter( function ( action ) {
8256 return action.getFlags().indexOf( 'primary' ) > -1;
8257 } );
8258 if ( actions.length > 0 ) {
8259 actions[ 0 ].$button.focus();
8260 }
8261 }, this );
8262 };
8263
8264 /**
8265 * @inheritdoc
8266 */
8267 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8268 var bodyHeight, oldOverflow,
8269 $scrollable = this.container.$element;
8270
8271 oldOverflow = $scrollable[ 0 ].style.overflow;
8272 $scrollable[ 0 ].style.overflow = 'hidden';
8273
8274 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8275
8276 bodyHeight = this.text.$element.outerHeight( true );
8277 $scrollable[ 0 ].style.overflow = oldOverflow;
8278
8279 return bodyHeight;
8280 };
8281
8282 /**
8283 * @inheritdoc
8284 */
8285 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8286 var $scrollable = this.container.$element;
8287 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8288
8289 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8290 // Need to do it after transition completes (250ms), add 50ms just in case.
8291 setTimeout( function () {
8292 var oldOverflow = $scrollable[ 0 ].style.overflow;
8293 $scrollable[ 0 ].style.overflow = 'hidden';
8294
8295 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8296
8297 $scrollable[ 0 ].style.overflow = oldOverflow;
8298 }, 300 );
8299
8300 return this;
8301 };
8302
8303 /**
8304 * @inheritdoc
8305 */
8306 OO.ui.MessageDialog.prototype.initialize = function () {
8307 // Parent method
8308 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8309
8310 // Properties
8311 this.$actions = $( '<div>' );
8312 this.container = new OO.ui.PanelLayout( {
8313 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8314 } );
8315 this.text = new OO.ui.PanelLayout( {
8316 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8317 } );
8318 this.message = new OO.ui.LabelWidget( {
8319 classes: [ 'oo-ui-messageDialog-message' ]
8320 } );
8321
8322 // Initialization
8323 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8324 this.$content.addClass( 'oo-ui-messageDialog-content' );
8325 this.container.$element.append( this.text.$element );
8326 this.text.$element.append( this.title.$element, this.message.$element );
8327 this.$body.append( this.container.$element );
8328 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8329 this.$foot.append( this.$actions );
8330 };
8331
8332 /**
8333 * @inheritdoc
8334 */
8335 OO.ui.MessageDialog.prototype.attachActions = function () {
8336 var i, len, other, special, others;
8337
8338 // Parent method
8339 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8340
8341 special = this.actions.getSpecial();
8342 others = this.actions.getOthers();
8343
8344 if ( special.safe ) {
8345 this.$actions.append( special.safe.$element );
8346 special.safe.toggleFramed( false );
8347 }
8348 if ( others.length ) {
8349 for ( i = 0, len = others.length; i < len; i++ ) {
8350 other = others[ i ];
8351 this.$actions.append( other.$element );
8352 other.toggleFramed( false );
8353 }
8354 }
8355 if ( special.primary ) {
8356 this.$actions.append( special.primary.$element );
8357 special.primary.toggleFramed( false );
8358 }
8359
8360 if ( !this.isOpening() ) {
8361 // If the dialog is currently opening, this will be called automatically soon.
8362 // This also calls #fitActions.
8363 this.updateSize();
8364 }
8365 };
8366
8367 /**
8368 * Fit action actions into columns or rows.
8369 *
8370 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8371 *
8372 * @private
8373 */
8374 OO.ui.MessageDialog.prototype.fitActions = function () {
8375 var i, len, action,
8376 previous = this.verticalActionLayout,
8377 actions = this.actions.get();
8378
8379 // Detect clipping
8380 this.toggleVerticalActionLayout( false );
8381 for ( i = 0, len = actions.length; i < len; i++ ) {
8382 action = actions[ i ];
8383 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8384 this.toggleVerticalActionLayout( true );
8385 break;
8386 }
8387 }
8388
8389 // Move the body out of the way of the foot
8390 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8391
8392 if ( this.verticalActionLayout !== previous ) {
8393 // We changed the layout, window height might need to be updated.
8394 this.updateSize();
8395 }
8396 };
8397
8398 /**
8399 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8400 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8401 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8402 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8403 * required for each process.
8404 *
8405 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8406 * processes with an animation. The header contains the dialog title as well as
8407 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8408 * a ‘primary’ action on the right (e.g., ‘Done’).
8409 *
8410 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8411 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8412 *
8413 * @example
8414 * // Example: Creating and opening a process dialog window.
8415 * function MyProcessDialog( config ) {
8416 * MyProcessDialog.parent.call( this, config );
8417 * }
8418 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8419 *
8420 * MyProcessDialog.static.title = 'Process dialog';
8421 * MyProcessDialog.static.actions = [
8422 * { action: 'save', label: 'Done', flags: 'primary' },
8423 * { label: 'Cancel', flags: 'safe' }
8424 * ];
8425 *
8426 * MyProcessDialog.prototype.initialize = function () {
8427 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8428 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8429 * 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>' );
8430 * this.$body.append( this.content.$element );
8431 * };
8432 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8433 * var dialog = this;
8434 * if ( action ) {
8435 * return new OO.ui.Process( function () {
8436 * dialog.close( { action: action } );
8437 * } );
8438 * }
8439 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8440 * };
8441 *
8442 * var windowManager = new OO.ui.WindowManager();
8443 * $( 'body' ).append( windowManager.$element );
8444 *
8445 * var dialog = new MyProcessDialog();
8446 * windowManager.addWindows( [ dialog ] );
8447 * windowManager.openWindow( dialog );
8448 *
8449 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8450 *
8451 * @abstract
8452 * @class
8453 * @extends OO.ui.Dialog
8454 *
8455 * @constructor
8456 * @param {Object} [config] Configuration options
8457 */
8458 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8459 // Parent constructor
8460 OO.ui.ProcessDialog.parent.call( this, config );
8461
8462 // Properties
8463 this.fitOnOpen = false;
8464
8465 // Initialization
8466 this.$element.addClass( 'oo-ui-processDialog' );
8467 };
8468
8469 /* Setup */
8470
8471 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8472
8473 /* Methods */
8474
8475 /**
8476 * Handle dismiss button click events.
8477 *
8478 * Hides errors.
8479 *
8480 * @private
8481 */
8482 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8483 this.hideErrors();
8484 };
8485
8486 /**
8487 * Handle retry button click events.
8488 *
8489 * Hides errors and then tries again.
8490 *
8491 * @private
8492 */
8493 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8494 this.hideErrors();
8495 this.executeAction( this.currentAction );
8496 };
8497
8498 /**
8499 * @inheritdoc
8500 */
8501 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8502 if ( this.actions.isSpecial( action ) ) {
8503 this.fitLabel();
8504 }
8505 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8506 };
8507
8508 /**
8509 * @inheritdoc
8510 */
8511 OO.ui.ProcessDialog.prototype.initialize = function () {
8512 // Parent method
8513 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8514
8515 // Properties
8516 this.$navigation = $( '<div>' );
8517 this.$location = $( '<div>' );
8518 this.$safeActions = $( '<div>' );
8519 this.$primaryActions = $( '<div>' );
8520 this.$otherActions = $( '<div>' );
8521 this.dismissButton = new OO.ui.ButtonWidget( {
8522 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8523 } );
8524 this.retryButton = new OO.ui.ButtonWidget();
8525 this.$errors = $( '<div>' );
8526 this.$errorsTitle = $( '<div>' );
8527
8528 // Events
8529 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8530 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8531
8532 // Initialization
8533 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8534 this.$location
8535 .append( this.title.$element )
8536 .addClass( 'oo-ui-processDialog-location' );
8537 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8538 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8539 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8540 this.$errorsTitle
8541 .addClass( 'oo-ui-processDialog-errors-title' )
8542 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8543 this.$errors
8544 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8545 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8546 this.$content
8547 .addClass( 'oo-ui-processDialog-content' )
8548 .append( this.$errors );
8549 this.$navigation
8550 .addClass( 'oo-ui-processDialog-navigation' )
8551 .append( this.$safeActions, this.$location, this.$primaryActions );
8552 this.$head.append( this.$navigation );
8553 this.$foot.append( this.$otherActions );
8554 };
8555
8556 /**
8557 * @inheritdoc
8558 */
8559 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8560 var i, len, widgets = [];
8561 for ( i = 0, len = actions.length; i < len; i++ ) {
8562 widgets.push(
8563 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8564 );
8565 }
8566 return widgets;
8567 };
8568
8569 /**
8570 * @inheritdoc
8571 */
8572 OO.ui.ProcessDialog.prototype.attachActions = function () {
8573 var i, len, other, special, others;
8574
8575 // Parent method
8576 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8577
8578 special = this.actions.getSpecial();
8579 others = this.actions.getOthers();
8580 if ( special.primary ) {
8581 this.$primaryActions.append( special.primary.$element );
8582 }
8583 for ( i = 0, len = others.length; i < len; i++ ) {
8584 other = others[ i ];
8585 this.$otherActions.append( other.$element );
8586 }
8587 if ( special.safe ) {
8588 this.$safeActions.append( special.safe.$element );
8589 }
8590
8591 this.fitLabel();
8592 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8593 };
8594
8595 /**
8596 * @inheritdoc
8597 */
8598 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8599 var process = this;
8600 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8601 .fail( function ( errors ) {
8602 process.showErrors( errors || [] );
8603 } );
8604 };
8605
8606 /**
8607 * @inheritdoc
8608 */
8609 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8610 // Parent method
8611 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8612
8613 this.fitLabel();
8614 };
8615
8616 /**
8617 * Fit label between actions.
8618 *
8619 * @private
8620 * @chainable
8621 */
8622 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8623 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8624 size = this.getSizeProperties();
8625
8626 if ( typeof size.width !== 'number' ) {
8627 if ( this.isOpened() ) {
8628 navigationWidth = this.$head.width() - 20;
8629 } else if ( this.isOpening() ) {
8630 if ( !this.fitOnOpen ) {
8631 // Size is relative and the dialog isn't open yet, so wait.
8632 this.manager.opening.done( this.fitLabel.bind( this ) );
8633 this.fitOnOpen = true;
8634 }
8635 return;
8636 } else {
8637 return;
8638 }
8639 } else {
8640 navigationWidth = size.width - 20;
8641 }
8642
8643 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8644 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8645 biggerWidth = Math.max( safeWidth, primaryWidth );
8646
8647 labelWidth = this.title.$element.width();
8648
8649 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8650 // We have enough space to center the label
8651 leftWidth = rightWidth = biggerWidth;
8652 } else {
8653 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8654 if ( this.getDir() === 'ltr' ) {
8655 leftWidth = safeWidth;
8656 rightWidth = primaryWidth;
8657 } else {
8658 leftWidth = primaryWidth;
8659 rightWidth = safeWidth;
8660 }
8661 }
8662
8663 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8664
8665 return this;
8666 };
8667
8668 /**
8669 * Handle errors that occurred during accept or reject processes.
8670 *
8671 * @private
8672 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8673 */
8674 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8675 var i, len, $item, actions,
8676 items = [],
8677 abilities = {},
8678 recoverable = true,
8679 warning = false;
8680
8681 if ( errors instanceof OO.ui.Error ) {
8682 errors = [ errors ];
8683 }
8684
8685 for ( i = 0, len = errors.length; i < len; i++ ) {
8686 if ( !errors[ i ].isRecoverable() ) {
8687 recoverable = false;
8688 }
8689 if ( errors[ i ].isWarning() ) {
8690 warning = true;
8691 }
8692 $item = $( '<div>' )
8693 .addClass( 'oo-ui-processDialog-error' )
8694 .append( errors[ i ].getMessage() );
8695 items.push( $item[ 0 ] );
8696 }
8697 this.$errorItems = $( items );
8698 if ( recoverable ) {
8699 abilities[ this.currentAction ] = true;
8700 // Copy the flags from the first matching action
8701 actions = this.actions.get( { actions: this.currentAction } );
8702 if ( actions.length ) {
8703 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8704 }
8705 } else {
8706 abilities[ this.currentAction ] = false;
8707 this.actions.setAbilities( abilities );
8708 }
8709 if ( warning ) {
8710 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8711 } else {
8712 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8713 }
8714 this.retryButton.toggle( recoverable );
8715 this.$errorsTitle.after( this.$errorItems );
8716 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8717 };
8718
8719 /**
8720 * Hide errors.
8721 *
8722 * @private
8723 */
8724 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8725 this.$errors.addClass( 'oo-ui-element-hidden' );
8726 if ( this.$errorItems ) {
8727 this.$errorItems.remove();
8728 this.$errorItems = null;
8729 }
8730 };
8731
8732 /**
8733 * @inheritdoc
8734 */
8735 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8736 // Parent method
8737 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8738 .first( function () {
8739 // Make sure to hide errors
8740 this.hideErrors();
8741 this.fitOnOpen = false;
8742 }, this );
8743 };
8744
8745 /**
8746 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8747 * which is a widget that is specified by reference before any optional configuration settings.
8748 *
8749 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8750 *
8751 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8752 * A left-alignment is used for forms with many fields.
8753 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8754 * A right-alignment is used for long but familiar forms which users tab through,
8755 * verifying the current field with a quick glance at the label.
8756 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8757 * that users fill out from top to bottom.
8758 * - **inline**: The label is placed after the field-widget and aligned to the left.
8759 * An inline-alignment is best used with checkboxes or radio buttons.
8760 *
8761 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8762 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8763 *
8764 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8765 * @class
8766 * @extends OO.ui.Layout
8767 * @mixins OO.ui.mixin.LabelElement
8768 * @mixins OO.ui.mixin.TitledElement
8769 *
8770 * @constructor
8771 * @param {OO.ui.Widget} fieldWidget Field widget
8772 * @param {Object} [config] Configuration options
8773 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8774 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8775 * The array may contain strings or OO.ui.HtmlSnippet instances.
8776 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8777 * The array may contain strings or OO.ui.HtmlSnippet instances.
8778 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8779 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8780 * For important messages, you are advised to use `notices`, as they are always shown.
8781 *
8782 * @throws {Error} An error is thrown if no widget is specified
8783 */
8784 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8785 var hasInputWidget, div, i;
8786
8787 // Allow passing positional parameters inside the config object
8788 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8789 config = fieldWidget;
8790 fieldWidget = config.fieldWidget;
8791 }
8792
8793 // Make sure we have required constructor arguments
8794 if ( fieldWidget === undefined ) {
8795 throw new Error( 'Widget not found' );
8796 }
8797
8798 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
8799
8800 // Configuration initialization
8801 config = $.extend( { align: 'left' }, config );
8802
8803 // Parent constructor
8804 OO.ui.FieldLayout.parent.call( this, config );
8805
8806 // Mixin constructors
8807 OO.ui.mixin.LabelElement.call( this, config );
8808 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8809
8810 // Properties
8811 this.fieldWidget = fieldWidget;
8812 this.errors = config.errors || [];
8813 this.notices = config.notices || [];
8814 this.$field = $( '<div>' );
8815 this.$messages = $( '<ul>' );
8816 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8817 this.align = null;
8818 if ( config.help ) {
8819 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8820 classes: [ 'oo-ui-fieldLayout-help' ],
8821 framed: false,
8822 icon: 'info'
8823 } );
8824
8825 div = $( '<div>' );
8826 if ( config.help instanceof OO.ui.HtmlSnippet ) {
8827 div.html( config.help.toString() );
8828 } else {
8829 div.text( config.help );
8830 }
8831 this.popupButtonWidget.getPopup().$body.append(
8832 div.addClass( 'oo-ui-fieldLayout-help-content' )
8833 );
8834 this.$help = this.popupButtonWidget.$element;
8835 } else {
8836 this.$help = $( [] );
8837 }
8838
8839 // Events
8840 if ( hasInputWidget ) {
8841 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8842 }
8843 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8844
8845 // Initialization
8846 this.$element
8847 .addClass( 'oo-ui-fieldLayout' )
8848 .append( this.$help, this.$body );
8849 if ( this.errors.length || this.notices.length ) {
8850 this.$element.append( this.$messages );
8851 }
8852 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8853 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
8854 this.$field
8855 .addClass( 'oo-ui-fieldLayout-field' )
8856 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8857 .append( this.fieldWidget.$element );
8858
8859 for ( i = 0; i < this.notices.length; i++ ) {
8860 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
8861 }
8862 for ( i = 0; i < this.errors.length; i++ ) {
8863 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
8864 }
8865
8866 this.setAlignment( config.align );
8867 };
8868
8869 /* Setup */
8870
8871 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8872 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
8873 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
8874
8875 /* Methods */
8876
8877 /**
8878 * Handle field disable events.
8879 *
8880 * @private
8881 * @param {boolean} value Field is disabled
8882 */
8883 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8884 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8885 };
8886
8887 /**
8888 * Handle label mouse click events.
8889 *
8890 * @private
8891 * @param {jQuery.Event} e Mouse click event
8892 */
8893 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8894 this.fieldWidget.simulateLabelClick();
8895 return false;
8896 };
8897
8898 /**
8899 * Get the widget contained by the field.
8900 *
8901 * @return {OO.ui.Widget} Field widget
8902 */
8903 OO.ui.FieldLayout.prototype.getField = function () {
8904 return this.fieldWidget;
8905 };
8906
8907 /**
8908 * @param {string} kind 'error' or 'notice'
8909 * @param {string|OO.ui.HtmlSnippet} text
8910 * @return {jQuery}
8911 */
8912 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
8913 var $listItem, $icon, message;
8914 $listItem = $( '<li>' );
8915 if ( kind === 'error' ) {
8916 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
8917 } else if ( kind === 'notice' ) {
8918 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
8919 } else {
8920 $icon = '';
8921 }
8922 message = new OO.ui.LabelWidget( { label: text } );
8923 $listItem
8924 .append( $icon, message.$element )
8925 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
8926 return $listItem;
8927 };
8928
8929 /**
8930 * Set the field alignment mode.
8931 *
8932 * @private
8933 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8934 * @chainable
8935 */
8936 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8937 if ( value !== this.align ) {
8938 // Default to 'left'
8939 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8940 value = 'left';
8941 }
8942 // Reorder elements
8943 if ( value === 'inline' ) {
8944 this.$body.append( this.$field, this.$label );
8945 } else {
8946 this.$body.append( this.$label, this.$field );
8947 }
8948 // Set classes. The following classes can be used here:
8949 // * oo-ui-fieldLayout-align-left
8950 // * oo-ui-fieldLayout-align-right
8951 // * oo-ui-fieldLayout-align-top
8952 // * oo-ui-fieldLayout-align-inline
8953 if ( this.align ) {
8954 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8955 }
8956 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8957 this.align = value;
8958 }
8959
8960 return this;
8961 };
8962
8963 /**
8964 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8965 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8966 * is required and is specified before any optional configuration settings.
8967 *
8968 * Labels can be aligned in one of four ways:
8969 *
8970 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8971 * A left-alignment is used for forms with many fields.
8972 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8973 * A right-alignment is used for long but familiar forms which users tab through,
8974 * verifying the current field with a quick glance at the label.
8975 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8976 * that users fill out from top to bottom.
8977 * - **inline**: The label is placed after the field-widget and aligned to the left.
8978 * An inline-alignment is best used with checkboxes or radio buttons.
8979 *
8980 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8981 * text is specified.
8982 *
8983 * @example
8984 * // Example of an ActionFieldLayout
8985 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8986 * new OO.ui.TextInputWidget( {
8987 * placeholder: 'Field widget'
8988 * } ),
8989 * new OO.ui.ButtonWidget( {
8990 * label: 'Button'
8991 * } ),
8992 * {
8993 * label: 'An ActionFieldLayout. This label is aligned top',
8994 * align: 'top',
8995 * help: 'This is help text'
8996 * }
8997 * );
8998 *
8999 * $( 'body' ).append( actionFieldLayout.$element );
9000 *
9001 *
9002 * @class
9003 * @extends OO.ui.FieldLayout
9004 *
9005 * @constructor
9006 * @param {OO.ui.Widget} fieldWidget Field widget
9007 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9008 */
9009 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9010 // Allow passing positional parameters inside the config object
9011 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9012 config = fieldWidget;
9013 fieldWidget = config.fieldWidget;
9014 buttonWidget = config.buttonWidget;
9015 }
9016
9017 // Parent constructor
9018 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9019
9020 // Properties
9021 this.buttonWidget = buttonWidget;
9022 this.$button = $( '<div>' );
9023 this.$input = $( '<div>' );
9024
9025 // Initialization
9026 this.$element
9027 .addClass( 'oo-ui-actionFieldLayout' );
9028 this.$button
9029 .addClass( 'oo-ui-actionFieldLayout-button' )
9030 .append( this.buttonWidget.$element );
9031 this.$input
9032 .addClass( 'oo-ui-actionFieldLayout-input' )
9033 .append( this.fieldWidget.$element );
9034 this.$field
9035 .append( this.$input, this.$button );
9036 };
9037
9038 /* Setup */
9039
9040 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9041
9042 /**
9043 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9044 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9045 * configured with a label as well. For more information and examples,
9046 * please see the [OOjs UI documentation on MediaWiki][1].
9047 *
9048 * @example
9049 * // Example of a fieldset layout
9050 * var input1 = new OO.ui.TextInputWidget( {
9051 * placeholder: 'A text input field'
9052 * } );
9053 *
9054 * var input2 = new OO.ui.TextInputWidget( {
9055 * placeholder: 'A text input field'
9056 * } );
9057 *
9058 * var fieldset = new OO.ui.FieldsetLayout( {
9059 * label: 'Example of a fieldset layout'
9060 * } );
9061 *
9062 * fieldset.addItems( [
9063 * new OO.ui.FieldLayout( input1, {
9064 * label: 'Field One'
9065 * } ),
9066 * new OO.ui.FieldLayout( input2, {
9067 * label: 'Field Two'
9068 * } )
9069 * ] );
9070 * $( 'body' ).append( fieldset.$element );
9071 *
9072 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9073 *
9074 * @class
9075 * @extends OO.ui.Layout
9076 * @mixins OO.ui.mixin.IconElement
9077 * @mixins OO.ui.mixin.LabelElement
9078 * @mixins OO.ui.mixin.GroupElement
9079 *
9080 * @constructor
9081 * @param {Object} [config] Configuration options
9082 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9083 */
9084 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9085 // Configuration initialization
9086 config = config || {};
9087
9088 // Parent constructor
9089 OO.ui.FieldsetLayout.parent.call( this, config );
9090
9091 // Mixin constructors
9092 OO.ui.mixin.IconElement.call( this, config );
9093 OO.ui.mixin.LabelElement.call( this, config );
9094 OO.ui.mixin.GroupElement.call( this, config );
9095
9096 if ( config.help ) {
9097 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9098 classes: [ 'oo-ui-fieldsetLayout-help' ],
9099 framed: false,
9100 icon: 'info'
9101 } );
9102
9103 this.popupButtonWidget.getPopup().$body.append(
9104 $( '<div>' )
9105 .text( config.help )
9106 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9107 );
9108 this.$help = this.popupButtonWidget.$element;
9109 } else {
9110 this.$help = $( [] );
9111 }
9112
9113 // Initialization
9114 this.$element
9115 .addClass( 'oo-ui-fieldsetLayout' )
9116 .prepend( this.$help, this.$icon, this.$label, this.$group );
9117 if ( Array.isArray( config.items ) ) {
9118 this.addItems( config.items );
9119 }
9120 };
9121
9122 /* Setup */
9123
9124 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9125 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9126 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9127 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9128
9129 /**
9130 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9131 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9132 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9133 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9134 *
9135 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9136 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9137 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9138 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9139 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9140 * often have simplified APIs to match the capabilities of HTML forms.
9141 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9142 *
9143 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9144 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9145 *
9146 * @example
9147 * // Example of a form layout that wraps a fieldset layout
9148 * var input1 = new OO.ui.TextInputWidget( {
9149 * placeholder: 'Username'
9150 * } );
9151 * var input2 = new OO.ui.TextInputWidget( {
9152 * placeholder: 'Password',
9153 * type: 'password'
9154 * } );
9155 * var submit = new OO.ui.ButtonInputWidget( {
9156 * label: 'Submit'
9157 * } );
9158 *
9159 * var fieldset = new OO.ui.FieldsetLayout( {
9160 * label: 'A form layout'
9161 * } );
9162 * fieldset.addItems( [
9163 * new OO.ui.FieldLayout( input1, {
9164 * label: 'Username',
9165 * align: 'top'
9166 * } ),
9167 * new OO.ui.FieldLayout( input2, {
9168 * label: 'Password',
9169 * align: 'top'
9170 * } ),
9171 * new OO.ui.FieldLayout( submit )
9172 * ] );
9173 * var form = new OO.ui.FormLayout( {
9174 * items: [ fieldset ],
9175 * action: '/api/formhandler',
9176 * method: 'get'
9177 * } )
9178 * $( 'body' ).append( form.$element );
9179 *
9180 * @class
9181 * @extends OO.ui.Layout
9182 * @mixins OO.ui.mixin.GroupElement
9183 *
9184 * @constructor
9185 * @param {Object} [config] Configuration options
9186 * @cfg {string} [method] HTML form `method` attribute
9187 * @cfg {string} [action] HTML form `action` attribute
9188 * @cfg {string} [enctype] HTML form `enctype` attribute
9189 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9190 */
9191 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9192 // Configuration initialization
9193 config = config || {};
9194
9195 // Parent constructor
9196 OO.ui.FormLayout.parent.call( this, config );
9197
9198 // Mixin constructors
9199 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9200
9201 // Events
9202 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9203
9204 // Make sure the action is safe
9205 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9206 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9207 }
9208
9209 // Initialization
9210 this.$element
9211 .addClass( 'oo-ui-formLayout' )
9212 .attr( {
9213 method: config.method,
9214 action: config.action,
9215 enctype: config.enctype
9216 } );
9217 if ( Array.isArray( config.items ) ) {
9218 this.addItems( config.items );
9219 }
9220 };
9221
9222 /* Setup */
9223
9224 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9225 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9226
9227 /* Events */
9228
9229 /**
9230 * A 'submit' event is emitted when the form is submitted.
9231 *
9232 * @event submit
9233 */
9234
9235 /* Static Properties */
9236
9237 OO.ui.FormLayout.static.tagName = 'form';
9238
9239 /* Methods */
9240
9241 /**
9242 * Handle form submit events.
9243 *
9244 * @private
9245 * @param {jQuery.Event} e Submit event
9246 * @fires submit
9247 */
9248 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9249 if ( this.emit( 'submit' ) ) {
9250 return false;
9251 }
9252 };
9253
9254 /**
9255 * 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)
9256 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9257 *
9258 * @example
9259 * var menuLayout = new OO.ui.MenuLayout( {
9260 * position: 'top'
9261 * } ),
9262 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9263 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9264 * select = new OO.ui.SelectWidget( {
9265 * items: [
9266 * new OO.ui.OptionWidget( {
9267 * data: 'before',
9268 * label: 'Before',
9269 * } ),
9270 * new OO.ui.OptionWidget( {
9271 * data: 'after',
9272 * label: 'After',
9273 * } ),
9274 * new OO.ui.OptionWidget( {
9275 * data: 'top',
9276 * label: 'Top',
9277 * } ),
9278 * new OO.ui.OptionWidget( {
9279 * data: 'bottom',
9280 * label: 'Bottom',
9281 * } )
9282 * ]
9283 * } ).on( 'select', function ( item ) {
9284 * menuLayout.setMenuPosition( item.getData() );
9285 * } );
9286 *
9287 * menuLayout.$menu.append(
9288 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9289 * );
9290 * menuLayout.$content.append(
9291 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9292 * );
9293 * $( 'body' ).append( menuLayout.$element );
9294 *
9295 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9296 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9297 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9298 * may be omitted.
9299 *
9300 * .oo-ui-menuLayout-menu {
9301 * height: 200px;
9302 * width: 200px;
9303 * }
9304 * .oo-ui-menuLayout-content {
9305 * top: 200px;
9306 * left: 200px;
9307 * right: 200px;
9308 * bottom: 200px;
9309 * }
9310 *
9311 * @class
9312 * @extends OO.ui.Layout
9313 *
9314 * @constructor
9315 * @param {Object} [config] Configuration options
9316 * @cfg {boolean} [showMenu=true] Show menu
9317 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9318 */
9319 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9320 // Configuration initialization
9321 config = $.extend( {
9322 showMenu: true,
9323 menuPosition: 'before'
9324 }, config );
9325
9326 // Parent constructor
9327 OO.ui.MenuLayout.parent.call( this, config );
9328
9329 /**
9330 * Menu DOM node
9331 *
9332 * @property {jQuery}
9333 */
9334 this.$menu = $( '<div>' );
9335 /**
9336 * Content DOM node
9337 *
9338 * @property {jQuery}
9339 */
9340 this.$content = $( '<div>' );
9341
9342 // Initialization
9343 this.$menu
9344 .addClass( 'oo-ui-menuLayout-menu' );
9345 this.$content.addClass( 'oo-ui-menuLayout-content' );
9346 this.$element
9347 .addClass( 'oo-ui-menuLayout' )
9348 .append( this.$content, this.$menu );
9349 this.setMenuPosition( config.menuPosition );
9350 this.toggleMenu( config.showMenu );
9351 };
9352
9353 /* Setup */
9354
9355 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9356
9357 /* Methods */
9358
9359 /**
9360 * Toggle menu.
9361 *
9362 * @param {boolean} showMenu Show menu, omit to toggle
9363 * @chainable
9364 */
9365 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9366 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9367
9368 if ( this.showMenu !== showMenu ) {
9369 this.showMenu = showMenu;
9370 this.$element
9371 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9372 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9373 }
9374
9375 return this;
9376 };
9377
9378 /**
9379 * Check if menu is visible
9380 *
9381 * @return {boolean} Menu is visible
9382 */
9383 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9384 return this.showMenu;
9385 };
9386
9387 /**
9388 * Set menu position.
9389 *
9390 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9391 * @throws {Error} If position value is not supported
9392 * @chainable
9393 */
9394 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9395 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9396 this.menuPosition = position;
9397 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9398
9399 return this;
9400 };
9401
9402 /**
9403 * Get menu position.
9404 *
9405 * @return {string} Menu position
9406 */
9407 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9408 return this.menuPosition;
9409 };
9410
9411 /**
9412 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9413 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9414 * through the pages and select which one to display. By default, only one page is
9415 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9416 * the booklet layout automatically focuses on the first focusable element, unless the
9417 * default setting is changed. Optionally, booklets can be configured to show
9418 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9419 *
9420 * @example
9421 * // Example of a BookletLayout that contains two PageLayouts.
9422 *
9423 * function PageOneLayout( name, config ) {
9424 * PageOneLayout.parent.call( this, name, config );
9425 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9426 * }
9427 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9428 * PageOneLayout.prototype.setupOutlineItem = function () {
9429 * this.outlineItem.setLabel( 'Page One' );
9430 * };
9431 *
9432 * function PageTwoLayout( name, config ) {
9433 * PageTwoLayout.parent.call( this, name, config );
9434 * this.$element.append( '<p>Second page</p>' );
9435 * }
9436 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9437 * PageTwoLayout.prototype.setupOutlineItem = function () {
9438 * this.outlineItem.setLabel( 'Page Two' );
9439 * };
9440 *
9441 * var page1 = new PageOneLayout( 'one' ),
9442 * page2 = new PageTwoLayout( 'two' );
9443 *
9444 * var booklet = new OO.ui.BookletLayout( {
9445 * outlined: true
9446 * } );
9447 *
9448 * booklet.addPages ( [ page1, page2 ] );
9449 * $( 'body' ).append( booklet.$element );
9450 *
9451 * @class
9452 * @extends OO.ui.MenuLayout
9453 *
9454 * @constructor
9455 * @param {Object} [config] Configuration options
9456 * @cfg {boolean} [continuous=false] Show all pages, one after another
9457 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9458 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9459 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9460 */
9461 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9462 // Configuration initialization
9463 config = config || {};
9464
9465 // Parent constructor
9466 OO.ui.BookletLayout.parent.call( this, config );
9467
9468 // Properties
9469 this.currentPageName = null;
9470 this.pages = {};
9471 this.ignoreFocus = false;
9472 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9473 this.$content.append( this.stackLayout.$element );
9474 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9475 this.outlineVisible = false;
9476 this.outlined = !!config.outlined;
9477 if ( this.outlined ) {
9478 this.editable = !!config.editable;
9479 this.outlineControlsWidget = null;
9480 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9481 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9482 this.$menu.append( this.outlinePanel.$element );
9483 this.outlineVisible = true;
9484 if ( this.editable ) {
9485 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9486 this.outlineSelectWidget
9487 );
9488 }
9489 }
9490 this.toggleMenu( this.outlined );
9491
9492 // Events
9493 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9494 if ( this.outlined ) {
9495 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9496 }
9497 if ( this.autoFocus ) {
9498 // Event 'focus' does not bubble, but 'focusin' does
9499 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9500 }
9501
9502 // Initialization
9503 this.$element.addClass( 'oo-ui-bookletLayout' );
9504 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9505 if ( this.outlined ) {
9506 this.outlinePanel.$element
9507 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9508 .append( this.outlineSelectWidget.$element );
9509 if ( this.editable ) {
9510 this.outlinePanel.$element
9511 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9512 .append( this.outlineControlsWidget.$element );
9513 }
9514 }
9515 };
9516
9517 /* Setup */
9518
9519 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9520
9521 /* Events */
9522
9523 /**
9524 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9525 * @event set
9526 * @param {OO.ui.PageLayout} page Current page
9527 */
9528
9529 /**
9530 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9531 *
9532 * @event add
9533 * @param {OO.ui.PageLayout[]} page Added pages
9534 * @param {number} index Index pages were added at
9535 */
9536
9537 /**
9538 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9539 * {@link #removePages removed} from the booklet.
9540 *
9541 * @event remove
9542 * @param {OO.ui.PageLayout[]} pages Removed pages
9543 */
9544
9545 /* Methods */
9546
9547 /**
9548 * Handle stack layout focus.
9549 *
9550 * @private
9551 * @param {jQuery.Event} e Focusin event
9552 */
9553 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9554 var name, $target;
9555
9556 // Find the page that an element was focused within
9557 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9558 for ( name in this.pages ) {
9559 // Check for page match, exclude current page to find only page changes
9560 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9561 this.setPage( name );
9562 break;
9563 }
9564 }
9565 };
9566
9567 /**
9568 * Handle stack layout set events.
9569 *
9570 * @private
9571 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9572 */
9573 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9574 var layout = this;
9575 if ( page ) {
9576 page.scrollElementIntoView( { complete: function () {
9577 if ( layout.autoFocus ) {
9578 layout.focus();
9579 }
9580 } } );
9581 }
9582 };
9583
9584 /**
9585 * Focus the first input in the current page.
9586 *
9587 * If no page is selected, the first selectable page will be selected.
9588 * If the focus is already in an element on the current page, nothing will happen.
9589 * @param {number} [itemIndex] A specific item to focus on
9590 */
9591 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9592 var $input, page,
9593 items = this.stackLayout.getItems();
9594
9595 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9596 page = items[ itemIndex ];
9597 } else {
9598 page = this.stackLayout.getCurrentItem();
9599 }
9600
9601 if ( !page && this.outlined ) {
9602 this.selectFirstSelectablePage();
9603 page = this.stackLayout.getCurrentItem();
9604 }
9605 if ( !page ) {
9606 return;
9607 }
9608 // Only change the focus if is not already in the current page
9609 if ( !page.$element.find( ':focus' ).length ) {
9610 $input = page.$element.find( ':input:first' );
9611 if ( $input.length ) {
9612 $input[ 0 ].focus();
9613 }
9614 }
9615 };
9616
9617 /**
9618 * Find the first focusable input in the booklet layout and focus
9619 * on it.
9620 */
9621 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9622 var i, len,
9623 found = false,
9624 items = this.stackLayout.getItems(),
9625 checkAndFocus = function () {
9626 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9627 $( this ).focus();
9628 found = true;
9629 return false;
9630 }
9631 };
9632
9633 for ( i = 0, len = items.length; i < len; i++ ) {
9634 if ( found ) {
9635 break;
9636 }
9637 // Find all potentially focusable elements in the item
9638 // and check if they are focusable
9639 items[ i ].$element
9640 .find( 'input, select, textarea, button, object' )
9641 /* jshint loopfunc:true */
9642 .each( checkAndFocus );
9643 }
9644 };
9645
9646 /**
9647 * Handle outline widget select events.
9648 *
9649 * @private
9650 * @param {OO.ui.OptionWidget|null} item Selected item
9651 */
9652 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9653 if ( item ) {
9654 this.setPage( item.getData() );
9655 }
9656 };
9657
9658 /**
9659 * Check if booklet has an outline.
9660 *
9661 * @return {boolean} Booklet has an outline
9662 */
9663 OO.ui.BookletLayout.prototype.isOutlined = function () {
9664 return this.outlined;
9665 };
9666
9667 /**
9668 * Check if booklet has editing controls.
9669 *
9670 * @return {boolean} Booklet is editable
9671 */
9672 OO.ui.BookletLayout.prototype.isEditable = function () {
9673 return this.editable;
9674 };
9675
9676 /**
9677 * Check if booklet has a visible outline.
9678 *
9679 * @return {boolean} Outline is visible
9680 */
9681 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9682 return this.outlined && this.outlineVisible;
9683 };
9684
9685 /**
9686 * Hide or show the outline.
9687 *
9688 * @param {boolean} [show] Show outline, omit to invert current state
9689 * @chainable
9690 */
9691 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9692 if ( this.outlined ) {
9693 show = show === undefined ? !this.outlineVisible : !!show;
9694 this.outlineVisible = show;
9695 this.toggleMenu( show );
9696 }
9697
9698 return this;
9699 };
9700
9701 /**
9702 * Get the page closest to the specified page.
9703 *
9704 * @param {OO.ui.PageLayout} page Page to use as a reference point
9705 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9706 */
9707 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9708 var next, prev, level,
9709 pages = this.stackLayout.getItems(),
9710 index = pages.indexOf( page );
9711
9712 if ( index !== -1 ) {
9713 next = pages[ index + 1 ];
9714 prev = pages[ index - 1 ];
9715 // Prefer adjacent pages at the same level
9716 if ( this.outlined ) {
9717 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9718 if (
9719 prev &&
9720 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9721 ) {
9722 return prev;
9723 }
9724 if (
9725 next &&
9726 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9727 ) {
9728 return next;
9729 }
9730 }
9731 }
9732 return prev || next || null;
9733 };
9734
9735 /**
9736 * Get the outline widget.
9737 *
9738 * If the booklet is not outlined, the method will return `null`.
9739 *
9740 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9741 */
9742 OO.ui.BookletLayout.prototype.getOutline = function () {
9743 return this.outlineSelectWidget;
9744 };
9745
9746 /**
9747 * Get the outline controls widget.
9748 *
9749 * If the outline is not editable, the method will return `null`.
9750 *
9751 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9752 */
9753 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9754 return this.outlineControlsWidget;
9755 };
9756
9757 /**
9758 * Get a page by its symbolic name.
9759 *
9760 * @param {string} name Symbolic name of page
9761 * @return {OO.ui.PageLayout|undefined} Page, if found
9762 */
9763 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9764 return this.pages[ name ];
9765 };
9766
9767 /**
9768 * Get the current page.
9769 *
9770 * @return {OO.ui.PageLayout|undefined} Current page, if found
9771 */
9772 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9773 var name = this.getCurrentPageName();
9774 return name ? this.getPage( name ) : undefined;
9775 };
9776
9777 /**
9778 * Get the symbolic name of the current page.
9779 *
9780 * @return {string|null} Symbolic name of the current page
9781 */
9782 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9783 return this.currentPageName;
9784 };
9785
9786 /**
9787 * Add pages to the booklet layout
9788 *
9789 * When pages are added with the same names as existing pages, the existing pages will be
9790 * automatically removed before the new pages are added.
9791 *
9792 * @param {OO.ui.PageLayout[]} pages Pages to add
9793 * @param {number} index Index of the insertion point
9794 * @fires add
9795 * @chainable
9796 */
9797 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9798 var i, len, name, page, item, currentIndex,
9799 stackLayoutPages = this.stackLayout.getItems(),
9800 remove = [],
9801 items = [];
9802
9803 // Remove pages with same names
9804 for ( i = 0, len = pages.length; i < len; i++ ) {
9805 page = pages[ i ];
9806 name = page.getName();
9807
9808 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9809 // Correct the insertion index
9810 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
9811 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9812 index--;
9813 }
9814 remove.push( this.pages[ name ] );
9815 }
9816 }
9817 if ( remove.length ) {
9818 this.removePages( remove );
9819 }
9820
9821 // Add new pages
9822 for ( i = 0, len = pages.length; i < len; i++ ) {
9823 page = pages[ i ];
9824 name = page.getName();
9825 this.pages[ page.getName() ] = page;
9826 if ( this.outlined ) {
9827 item = new OO.ui.OutlineOptionWidget( { data: name } );
9828 page.setOutlineItem( item );
9829 items.push( item );
9830 }
9831 }
9832
9833 if ( this.outlined && items.length ) {
9834 this.outlineSelectWidget.addItems( items, index );
9835 this.selectFirstSelectablePage();
9836 }
9837 this.stackLayout.addItems( pages, index );
9838 this.emit( 'add', pages, index );
9839
9840 return this;
9841 };
9842
9843 /**
9844 * Remove the specified pages from the booklet layout.
9845 *
9846 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9847 *
9848 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9849 * @fires remove
9850 * @chainable
9851 */
9852 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9853 var i, len, name, page,
9854 items = [];
9855
9856 for ( i = 0, len = pages.length; i < len; i++ ) {
9857 page = pages[ i ];
9858 name = page.getName();
9859 delete this.pages[ name ];
9860 if ( this.outlined ) {
9861 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9862 page.setOutlineItem( null );
9863 }
9864 }
9865 if ( this.outlined && items.length ) {
9866 this.outlineSelectWidget.removeItems( items );
9867 this.selectFirstSelectablePage();
9868 }
9869 this.stackLayout.removeItems( pages );
9870 this.emit( 'remove', pages );
9871
9872 return this;
9873 };
9874
9875 /**
9876 * Clear all pages from the booklet layout.
9877 *
9878 * To remove only a subset of pages from the booklet, use the #removePages method.
9879 *
9880 * @fires remove
9881 * @chainable
9882 */
9883 OO.ui.BookletLayout.prototype.clearPages = function () {
9884 var i, len,
9885 pages = this.stackLayout.getItems();
9886
9887 this.pages = {};
9888 this.currentPageName = null;
9889 if ( this.outlined ) {
9890 this.outlineSelectWidget.clearItems();
9891 for ( i = 0, len = pages.length; i < len; i++ ) {
9892 pages[ i ].setOutlineItem( null );
9893 }
9894 }
9895 this.stackLayout.clearItems();
9896
9897 this.emit( 'remove', pages );
9898
9899 return this;
9900 };
9901
9902 /**
9903 * Set the current page by symbolic name.
9904 *
9905 * @fires set
9906 * @param {string} name Symbolic name of page
9907 */
9908 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9909 var selectedItem,
9910 $focused,
9911 page = this.pages[ name ];
9912
9913 if ( name !== this.currentPageName ) {
9914 if ( this.outlined ) {
9915 selectedItem = this.outlineSelectWidget.getSelectedItem();
9916 if ( selectedItem && selectedItem.getData() !== name ) {
9917 this.outlineSelectWidget.selectItemByData( name );
9918 }
9919 }
9920 if ( page ) {
9921 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9922 this.pages[ this.currentPageName ].setActive( false );
9923 // Blur anything focused if the next page doesn't have anything focusable - this
9924 // is not needed if the next page has something focusable because once it is focused
9925 // this blur happens automatically
9926 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9927 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9928 if ( $focused.length ) {
9929 $focused[ 0 ].blur();
9930 }
9931 }
9932 }
9933 this.currentPageName = name;
9934 this.stackLayout.setItem( page );
9935 page.setActive( true );
9936 this.emit( 'set', page );
9937 }
9938 }
9939 };
9940
9941 /**
9942 * Select the first selectable page.
9943 *
9944 * @chainable
9945 */
9946 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9947 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9948 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9949 }
9950
9951 return this;
9952 };
9953
9954 /**
9955 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9956 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9957 * select which one to display. By default, only one card is displayed at a time. When a user
9958 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9959 * unless the default setting is changed.
9960 *
9961 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9962 *
9963 * @example
9964 * // Example of a IndexLayout that contains two CardLayouts.
9965 *
9966 * function CardOneLayout( name, config ) {
9967 * CardOneLayout.parent.call( this, name, config );
9968 * this.$element.append( '<p>First card</p>' );
9969 * }
9970 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9971 * CardOneLayout.prototype.setupTabItem = function () {
9972 * this.tabItem.setLabel( 'Card One' );
9973 * };
9974 *
9975 * function CardTwoLayout( name, config ) {
9976 * CardTwoLayout.parent.call( this, name, config );
9977 * this.$element.append( '<p>Second card</p>' );
9978 * }
9979 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9980 * CardTwoLayout.prototype.setupTabItem = function () {
9981 * this.tabItem.setLabel( 'Card Two' );
9982 * };
9983 *
9984 * var card1 = new CardOneLayout( 'one' ),
9985 * card2 = new CardTwoLayout( 'two' );
9986 *
9987 * var index = new OO.ui.IndexLayout();
9988 *
9989 * index.addCards ( [ card1, card2 ] );
9990 * $( 'body' ).append( index.$element );
9991 *
9992 * @class
9993 * @extends OO.ui.MenuLayout
9994 *
9995 * @constructor
9996 * @param {Object} [config] Configuration options
9997 * @cfg {boolean} [continuous=false] Show all cards, one after another
9998 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9999 */
10000 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
10001 // Configuration initialization
10002 config = $.extend( {}, config, { menuPosition: 'top' } );
10003
10004 // Parent constructor
10005 OO.ui.IndexLayout.parent.call( this, config );
10006
10007 // Properties
10008 this.currentCardName = null;
10009 this.cards = {};
10010 this.ignoreFocus = false;
10011 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
10012 this.$content.append( this.stackLayout.$element );
10013 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10014
10015 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10016 this.tabPanel = new OO.ui.PanelLayout();
10017 this.$menu.append( this.tabPanel.$element );
10018
10019 this.toggleMenu( true );
10020
10021 // Events
10022 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10023 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10024 if ( this.autoFocus ) {
10025 // Event 'focus' does not bubble, but 'focusin' does
10026 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10027 }
10028
10029 // Initialization
10030 this.$element.addClass( 'oo-ui-indexLayout' );
10031 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10032 this.tabPanel.$element
10033 .addClass( 'oo-ui-indexLayout-tabPanel' )
10034 .append( this.tabSelectWidget.$element );
10035 };
10036
10037 /* Setup */
10038
10039 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10040
10041 /* Events */
10042
10043 /**
10044 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10045 * @event set
10046 * @param {OO.ui.CardLayout} card Current card
10047 */
10048
10049 /**
10050 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10051 *
10052 * @event add
10053 * @param {OO.ui.CardLayout[]} card Added cards
10054 * @param {number} index Index cards were added at
10055 */
10056
10057 /**
10058 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10059 * {@link #removeCards removed} from the index.
10060 *
10061 * @event remove
10062 * @param {OO.ui.CardLayout[]} cards Removed cards
10063 */
10064
10065 /* Methods */
10066
10067 /**
10068 * Handle stack layout focus.
10069 *
10070 * @private
10071 * @param {jQuery.Event} e Focusin event
10072 */
10073 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10074 var name, $target;
10075
10076 // Find the card that an element was focused within
10077 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10078 for ( name in this.cards ) {
10079 // Check for card match, exclude current card to find only card changes
10080 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10081 this.setCard( name );
10082 break;
10083 }
10084 }
10085 };
10086
10087 /**
10088 * Handle stack layout set events.
10089 *
10090 * @private
10091 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10092 */
10093 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10094 var layout = this;
10095 if ( card ) {
10096 card.scrollElementIntoView( { complete: function () {
10097 if ( layout.autoFocus ) {
10098 layout.focus();
10099 }
10100 } } );
10101 }
10102 };
10103
10104 /**
10105 * Focus the first input in the current card.
10106 *
10107 * If no card is selected, the first selectable card will be selected.
10108 * If the focus is already in an element on the current card, nothing will happen.
10109 * @param {number} [itemIndex] A specific item to focus on
10110 */
10111 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10112 var $input, card,
10113 items = this.stackLayout.getItems();
10114
10115 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10116 card = items[ itemIndex ];
10117 } else {
10118 card = this.stackLayout.getCurrentItem();
10119 }
10120
10121 if ( !card ) {
10122 this.selectFirstSelectableCard();
10123 card = this.stackLayout.getCurrentItem();
10124 }
10125 if ( !card ) {
10126 return;
10127 }
10128 // Only change the focus if is not already in the current card
10129 if ( !card.$element.find( ':focus' ).length ) {
10130 $input = card.$element.find( ':input:first' );
10131 if ( $input.length ) {
10132 $input[ 0 ].focus();
10133 }
10134 }
10135 };
10136
10137 /**
10138 * Find the first focusable input in the index layout and focus
10139 * on it.
10140 */
10141 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10142 var i, len,
10143 found = false,
10144 items = this.stackLayout.getItems(),
10145 checkAndFocus = function () {
10146 if ( OO.ui.isFocusableElement( $( this ) ) ) {
10147 $( this ).focus();
10148 found = true;
10149 return false;
10150 }
10151 };
10152
10153 for ( i = 0, len = items.length; i < len; i++ ) {
10154 if ( found ) {
10155 break;
10156 }
10157 // Find all potentially focusable elements in the item
10158 // and check if they are focusable
10159 items[ i ].$element
10160 .find( 'input, select, textarea, button, object' )
10161 .each( checkAndFocus );
10162 }
10163 };
10164
10165 /**
10166 * Handle tab widget select events.
10167 *
10168 * @private
10169 * @param {OO.ui.OptionWidget|null} item Selected item
10170 */
10171 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10172 if ( item ) {
10173 this.setCard( item.getData() );
10174 }
10175 };
10176
10177 /**
10178 * Get the card closest to the specified card.
10179 *
10180 * @param {OO.ui.CardLayout} card Card to use as a reference point
10181 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10182 */
10183 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10184 var next, prev, level,
10185 cards = this.stackLayout.getItems(),
10186 index = cards.indexOf( card );
10187
10188 if ( index !== -1 ) {
10189 next = cards[ index + 1 ];
10190 prev = cards[ index - 1 ];
10191 // Prefer adjacent cards at the same level
10192 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10193 if (
10194 prev &&
10195 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10196 ) {
10197 return prev;
10198 }
10199 if (
10200 next &&
10201 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10202 ) {
10203 return next;
10204 }
10205 }
10206 return prev || next || null;
10207 };
10208
10209 /**
10210 * Get the tabs widget.
10211 *
10212 * @return {OO.ui.TabSelectWidget} Tabs widget
10213 */
10214 OO.ui.IndexLayout.prototype.getTabs = function () {
10215 return this.tabSelectWidget;
10216 };
10217
10218 /**
10219 * Get a card by its symbolic name.
10220 *
10221 * @param {string} name Symbolic name of card
10222 * @return {OO.ui.CardLayout|undefined} Card, if found
10223 */
10224 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10225 return this.cards[ name ];
10226 };
10227
10228 /**
10229 * Get the current card.
10230 *
10231 * @return {OO.ui.CardLayout|undefined} Current card, if found
10232 */
10233 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10234 var name = this.getCurrentCardName();
10235 return name ? this.getCard( name ) : undefined;
10236 };
10237
10238 /**
10239 * Get the symbolic name of the current card.
10240 *
10241 * @return {string|null} Symbolic name of the current card
10242 */
10243 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10244 return this.currentCardName;
10245 };
10246
10247 /**
10248 * Add cards to the index layout
10249 *
10250 * When cards are added with the same names as existing cards, the existing cards will be
10251 * automatically removed before the new cards are added.
10252 *
10253 * @param {OO.ui.CardLayout[]} cards Cards to add
10254 * @param {number} index Index of the insertion point
10255 * @fires add
10256 * @chainable
10257 */
10258 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10259 var i, len, name, card, item, currentIndex,
10260 stackLayoutCards = this.stackLayout.getItems(),
10261 remove = [],
10262 items = [];
10263
10264 // Remove cards with same names
10265 for ( i = 0, len = cards.length; i < len; i++ ) {
10266 card = cards[ i ];
10267 name = card.getName();
10268
10269 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10270 // Correct the insertion index
10271 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10272 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10273 index--;
10274 }
10275 remove.push( this.cards[ name ] );
10276 }
10277 }
10278 if ( remove.length ) {
10279 this.removeCards( remove );
10280 }
10281
10282 // Add new cards
10283 for ( i = 0, len = cards.length; i < len; i++ ) {
10284 card = cards[ i ];
10285 name = card.getName();
10286 this.cards[ card.getName() ] = card;
10287 item = new OO.ui.TabOptionWidget( { data: name } );
10288 card.setTabItem( item );
10289 items.push( item );
10290 }
10291
10292 if ( items.length ) {
10293 this.tabSelectWidget.addItems( items, index );
10294 this.selectFirstSelectableCard();
10295 }
10296 this.stackLayout.addItems( cards, index );
10297 this.emit( 'add', cards, index );
10298
10299 return this;
10300 };
10301
10302 /**
10303 * Remove the specified cards from the index layout.
10304 *
10305 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10306 *
10307 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10308 * @fires remove
10309 * @chainable
10310 */
10311 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10312 var i, len, name, card,
10313 items = [];
10314
10315 for ( i = 0, len = cards.length; i < len; i++ ) {
10316 card = cards[ i ];
10317 name = card.getName();
10318 delete this.cards[ name ];
10319 items.push( this.tabSelectWidget.getItemFromData( name ) );
10320 card.setTabItem( null );
10321 }
10322 if ( items.length ) {
10323 this.tabSelectWidget.removeItems( items );
10324 this.selectFirstSelectableCard();
10325 }
10326 this.stackLayout.removeItems( cards );
10327 this.emit( 'remove', cards );
10328
10329 return this;
10330 };
10331
10332 /**
10333 * Clear all cards from the index layout.
10334 *
10335 * To remove only a subset of cards from the index, use the #removeCards method.
10336 *
10337 * @fires remove
10338 * @chainable
10339 */
10340 OO.ui.IndexLayout.prototype.clearCards = function () {
10341 var i, len,
10342 cards = this.stackLayout.getItems();
10343
10344 this.cards = {};
10345 this.currentCardName = null;
10346 this.tabSelectWidget.clearItems();
10347 for ( i = 0, len = cards.length; i < len; i++ ) {
10348 cards[ i ].setTabItem( null );
10349 }
10350 this.stackLayout.clearItems();
10351
10352 this.emit( 'remove', cards );
10353
10354 return this;
10355 };
10356
10357 /**
10358 * Set the current card by symbolic name.
10359 *
10360 * @fires set
10361 * @param {string} name Symbolic name of card
10362 */
10363 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10364 var selectedItem,
10365 $focused,
10366 card = this.cards[ name ];
10367
10368 if ( name !== this.currentCardName ) {
10369 selectedItem = this.tabSelectWidget.getSelectedItem();
10370 if ( selectedItem && selectedItem.getData() !== name ) {
10371 this.tabSelectWidget.selectItemByData( name );
10372 }
10373 if ( card ) {
10374 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
10375 this.cards[ this.currentCardName ].setActive( false );
10376 // Blur anything focused if the next card doesn't have anything focusable - this
10377 // is not needed if the next card has something focusable because once it is focused
10378 // this blur happens automatically
10379 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
10380 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
10381 if ( $focused.length ) {
10382 $focused[ 0 ].blur();
10383 }
10384 }
10385 }
10386 this.currentCardName = name;
10387 this.stackLayout.setItem( card );
10388 card.setActive( true );
10389 this.emit( 'set', card );
10390 }
10391 }
10392 };
10393
10394 /**
10395 * Select the first selectable card.
10396 *
10397 * @chainable
10398 */
10399 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10400 if ( !this.tabSelectWidget.getSelectedItem() ) {
10401 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10402 }
10403
10404 return this;
10405 };
10406
10407 /**
10408 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10409 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10410 *
10411 * @example
10412 * // Example of a panel layout
10413 * var panel = new OO.ui.PanelLayout( {
10414 * expanded: false,
10415 * framed: true,
10416 * padded: true,
10417 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10418 * } );
10419 * $( 'body' ).append( panel.$element );
10420 *
10421 * @class
10422 * @extends OO.ui.Layout
10423 *
10424 * @constructor
10425 * @param {Object} [config] Configuration options
10426 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10427 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10428 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10429 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10430 */
10431 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10432 // Configuration initialization
10433 config = $.extend( {
10434 scrollable: false,
10435 padded: false,
10436 expanded: true,
10437 framed: false
10438 }, config );
10439
10440 // Parent constructor
10441 OO.ui.PanelLayout.parent.call( this, config );
10442
10443 // Initialization
10444 this.$element.addClass( 'oo-ui-panelLayout' );
10445 if ( config.scrollable ) {
10446 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10447 }
10448 if ( config.padded ) {
10449 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10450 }
10451 if ( config.expanded ) {
10452 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10453 }
10454 if ( config.framed ) {
10455 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10456 }
10457 };
10458
10459 /* Setup */
10460
10461 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10462
10463 /**
10464 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10465 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10466 * rather extended to include the required content and functionality.
10467 *
10468 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10469 * item is customized (with a label) using the #setupTabItem method. See
10470 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10471 *
10472 * @class
10473 * @extends OO.ui.PanelLayout
10474 *
10475 * @constructor
10476 * @param {string} name Unique symbolic name of card
10477 * @param {Object} [config] Configuration options
10478 */
10479 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10480 // Allow passing positional parameters inside the config object
10481 if ( OO.isPlainObject( name ) && config === undefined ) {
10482 config = name;
10483 name = config.name;
10484 }
10485
10486 // Configuration initialization
10487 config = $.extend( { scrollable: true }, config );
10488
10489 // Parent constructor
10490 OO.ui.CardLayout.parent.call( this, config );
10491
10492 // Properties
10493 this.name = name;
10494 this.tabItem = null;
10495 this.active = false;
10496
10497 // Initialization
10498 this.$element.addClass( 'oo-ui-cardLayout' );
10499 };
10500
10501 /* Setup */
10502
10503 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10504
10505 /* Events */
10506
10507 /**
10508 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10509 * shown in a index layout that is configured to display only one card at a time.
10510 *
10511 * @event active
10512 * @param {boolean} active Card is active
10513 */
10514
10515 /* Methods */
10516
10517 /**
10518 * Get the symbolic name of the card.
10519 *
10520 * @return {string} Symbolic name of card
10521 */
10522 OO.ui.CardLayout.prototype.getName = function () {
10523 return this.name;
10524 };
10525
10526 /**
10527 * Check if card is active.
10528 *
10529 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10530 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10531 *
10532 * @return {boolean} Card is active
10533 */
10534 OO.ui.CardLayout.prototype.isActive = function () {
10535 return this.active;
10536 };
10537
10538 /**
10539 * Get tab item.
10540 *
10541 * The tab item allows users to access the card from the index's tab
10542 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10543 *
10544 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10545 */
10546 OO.ui.CardLayout.prototype.getTabItem = function () {
10547 return this.tabItem;
10548 };
10549
10550 /**
10551 * Set or unset the tab item.
10552 *
10553 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10554 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10555 * level), use #setupTabItem instead of this method.
10556 *
10557 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10558 * @chainable
10559 */
10560 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10561 this.tabItem = tabItem || null;
10562 if ( tabItem ) {
10563 this.setupTabItem();
10564 }
10565 return this;
10566 };
10567
10568 /**
10569 * Set up the tab item.
10570 *
10571 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10572 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10573 * the #setTabItem method instead.
10574 *
10575 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10576 * @chainable
10577 */
10578 OO.ui.CardLayout.prototype.setupTabItem = function () {
10579 return this;
10580 };
10581
10582 /**
10583 * Set the card to its 'active' state.
10584 *
10585 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10586 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10587 * context, setting the active state on a card does nothing.
10588 *
10589 * @param {boolean} value Card is active
10590 * @fires active
10591 */
10592 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10593 active = !!active;
10594
10595 if ( active !== this.active ) {
10596 this.active = active;
10597 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10598 this.emit( 'active', this.active );
10599 }
10600 };
10601
10602 /**
10603 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10604 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10605 * rather extended to include the required content and functionality.
10606 *
10607 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10608 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10609 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10610 *
10611 * @class
10612 * @extends OO.ui.PanelLayout
10613 *
10614 * @constructor
10615 * @param {string} name Unique symbolic name of page
10616 * @param {Object} [config] Configuration options
10617 */
10618 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10619 // Allow passing positional parameters inside the config object
10620 if ( OO.isPlainObject( name ) && config === undefined ) {
10621 config = name;
10622 name = config.name;
10623 }
10624
10625 // Configuration initialization
10626 config = $.extend( { scrollable: true }, config );
10627
10628 // Parent constructor
10629 OO.ui.PageLayout.parent.call( this, config );
10630
10631 // Properties
10632 this.name = name;
10633 this.outlineItem = null;
10634 this.active = false;
10635
10636 // Initialization
10637 this.$element.addClass( 'oo-ui-pageLayout' );
10638 };
10639
10640 /* Setup */
10641
10642 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10643
10644 /* Events */
10645
10646 /**
10647 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10648 * shown in a booklet layout that is configured to display only one page at a time.
10649 *
10650 * @event active
10651 * @param {boolean} active Page is active
10652 */
10653
10654 /* Methods */
10655
10656 /**
10657 * Get the symbolic name of the page.
10658 *
10659 * @return {string} Symbolic name of page
10660 */
10661 OO.ui.PageLayout.prototype.getName = function () {
10662 return this.name;
10663 };
10664
10665 /**
10666 * Check if page is active.
10667 *
10668 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10669 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10670 *
10671 * @return {boolean} Page is active
10672 */
10673 OO.ui.PageLayout.prototype.isActive = function () {
10674 return this.active;
10675 };
10676
10677 /**
10678 * Get outline item.
10679 *
10680 * The outline item allows users to access the page from the booklet's outline
10681 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10682 *
10683 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10684 */
10685 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10686 return this.outlineItem;
10687 };
10688
10689 /**
10690 * Set or unset the outline item.
10691 *
10692 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10693 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10694 * level), use #setupOutlineItem instead of this method.
10695 *
10696 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10697 * @chainable
10698 */
10699 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10700 this.outlineItem = outlineItem || null;
10701 if ( outlineItem ) {
10702 this.setupOutlineItem();
10703 }
10704 return this;
10705 };
10706
10707 /**
10708 * Set up the outline item.
10709 *
10710 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10711 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10712 * the #setOutlineItem method instead.
10713 *
10714 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10715 * @chainable
10716 */
10717 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10718 return this;
10719 };
10720
10721 /**
10722 * Set the page to its 'active' state.
10723 *
10724 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10725 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10726 * context, setting the active state on a page does nothing.
10727 *
10728 * @param {boolean} value Page is active
10729 * @fires active
10730 */
10731 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10732 active = !!active;
10733
10734 if ( active !== this.active ) {
10735 this.active = active;
10736 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10737 this.emit( 'active', this.active );
10738 }
10739 };
10740
10741 /**
10742 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10743 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10744 * by setting the #continuous option to 'true'.
10745 *
10746 * @example
10747 * // A stack layout with two panels, configured to be displayed continously
10748 * var myStack = new OO.ui.StackLayout( {
10749 * items: [
10750 * new OO.ui.PanelLayout( {
10751 * $content: $( '<p>Panel One</p>' ),
10752 * padded: true,
10753 * framed: true
10754 * } ),
10755 * new OO.ui.PanelLayout( {
10756 * $content: $( '<p>Panel Two</p>' ),
10757 * padded: true,
10758 * framed: true
10759 * } )
10760 * ],
10761 * continuous: true
10762 * } );
10763 * $( 'body' ).append( myStack.$element );
10764 *
10765 * @class
10766 * @extends OO.ui.PanelLayout
10767 * @mixins OO.ui.mixin.GroupElement
10768 *
10769 * @constructor
10770 * @param {Object} [config] Configuration options
10771 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10772 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10773 */
10774 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10775 // Configuration initialization
10776 config = $.extend( { scrollable: true }, config );
10777
10778 // Parent constructor
10779 OO.ui.StackLayout.parent.call( this, config );
10780
10781 // Mixin constructors
10782 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10783
10784 // Properties
10785 this.currentItem = null;
10786 this.continuous = !!config.continuous;
10787
10788 // Initialization
10789 this.$element.addClass( 'oo-ui-stackLayout' );
10790 if ( this.continuous ) {
10791 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10792 }
10793 if ( Array.isArray( config.items ) ) {
10794 this.addItems( config.items );
10795 }
10796 };
10797
10798 /* Setup */
10799
10800 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10801 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
10802
10803 /* Events */
10804
10805 /**
10806 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10807 * {@link #clearItems cleared} or {@link #setItem displayed}.
10808 *
10809 * @event set
10810 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10811 */
10812
10813 /* Methods */
10814
10815 /**
10816 * Get the current panel.
10817 *
10818 * @return {OO.ui.Layout|null}
10819 */
10820 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10821 return this.currentItem;
10822 };
10823
10824 /**
10825 * Unset the current item.
10826 *
10827 * @private
10828 * @param {OO.ui.StackLayout} layout
10829 * @fires set
10830 */
10831 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10832 var prevItem = this.currentItem;
10833 if ( prevItem === null ) {
10834 return;
10835 }
10836
10837 this.currentItem = null;
10838 this.emit( 'set', null );
10839 };
10840
10841 /**
10842 * Add panel layouts to the stack layout.
10843 *
10844 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10845 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10846 * by the index.
10847 *
10848 * @param {OO.ui.Layout[]} items Panels to add
10849 * @param {number} [index] Index of the insertion point
10850 * @chainable
10851 */
10852 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10853 // Update the visibility
10854 this.updateHiddenState( items, this.currentItem );
10855
10856 // Mixin method
10857 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
10858
10859 if ( !this.currentItem && items.length ) {
10860 this.setItem( items[ 0 ] );
10861 }
10862
10863 return this;
10864 };
10865
10866 /**
10867 * Remove the specified panels from the stack layout.
10868 *
10869 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10870 * you may wish to use the #clearItems method instead.
10871 *
10872 * @param {OO.ui.Layout[]} items Panels to remove
10873 * @chainable
10874 * @fires set
10875 */
10876 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10877 // Mixin method
10878 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
10879
10880 if ( items.indexOf( this.currentItem ) !== -1 ) {
10881 if ( this.items.length ) {
10882 this.setItem( this.items[ 0 ] );
10883 } else {
10884 this.unsetCurrentItem();
10885 }
10886 }
10887
10888 return this;
10889 };
10890
10891 /**
10892 * Clear all panels from the stack layout.
10893 *
10894 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10895 * a subset of panels, use the #removeItems method.
10896 *
10897 * @chainable
10898 * @fires set
10899 */
10900 OO.ui.StackLayout.prototype.clearItems = function () {
10901 this.unsetCurrentItem();
10902 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
10903
10904 return this;
10905 };
10906
10907 /**
10908 * Show the specified panel.
10909 *
10910 * If another panel is currently displayed, it will be hidden.
10911 *
10912 * @param {OO.ui.Layout} item Panel to show
10913 * @chainable
10914 * @fires set
10915 */
10916 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10917 if ( item !== this.currentItem ) {
10918 this.updateHiddenState( this.items, item );
10919
10920 if ( this.items.indexOf( item ) !== -1 ) {
10921 this.currentItem = item;
10922 this.emit( 'set', item );
10923 } else {
10924 this.unsetCurrentItem();
10925 }
10926 }
10927
10928 return this;
10929 };
10930
10931 /**
10932 * Update the visibility of all items in case of non-continuous view.
10933 *
10934 * Ensure all items are hidden except for the selected one.
10935 * This method does nothing when the stack is continuous.
10936 *
10937 * @private
10938 * @param {OO.ui.Layout[]} items Item list iterate over
10939 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10940 */
10941 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10942 var i, len;
10943
10944 if ( !this.continuous ) {
10945 for ( i = 0, len = items.length; i < len; i++ ) {
10946 if ( !selectedItem || selectedItem !== items[ i ] ) {
10947 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10948 }
10949 }
10950 if ( selectedItem ) {
10951 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10952 }
10953 }
10954 };
10955
10956 /**
10957 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10958 * items), with small margins between them. Convenient when you need to put a number of block-level
10959 * widgets on a single line next to each other.
10960 *
10961 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10962 *
10963 * @example
10964 * // HorizontalLayout with a text input and a label
10965 * var layout = new OO.ui.HorizontalLayout( {
10966 * items: [
10967 * new OO.ui.LabelWidget( { label: 'Label' } ),
10968 * new OO.ui.TextInputWidget( { value: 'Text' } )
10969 * ]
10970 * } );
10971 * $( 'body' ).append( layout.$element );
10972 *
10973 * @class
10974 * @extends OO.ui.Layout
10975 * @mixins OO.ui.mixin.GroupElement
10976 *
10977 * @constructor
10978 * @param {Object} [config] Configuration options
10979 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10980 */
10981 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
10982 // Configuration initialization
10983 config = config || {};
10984
10985 // Parent constructor
10986 OO.ui.HorizontalLayout.parent.call( this, config );
10987
10988 // Mixin constructors
10989 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10990
10991 // Initialization
10992 this.$element.addClass( 'oo-ui-horizontalLayout' );
10993 if ( Array.isArray( config.items ) ) {
10994 this.addItems( config.items );
10995 }
10996 };
10997
10998 /* Setup */
10999
11000 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
11001 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11002
11003 /**
11004 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11005 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11006 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11007 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11008 * the tool.
11009 *
11010 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11011 * set up.
11012 *
11013 * @example
11014 * // Example of a BarToolGroup with two tools
11015 * var toolFactory = new OO.ui.ToolFactory();
11016 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11017 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11018 *
11019 * // We will be placing status text in this element when tools are used
11020 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11021 *
11022 * // Define the tools that we're going to place in our toolbar
11023 *
11024 * // Create a class inheriting from OO.ui.Tool
11025 * function PictureTool() {
11026 * PictureTool.parent.apply( this, arguments );
11027 * }
11028 * OO.inheritClass( PictureTool, OO.ui.Tool );
11029 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11030 * // of 'icon' and 'title' (displayed icon and text).
11031 * PictureTool.static.name = 'picture';
11032 * PictureTool.static.icon = 'picture';
11033 * PictureTool.static.title = 'Insert picture';
11034 * // Defines the action that will happen when this tool is selected (clicked).
11035 * PictureTool.prototype.onSelect = function () {
11036 * $area.text( 'Picture tool clicked!' );
11037 * // Never display this tool as "active" (selected).
11038 * this.setActive( false );
11039 * };
11040 * // Make this tool available in our toolFactory and thus our toolbar
11041 * toolFactory.register( PictureTool );
11042 *
11043 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11044 * // little popup window (a PopupWidget).
11045 * function HelpTool( toolGroup, config ) {
11046 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11047 * padded: true,
11048 * label: 'Help',
11049 * head: true
11050 * } }, config ) );
11051 * this.popup.$body.append( '<p>I am helpful!</p>' );
11052 * }
11053 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11054 * HelpTool.static.name = 'help';
11055 * HelpTool.static.icon = 'help';
11056 * HelpTool.static.title = 'Help';
11057 * toolFactory.register( HelpTool );
11058 *
11059 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11060 * // used once (but not all defined tools must be used).
11061 * toolbar.setup( [
11062 * {
11063 * // 'bar' tool groups display tools by icon only
11064 * type: 'bar',
11065 * include: [ 'picture', 'help' ]
11066 * }
11067 * ] );
11068 *
11069 * // Create some UI around the toolbar and place it in the document
11070 * var frame = new OO.ui.PanelLayout( {
11071 * expanded: false,
11072 * framed: true
11073 * } );
11074 * var contentFrame = new OO.ui.PanelLayout( {
11075 * expanded: false,
11076 * padded: true
11077 * } );
11078 * frame.$element.append(
11079 * toolbar.$element,
11080 * contentFrame.$element.append( $area )
11081 * );
11082 * $( 'body' ).append( frame.$element );
11083 *
11084 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11085 * // document.
11086 * toolbar.initialize();
11087 *
11088 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11089 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11090 *
11091 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11092 *
11093 * @class
11094 * @extends OO.ui.ToolGroup
11095 *
11096 * @constructor
11097 * @param {OO.ui.Toolbar} toolbar
11098 * @param {Object} [config] Configuration options
11099 */
11100 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11101 // Allow passing positional parameters inside the config object
11102 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11103 config = toolbar;
11104 toolbar = config.toolbar;
11105 }
11106
11107 // Parent constructor
11108 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11109
11110 // Initialization
11111 this.$element.addClass( 'oo-ui-barToolGroup' );
11112 };
11113
11114 /* Setup */
11115
11116 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11117
11118 /* Static Properties */
11119
11120 OO.ui.BarToolGroup.static.titleTooltips = true;
11121
11122 OO.ui.BarToolGroup.static.accelTooltips = true;
11123
11124 OO.ui.BarToolGroup.static.name = 'bar';
11125
11126 /**
11127 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11128 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11129 * optional icon and label. This class can be used for other base classes that also use this functionality.
11130 *
11131 * @abstract
11132 * @class
11133 * @extends OO.ui.ToolGroup
11134 * @mixins OO.ui.mixin.IconElement
11135 * @mixins OO.ui.mixin.IndicatorElement
11136 * @mixins OO.ui.mixin.LabelElement
11137 * @mixins OO.ui.mixin.TitledElement
11138 * @mixins OO.ui.mixin.ClippableElement
11139 * @mixins OO.ui.mixin.TabIndexedElement
11140 *
11141 * @constructor
11142 * @param {OO.ui.Toolbar} toolbar
11143 * @param {Object} [config] Configuration options
11144 * @cfg {string} [header] Text to display at the top of the popup
11145 */
11146 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11147 // Allow passing positional parameters inside the config object
11148 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11149 config = toolbar;
11150 toolbar = config.toolbar;
11151 }
11152
11153 // Configuration initialization
11154 config = config || {};
11155
11156 // Parent constructor
11157 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11158
11159 // Properties
11160 this.active = false;
11161 this.dragging = false;
11162 this.onBlurHandler = this.onBlur.bind( this );
11163 this.$handle = $( '<span>' );
11164
11165 // Mixin constructors
11166 OO.ui.mixin.IconElement.call( this, config );
11167 OO.ui.mixin.IndicatorElement.call( this, config );
11168 OO.ui.mixin.LabelElement.call( this, config );
11169 OO.ui.mixin.TitledElement.call( this, config );
11170 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11171 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11172
11173 // Events
11174 this.$handle.on( {
11175 keydown: this.onHandleMouseKeyDown.bind( this ),
11176 keyup: this.onHandleMouseKeyUp.bind( this ),
11177 mousedown: this.onHandleMouseKeyDown.bind( this ),
11178 mouseup: this.onHandleMouseKeyUp.bind( this )
11179 } );
11180
11181 // Initialization
11182 this.$handle
11183 .addClass( 'oo-ui-popupToolGroup-handle' )
11184 .append( this.$icon, this.$label, this.$indicator );
11185 // If the pop-up should have a header, add it to the top of the toolGroup.
11186 // Note: If this feature is useful for other widgets, we could abstract it into an
11187 // OO.ui.HeaderedElement mixin constructor.
11188 if ( config.header !== undefined ) {
11189 this.$group
11190 .prepend( $( '<span>' )
11191 .addClass( 'oo-ui-popupToolGroup-header' )
11192 .text( config.header )
11193 );
11194 }
11195 this.$element
11196 .addClass( 'oo-ui-popupToolGroup' )
11197 .prepend( this.$handle );
11198 };
11199
11200 /* Setup */
11201
11202 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11203 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11204 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11205 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11206 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11207 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11208 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11209
11210 /* Methods */
11211
11212 /**
11213 * @inheritdoc
11214 */
11215 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11216 // Parent method
11217 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11218
11219 if ( this.isDisabled() && this.isElementAttached() ) {
11220 this.setActive( false );
11221 }
11222 };
11223
11224 /**
11225 * Handle focus being lost.
11226 *
11227 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11228 *
11229 * @protected
11230 * @param {jQuery.Event} e Mouse up or key up event
11231 */
11232 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11233 // Only deactivate when clicking outside the dropdown element
11234 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11235 this.setActive( false );
11236 }
11237 };
11238
11239 /**
11240 * @inheritdoc
11241 */
11242 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11243 // Only close toolgroup when a tool was actually selected
11244 if (
11245 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11246 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11247 ) {
11248 this.setActive( false );
11249 }
11250 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11251 };
11252
11253 /**
11254 * Handle mouse up and key up events.
11255 *
11256 * @protected
11257 * @param {jQuery.Event} e Mouse up or key up event
11258 */
11259 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11260 if (
11261 !this.isDisabled() &&
11262 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11263 ) {
11264 return false;
11265 }
11266 };
11267
11268 /**
11269 * Handle mouse down and key down events.
11270 *
11271 * @protected
11272 * @param {jQuery.Event} e Mouse down or key down event
11273 */
11274 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11275 if (
11276 !this.isDisabled() &&
11277 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11278 ) {
11279 this.setActive( !this.active );
11280 return false;
11281 }
11282 };
11283
11284 /**
11285 * Switch into 'active' mode.
11286 *
11287 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11288 * deactivation.
11289 */
11290 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11291 var containerWidth, containerLeft;
11292 value = !!value;
11293 if ( this.active !== value ) {
11294 this.active = value;
11295 if ( value ) {
11296 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11297 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11298
11299 this.$clippable.css( 'left', '' );
11300 // Try anchoring the popup to the left first
11301 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11302 this.toggleClipping( true );
11303 if ( this.isClippedHorizontally() ) {
11304 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11305 this.toggleClipping( false );
11306 this.$element
11307 .removeClass( 'oo-ui-popupToolGroup-left' )
11308 .addClass( 'oo-ui-popupToolGroup-right' );
11309 this.toggleClipping( true );
11310 }
11311 if ( this.isClippedHorizontally() ) {
11312 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11313 containerWidth = this.$clippableContainer.width();
11314 containerLeft = this.$clippableContainer.offset().left;
11315
11316 this.toggleClipping( false );
11317 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11318
11319 this.$clippable.css( {
11320 left: -( this.$element.offset().left - containerLeft ),
11321 width: containerWidth
11322 } );
11323 }
11324 } else {
11325 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11326 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11327 this.$element.removeClass(
11328 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11329 );
11330 this.toggleClipping( false );
11331 }
11332 }
11333 };
11334
11335 /**
11336 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11337 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11338 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11339 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11340 * with a label, icon, indicator, header, and title.
11341 *
11342 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11343 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11344 * users to collapse the list again.
11345 *
11346 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11347 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11348 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11349 *
11350 * @example
11351 * // Example of a ListToolGroup
11352 * var toolFactory = new OO.ui.ToolFactory();
11353 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11354 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11355 *
11356 * // Configure and register two tools
11357 * function SettingsTool() {
11358 * SettingsTool.parent.apply( this, arguments );
11359 * }
11360 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11361 * SettingsTool.static.name = 'settings';
11362 * SettingsTool.static.icon = 'settings';
11363 * SettingsTool.static.title = 'Change settings';
11364 * SettingsTool.prototype.onSelect = function () {
11365 * this.setActive( false );
11366 * };
11367 * toolFactory.register( SettingsTool );
11368 * // Register two more tools, nothing interesting here
11369 * function StuffTool() {
11370 * StuffTool.parent.apply( this, arguments );
11371 * }
11372 * OO.inheritClass( StuffTool, OO.ui.Tool );
11373 * StuffTool.static.name = 'stuff';
11374 * StuffTool.static.icon = 'ellipsis';
11375 * StuffTool.static.title = 'Change the world';
11376 * StuffTool.prototype.onSelect = function () {
11377 * this.setActive( false );
11378 * };
11379 * toolFactory.register( StuffTool );
11380 * toolbar.setup( [
11381 * {
11382 * // Configurations for list toolgroup.
11383 * type: 'list',
11384 * label: 'ListToolGroup',
11385 * indicator: 'down',
11386 * icon: 'picture',
11387 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11388 * header: 'This is the header',
11389 * include: [ 'settings', 'stuff' ],
11390 * allowCollapse: ['stuff']
11391 * }
11392 * ] );
11393 *
11394 * // Create some UI around the toolbar and place it in the document
11395 * var frame = new OO.ui.PanelLayout( {
11396 * expanded: false,
11397 * framed: true
11398 * } );
11399 * frame.$element.append(
11400 * toolbar.$element
11401 * );
11402 * $( 'body' ).append( frame.$element );
11403 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11404 * toolbar.initialize();
11405 *
11406 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11407 *
11408 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11409 *
11410 * @class
11411 * @extends OO.ui.PopupToolGroup
11412 *
11413 * @constructor
11414 * @param {OO.ui.Toolbar} toolbar
11415 * @param {Object} [config] Configuration options
11416 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11417 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11418 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11419 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11420 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11421 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11422 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11423 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11424 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11425 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11426 */
11427 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11428 // Allow passing positional parameters inside the config object
11429 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11430 config = toolbar;
11431 toolbar = config.toolbar;
11432 }
11433
11434 // Configuration initialization
11435 config = config || {};
11436
11437 // Properties (must be set before parent constructor, which calls #populate)
11438 this.allowCollapse = config.allowCollapse;
11439 this.forceExpand = config.forceExpand;
11440 this.expanded = config.expanded !== undefined ? config.expanded : false;
11441 this.collapsibleTools = [];
11442
11443 // Parent constructor
11444 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11445
11446 // Initialization
11447 this.$element.addClass( 'oo-ui-listToolGroup' );
11448 };
11449
11450 /* Setup */
11451
11452 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11453
11454 /* Static Properties */
11455
11456 OO.ui.ListToolGroup.static.name = 'list';
11457
11458 /* Methods */
11459
11460 /**
11461 * @inheritdoc
11462 */
11463 OO.ui.ListToolGroup.prototype.populate = function () {
11464 var i, len, allowCollapse = [];
11465
11466 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11467
11468 // Update the list of collapsible tools
11469 if ( this.allowCollapse !== undefined ) {
11470 allowCollapse = this.allowCollapse;
11471 } else if ( this.forceExpand !== undefined ) {
11472 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11473 }
11474
11475 this.collapsibleTools = [];
11476 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11477 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11478 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11479 }
11480 }
11481
11482 // Keep at the end, even when tools are added
11483 this.$group.append( this.getExpandCollapseTool().$element );
11484
11485 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11486 this.updateCollapsibleState();
11487 };
11488
11489 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11490 var ExpandCollapseTool;
11491 if ( this.expandCollapseTool === undefined ) {
11492 ExpandCollapseTool = function () {
11493 ExpandCollapseTool.parent.apply( this, arguments );
11494 };
11495
11496 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11497
11498 ExpandCollapseTool.prototype.onSelect = function () {
11499 this.toolGroup.expanded = !this.toolGroup.expanded;
11500 this.toolGroup.updateCollapsibleState();
11501 this.setActive( false );
11502 };
11503 ExpandCollapseTool.prototype.onUpdateState = function () {
11504 // Do nothing. Tool interface requires an implementation of this function.
11505 };
11506
11507 ExpandCollapseTool.static.name = 'more-fewer';
11508
11509 this.expandCollapseTool = new ExpandCollapseTool( this );
11510 }
11511 return this.expandCollapseTool;
11512 };
11513
11514 /**
11515 * @inheritdoc
11516 */
11517 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11518 // Do not close the popup when the user wants to show more/fewer tools
11519 if (
11520 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11521 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11522 ) {
11523 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11524 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11525 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11526 } else {
11527 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11528 }
11529 };
11530
11531 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11532 var i, len;
11533
11534 this.getExpandCollapseTool()
11535 .setIcon( this.expanded ? 'collapse' : 'expand' )
11536 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11537
11538 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11539 this.collapsibleTools[ i ].toggle( this.expanded );
11540 }
11541 };
11542
11543 /**
11544 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11545 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11546 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11547 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11548 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11549 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11550 *
11551 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11552 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11553 * a MenuToolGroup is used.
11554 *
11555 * @example
11556 * // Example of a MenuToolGroup
11557 * var toolFactory = new OO.ui.ToolFactory();
11558 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11559 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11560 *
11561 * // We will be placing status text in this element when tools are used
11562 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11563 *
11564 * // Define the tools that we're going to place in our toolbar
11565 *
11566 * function SettingsTool() {
11567 * SettingsTool.parent.apply( this, arguments );
11568 * this.reallyActive = false;
11569 * }
11570 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11571 * SettingsTool.static.name = 'settings';
11572 * SettingsTool.static.icon = 'settings';
11573 * SettingsTool.static.title = 'Change settings';
11574 * SettingsTool.prototype.onSelect = function () {
11575 * $area.text( 'Settings tool clicked!' );
11576 * // Toggle the active state on each click
11577 * this.reallyActive = !this.reallyActive;
11578 * this.setActive( this.reallyActive );
11579 * // To update the menu label
11580 * this.toolbar.emit( 'updateState' );
11581 * };
11582 * SettingsTool.prototype.onUpdateState = function () {
11583 * };
11584 * toolFactory.register( SettingsTool );
11585 *
11586 * function StuffTool() {
11587 * StuffTool.parent.apply( this, arguments );
11588 * this.reallyActive = false;
11589 * }
11590 * OO.inheritClass( StuffTool, OO.ui.Tool );
11591 * StuffTool.static.name = 'stuff';
11592 * StuffTool.static.icon = 'ellipsis';
11593 * StuffTool.static.title = 'More stuff';
11594 * StuffTool.prototype.onSelect = function () {
11595 * $area.text( 'More stuff tool clicked!' );
11596 * // Toggle the active state on each click
11597 * this.reallyActive = !this.reallyActive;
11598 * this.setActive( this.reallyActive );
11599 * // To update the menu label
11600 * this.toolbar.emit( 'updateState' );
11601 * };
11602 * StuffTool.prototype.onUpdateState = function () {
11603 * };
11604 * toolFactory.register( StuffTool );
11605 *
11606 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11607 * // used once (but not all defined tools must be used).
11608 * toolbar.setup( [
11609 * {
11610 * type: 'menu',
11611 * header: 'This is the (optional) header',
11612 * title: 'This is the (optional) title',
11613 * indicator: 'down',
11614 * include: [ 'settings', 'stuff' ]
11615 * }
11616 * ] );
11617 *
11618 * // Create some UI around the toolbar and place it in the document
11619 * var frame = new OO.ui.PanelLayout( {
11620 * expanded: false,
11621 * framed: true
11622 * } );
11623 * var contentFrame = new OO.ui.PanelLayout( {
11624 * expanded: false,
11625 * padded: true
11626 * } );
11627 * frame.$element.append(
11628 * toolbar.$element,
11629 * contentFrame.$element.append( $area )
11630 * );
11631 * $( 'body' ).append( frame.$element );
11632 *
11633 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11634 * // document.
11635 * toolbar.initialize();
11636 * toolbar.emit( 'updateState' );
11637 *
11638 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11639 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11640 *
11641 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11642 *
11643 * @class
11644 * @extends OO.ui.PopupToolGroup
11645 *
11646 * @constructor
11647 * @param {OO.ui.Toolbar} toolbar
11648 * @param {Object} [config] Configuration options
11649 */
11650 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11651 // Allow passing positional parameters inside the config object
11652 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11653 config = toolbar;
11654 toolbar = config.toolbar;
11655 }
11656
11657 // Configuration initialization
11658 config = config || {};
11659
11660 // Parent constructor
11661 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11662
11663 // Events
11664 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11665
11666 // Initialization
11667 this.$element.addClass( 'oo-ui-menuToolGroup' );
11668 };
11669
11670 /* Setup */
11671
11672 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11673
11674 /* Static Properties */
11675
11676 OO.ui.MenuToolGroup.static.name = 'menu';
11677
11678 /* Methods */
11679
11680 /**
11681 * Handle the toolbar state being updated.
11682 *
11683 * When the state changes, the title of each active item in the menu will be joined together and
11684 * used as a label for the group. The label will be empty if none of the items are active.
11685 *
11686 * @private
11687 */
11688 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11689 var name,
11690 labelTexts = [];
11691
11692 for ( name in this.tools ) {
11693 if ( this.tools[ name ].isActive() ) {
11694 labelTexts.push( this.tools[ name ].getTitle() );
11695 }
11696 }
11697
11698 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11699 };
11700
11701 /**
11702 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11703 * 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
11704 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11705 *
11706 * // Example of a popup tool. When selected, a popup tool displays
11707 * // a popup window.
11708 * function HelpTool( toolGroup, config ) {
11709 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11710 * padded: true,
11711 * label: 'Help',
11712 * head: true
11713 * } }, config ) );
11714 * this.popup.$body.append( '<p>I am helpful!</p>' );
11715 * };
11716 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11717 * HelpTool.static.name = 'help';
11718 * HelpTool.static.icon = 'help';
11719 * HelpTool.static.title = 'Help';
11720 * toolFactory.register( HelpTool );
11721 *
11722 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11723 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11724 *
11725 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11726 *
11727 * @abstract
11728 * @class
11729 * @extends OO.ui.Tool
11730 * @mixins OO.ui.mixin.PopupElement
11731 *
11732 * @constructor
11733 * @param {OO.ui.ToolGroup} toolGroup
11734 * @param {Object} [config] Configuration options
11735 */
11736 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11737 // Allow passing positional parameters inside the config object
11738 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11739 config = toolGroup;
11740 toolGroup = config.toolGroup;
11741 }
11742
11743 // Parent constructor
11744 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11745
11746 // Mixin constructors
11747 OO.ui.mixin.PopupElement.call( this, config );
11748
11749 // Initialization
11750 this.$element
11751 .addClass( 'oo-ui-popupTool' )
11752 .append( this.popup.$element );
11753 };
11754
11755 /* Setup */
11756
11757 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11758 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11759
11760 /* Methods */
11761
11762 /**
11763 * Handle the tool being selected.
11764 *
11765 * @inheritdoc
11766 */
11767 OO.ui.PopupTool.prototype.onSelect = function () {
11768 if ( !this.isDisabled() ) {
11769 this.popup.toggle();
11770 }
11771 this.setActive( false );
11772 return false;
11773 };
11774
11775 /**
11776 * Handle the toolbar state being updated.
11777 *
11778 * @inheritdoc
11779 */
11780 OO.ui.PopupTool.prototype.onUpdateState = function () {
11781 this.setActive( false );
11782 };
11783
11784 /**
11785 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11786 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11787 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11788 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11789 * when the ToolGroupTool is selected.
11790 *
11791 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11792 *
11793 * function SettingsTool() {
11794 * SettingsTool.parent.apply( this, arguments );
11795 * };
11796 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11797 * SettingsTool.static.name = 'settings';
11798 * SettingsTool.static.title = 'Change settings';
11799 * SettingsTool.static.groupConfig = {
11800 * icon: 'settings',
11801 * label: 'ToolGroupTool',
11802 * include: [ 'setting1', 'setting2' ]
11803 * };
11804 * toolFactory.register( SettingsTool );
11805 *
11806 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11807 *
11808 * Please note that this implementation is subject to change per [T74159] [2].
11809 *
11810 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11811 * [2]: https://phabricator.wikimedia.org/T74159
11812 *
11813 * @abstract
11814 * @class
11815 * @extends OO.ui.Tool
11816 *
11817 * @constructor
11818 * @param {OO.ui.ToolGroup} toolGroup
11819 * @param {Object} [config] Configuration options
11820 */
11821 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
11822 // Allow passing positional parameters inside the config object
11823 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11824 config = toolGroup;
11825 toolGroup = config.toolGroup;
11826 }
11827
11828 // Parent constructor
11829 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
11830
11831 // Properties
11832 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
11833
11834 // Events
11835 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
11836
11837 // Initialization
11838 this.$link.remove();
11839 this.$element
11840 .addClass( 'oo-ui-toolGroupTool' )
11841 .append( this.innerToolGroup.$element );
11842 };
11843
11844 /* Setup */
11845
11846 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
11847
11848 /* Static Properties */
11849
11850 /**
11851 * Toolgroup configuration.
11852 *
11853 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11854 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11855 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11856 *
11857 * @property {Object.<string,Array>}
11858 */
11859 OO.ui.ToolGroupTool.static.groupConfig = {};
11860
11861 /* Methods */
11862
11863 /**
11864 * Handle the tool being selected.
11865 *
11866 * @inheritdoc
11867 */
11868 OO.ui.ToolGroupTool.prototype.onSelect = function () {
11869 this.innerToolGroup.setActive( !this.innerToolGroup.active );
11870 return false;
11871 };
11872
11873 /**
11874 * Synchronize disabledness state of the tool with the inner toolgroup.
11875 *
11876 * @private
11877 * @param {boolean} disabled Element is disabled
11878 */
11879 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
11880 this.setDisabled( disabled );
11881 };
11882
11883 /**
11884 * Handle the toolbar state being updated.
11885 *
11886 * @inheritdoc
11887 */
11888 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
11889 this.setActive( false );
11890 };
11891
11892 /**
11893 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11894 *
11895 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11896 * more information.
11897 * @return {OO.ui.ListToolGroup}
11898 */
11899 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
11900 if ( group.include === '*' ) {
11901 // Apply defaults to catch-all groups
11902 if ( group.label === undefined ) {
11903 group.label = OO.ui.msg( 'ooui-toolbar-more' );
11904 }
11905 }
11906
11907 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
11908 };
11909
11910 /**
11911 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11912 *
11913 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11914 *
11915 * @private
11916 * @abstract
11917 * @class
11918 * @extends OO.ui.mixin.GroupElement
11919 *
11920 * @constructor
11921 * @param {Object} [config] Configuration options
11922 */
11923 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
11924 // Parent constructor
11925 OO.ui.mixin.GroupWidget.parent.call( this, config );
11926 };
11927
11928 /* Setup */
11929
11930 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
11931
11932 /* Methods */
11933
11934 /**
11935 * Set the disabled state of the widget.
11936 *
11937 * This will also update the disabled state of child widgets.
11938 *
11939 * @param {boolean} disabled Disable widget
11940 * @chainable
11941 */
11942 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
11943 var i, len;
11944
11945 // Parent method
11946 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11947 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
11948
11949 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11950 if ( this.items ) {
11951 for ( i = 0, len = this.items.length; i < len; i++ ) {
11952 this.items[ i ].updateDisabled();
11953 }
11954 }
11955
11956 return this;
11957 };
11958
11959 /**
11960 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11961 *
11962 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11963 * allows bidirectional communication.
11964 *
11965 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11966 *
11967 * @private
11968 * @abstract
11969 * @class
11970 *
11971 * @constructor
11972 */
11973 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
11974 //
11975 };
11976
11977 /* Methods */
11978
11979 /**
11980 * Check if widget is disabled.
11981 *
11982 * Checks parent if present, making disabled state inheritable.
11983 *
11984 * @return {boolean} Widget is disabled
11985 */
11986 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
11987 return this.disabled ||
11988 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
11989 };
11990
11991 /**
11992 * Set group element is in.
11993 *
11994 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11995 * @chainable
11996 */
11997 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
11998 // Parent method
11999 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12000 OO.ui.Element.prototype.setElementGroup.call( this, group );
12001
12002 // Initialize item disabled states
12003 this.updateDisabled();
12004
12005 return this;
12006 };
12007
12008 /**
12009 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12010 * Controls include moving items up and down, removing items, and adding different kinds of items.
12011 *
12012 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12013 *
12014 * @class
12015 * @extends OO.ui.Widget
12016 * @mixins OO.ui.mixin.GroupElement
12017 * @mixins OO.ui.mixin.IconElement
12018 *
12019 * @constructor
12020 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12021 * @param {Object} [config] Configuration options
12022 * @cfg {Object} [abilities] List of abilties
12023 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12024 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12025 */
12026 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12027 // Allow passing positional parameters inside the config object
12028 if ( OO.isPlainObject( outline ) && config === undefined ) {
12029 config = outline;
12030 outline = config.outline;
12031 }
12032
12033 // Configuration initialization
12034 config = $.extend( { icon: 'add' }, config );
12035
12036 // Parent constructor
12037 OO.ui.OutlineControlsWidget.parent.call( this, config );
12038
12039 // Mixin constructors
12040 OO.ui.mixin.GroupElement.call( this, config );
12041 OO.ui.mixin.IconElement.call( this, config );
12042
12043 // Properties
12044 this.outline = outline;
12045 this.$movers = $( '<div>' );
12046 this.upButton = new OO.ui.ButtonWidget( {
12047 framed: false,
12048 icon: 'collapse',
12049 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12050 } );
12051 this.downButton = new OO.ui.ButtonWidget( {
12052 framed: false,
12053 icon: 'expand',
12054 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12055 } );
12056 this.removeButton = new OO.ui.ButtonWidget( {
12057 framed: false,
12058 icon: 'remove',
12059 title: OO.ui.msg( 'ooui-outline-control-remove' )
12060 } );
12061 this.abilities = { move: true, remove: true };
12062
12063 // Events
12064 outline.connect( this, {
12065 select: 'onOutlineChange',
12066 add: 'onOutlineChange',
12067 remove: 'onOutlineChange'
12068 } );
12069 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12070 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12071 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12072
12073 // Initialization
12074 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12075 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12076 this.$movers
12077 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12078 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12079 this.$element.append( this.$icon, this.$group, this.$movers );
12080 this.setAbilities( config.abilities || {} );
12081 };
12082
12083 /* Setup */
12084
12085 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12086 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12087 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12088
12089 /* Events */
12090
12091 /**
12092 * @event move
12093 * @param {number} places Number of places to move
12094 */
12095
12096 /**
12097 * @event remove
12098 */
12099
12100 /* Methods */
12101
12102 /**
12103 * Set abilities.
12104 *
12105 * @param {Object} abilities List of abilties
12106 * @param {boolean} [abilities.move] Allow moving movable items
12107 * @param {boolean} [abilities.remove] Allow removing removable items
12108 */
12109 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12110 var ability;
12111
12112 for ( ability in this.abilities ) {
12113 if ( abilities[ ability ] !== undefined ) {
12114 this.abilities[ ability ] = !!abilities[ ability ];
12115 }
12116 }
12117
12118 this.onOutlineChange();
12119 };
12120
12121 /**
12122 *
12123 * @private
12124 * Handle outline change events.
12125 */
12126 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12127 var i, len, firstMovable, lastMovable,
12128 items = this.outline.getItems(),
12129 selectedItem = this.outline.getSelectedItem(),
12130 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12131 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12132
12133 if ( movable ) {
12134 i = -1;
12135 len = items.length;
12136 while ( ++i < len ) {
12137 if ( items[ i ].isMovable() ) {
12138 firstMovable = items[ i ];
12139 break;
12140 }
12141 }
12142 i = len;
12143 while ( i-- ) {
12144 if ( items[ i ].isMovable() ) {
12145 lastMovable = items[ i ];
12146 break;
12147 }
12148 }
12149 }
12150 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12151 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12152 this.removeButton.setDisabled( !removable );
12153 };
12154
12155 /**
12156 * ToggleWidget implements basic behavior of widgets with an on/off state.
12157 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12158 *
12159 * @abstract
12160 * @class
12161 * @extends OO.ui.Widget
12162 *
12163 * @constructor
12164 * @param {Object} [config] Configuration options
12165 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12166 * By default, the toggle is in the 'off' state.
12167 */
12168 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12169 // Configuration initialization
12170 config = config || {};
12171
12172 // Parent constructor
12173 OO.ui.ToggleWidget.parent.call( this, config );
12174
12175 // Properties
12176 this.value = null;
12177
12178 // Initialization
12179 this.$element.addClass( 'oo-ui-toggleWidget' );
12180 this.setValue( !!config.value );
12181 };
12182
12183 /* Setup */
12184
12185 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12186
12187 /* Events */
12188
12189 /**
12190 * @event change
12191 *
12192 * A change event is emitted when the on/off state of the toggle changes.
12193 *
12194 * @param {boolean} value Value representing the new state of the toggle
12195 */
12196
12197 /* Methods */
12198
12199 /**
12200 * Get the value representing the toggle’s state.
12201 *
12202 * @return {boolean} The on/off state of the toggle
12203 */
12204 OO.ui.ToggleWidget.prototype.getValue = function () {
12205 return this.value;
12206 };
12207
12208 /**
12209 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12210 *
12211 * @param {boolean} value The state of the toggle
12212 * @fires change
12213 * @chainable
12214 */
12215 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12216 value = !!value;
12217 if ( this.value !== value ) {
12218 this.value = value;
12219 this.emit( 'change', value );
12220 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12221 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12222 this.$element.attr( 'aria-checked', value.toString() );
12223 }
12224 return this;
12225 };
12226
12227 /**
12228 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12229 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12230 * removed, and cleared from the group.
12231 *
12232 * @example
12233 * // Example: A ButtonGroupWidget with two buttons
12234 * var button1 = new OO.ui.PopupButtonWidget( {
12235 * label: 'Select a category',
12236 * icon: 'menu',
12237 * popup: {
12238 * $content: $( '<p>List of categories...</p>' ),
12239 * padded: true,
12240 * align: 'left'
12241 * }
12242 * } );
12243 * var button2 = new OO.ui.ButtonWidget( {
12244 * label: 'Add item'
12245 * });
12246 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12247 * items: [button1, button2]
12248 * } );
12249 * $( 'body' ).append( buttonGroup.$element );
12250 *
12251 * @class
12252 * @extends OO.ui.Widget
12253 * @mixins OO.ui.mixin.GroupElement
12254 *
12255 * @constructor
12256 * @param {Object} [config] Configuration options
12257 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12258 */
12259 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12260 // Configuration initialization
12261 config = config || {};
12262
12263 // Parent constructor
12264 OO.ui.ButtonGroupWidget.parent.call( this, config );
12265
12266 // Mixin constructors
12267 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12268
12269 // Initialization
12270 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12271 if ( Array.isArray( config.items ) ) {
12272 this.addItems( config.items );
12273 }
12274 };
12275
12276 /* Setup */
12277
12278 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12279 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12280
12281 /**
12282 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12283 * feels, and functionality can be customized via the class’s configuration options
12284 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12285 * and examples.
12286 *
12287 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12288 *
12289 * @example
12290 * // A button widget
12291 * var button = new OO.ui.ButtonWidget( {
12292 * label: 'Button with Icon',
12293 * icon: 'remove',
12294 * iconTitle: 'Remove'
12295 * } );
12296 * $( 'body' ).append( button.$element );
12297 *
12298 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12299 *
12300 * @class
12301 * @extends OO.ui.Widget
12302 * @mixins OO.ui.mixin.ButtonElement
12303 * @mixins OO.ui.mixin.IconElement
12304 * @mixins OO.ui.mixin.IndicatorElement
12305 * @mixins OO.ui.mixin.LabelElement
12306 * @mixins OO.ui.mixin.TitledElement
12307 * @mixins OO.ui.mixin.FlaggedElement
12308 * @mixins OO.ui.mixin.TabIndexedElement
12309 * @mixins OO.ui.mixin.AccessKeyedElement
12310 *
12311 * @constructor
12312 * @param {Object} [config] Configuration options
12313 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12314 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12315 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12316 */
12317 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12318 // Configuration initialization
12319 config = config || {};
12320
12321 // Parent constructor
12322 OO.ui.ButtonWidget.parent.call( this, config );
12323
12324 // Mixin constructors
12325 OO.ui.mixin.ButtonElement.call( this, config );
12326 OO.ui.mixin.IconElement.call( this, config );
12327 OO.ui.mixin.IndicatorElement.call( this, config );
12328 OO.ui.mixin.LabelElement.call( this, config );
12329 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12330 OO.ui.mixin.FlaggedElement.call( this, config );
12331 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12332 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12333
12334 // Properties
12335 this.href = null;
12336 this.target = null;
12337 this.noFollow = false;
12338
12339 // Events
12340 this.connect( this, { disable: 'onDisable' } );
12341
12342 // Initialization
12343 this.$button.append( this.$icon, this.$label, this.$indicator );
12344 this.$element
12345 .addClass( 'oo-ui-buttonWidget' )
12346 .append( this.$button );
12347 this.setHref( config.href );
12348 this.setTarget( config.target );
12349 this.setNoFollow( config.noFollow );
12350 };
12351
12352 /* Setup */
12353
12354 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12355 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12356 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12357 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12358 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12359 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12360 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12361 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12362 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12363
12364 /* Methods */
12365
12366 /**
12367 * @inheritdoc
12368 */
12369 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12370 if ( !this.isDisabled() ) {
12371 // Remove the tab-index while the button is down to prevent the button from stealing focus
12372 this.$button.removeAttr( 'tabindex' );
12373 }
12374
12375 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12376 };
12377
12378 /**
12379 * @inheritdoc
12380 */
12381 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12382 if ( !this.isDisabled() ) {
12383 // Restore the tab-index after the button is up to restore the button's accessibility
12384 this.$button.attr( 'tabindex', this.tabIndex );
12385 }
12386
12387 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12388 };
12389
12390 /**
12391 * Get hyperlink location.
12392 *
12393 * @return {string} Hyperlink location
12394 */
12395 OO.ui.ButtonWidget.prototype.getHref = function () {
12396 return this.href;
12397 };
12398
12399 /**
12400 * Get hyperlink target.
12401 *
12402 * @return {string} Hyperlink target
12403 */
12404 OO.ui.ButtonWidget.prototype.getTarget = function () {
12405 return this.target;
12406 };
12407
12408 /**
12409 * Get search engine traversal hint.
12410 *
12411 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12412 */
12413 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12414 return this.noFollow;
12415 };
12416
12417 /**
12418 * Set hyperlink location.
12419 *
12420 * @param {string|null} href Hyperlink location, null to remove
12421 */
12422 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12423 href = typeof href === 'string' ? href : null;
12424 if ( href !== null ) {
12425 if ( !OO.ui.isSafeUrl( href ) ) {
12426 throw new Error( 'Potentially unsafe href provided: ' + href );
12427 }
12428
12429 }
12430
12431 if ( href !== this.href ) {
12432 this.href = href;
12433 this.updateHref();
12434 }
12435
12436 return this;
12437 };
12438
12439 /**
12440 * Update the `href` attribute, in case of changes to href or
12441 * disabled state.
12442 *
12443 * @private
12444 * @chainable
12445 */
12446 OO.ui.ButtonWidget.prototype.updateHref = function () {
12447 if ( this.href !== null && !this.isDisabled() ) {
12448 this.$button.attr( 'href', this.href );
12449 } else {
12450 this.$button.removeAttr( 'href' );
12451 }
12452
12453 return this;
12454 };
12455
12456 /**
12457 * Handle disable events.
12458 *
12459 * @private
12460 * @param {boolean} disabled Element is disabled
12461 */
12462 OO.ui.ButtonWidget.prototype.onDisable = function () {
12463 this.updateHref();
12464 };
12465
12466 /**
12467 * Set hyperlink target.
12468 *
12469 * @param {string|null} target Hyperlink target, null to remove
12470 */
12471 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12472 target = typeof target === 'string' ? target : null;
12473
12474 if ( target !== this.target ) {
12475 this.target = target;
12476 if ( target !== null ) {
12477 this.$button.attr( 'target', target );
12478 } else {
12479 this.$button.removeAttr( 'target' );
12480 }
12481 }
12482
12483 return this;
12484 };
12485
12486 /**
12487 * Set search engine traversal hint.
12488 *
12489 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12490 */
12491 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12492 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12493
12494 if ( noFollow !== this.noFollow ) {
12495 this.noFollow = noFollow;
12496 if ( noFollow ) {
12497 this.$button.attr( 'rel', 'nofollow' );
12498 } else {
12499 this.$button.removeAttr( 'rel' );
12500 }
12501 }
12502
12503 return this;
12504 };
12505
12506 /**
12507 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12508 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12509 * of the actions.
12510 *
12511 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12512 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12513 * and examples.
12514 *
12515 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12516 *
12517 * @class
12518 * @extends OO.ui.ButtonWidget
12519 * @mixins OO.ui.mixin.PendingElement
12520 *
12521 * @constructor
12522 * @param {Object} [config] Configuration options
12523 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12524 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12525 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12526 * for more information about setting modes.
12527 * @cfg {boolean} [framed=false] Render the action button with a frame
12528 */
12529 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12530 // Configuration initialization
12531 config = $.extend( { framed: false }, config );
12532
12533 // Parent constructor
12534 OO.ui.ActionWidget.parent.call( this, config );
12535
12536 // Mixin constructors
12537 OO.ui.mixin.PendingElement.call( this, config );
12538
12539 // Properties
12540 this.action = config.action || '';
12541 this.modes = config.modes || [];
12542 this.width = 0;
12543 this.height = 0;
12544
12545 // Initialization
12546 this.$element.addClass( 'oo-ui-actionWidget' );
12547 };
12548
12549 /* Setup */
12550
12551 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12552 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12553
12554 /* Events */
12555
12556 /**
12557 * A resize event is emitted when the size of the widget changes.
12558 *
12559 * @event resize
12560 */
12561
12562 /* Methods */
12563
12564 /**
12565 * Check if the action is configured to be available in the specified `mode`.
12566 *
12567 * @param {string} mode Name of mode
12568 * @return {boolean} The action is configured with the mode
12569 */
12570 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12571 return this.modes.indexOf( mode ) !== -1;
12572 };
12573
12574 /**
12575 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12576 *
12577 * @return {string}
12578 */
12579 OO.ui.ActionWidget.prototype.getAction = function () {
12580 return this.action;
12581 };
12582
12583 /**
12584 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12585 *
12586 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12587 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12588 * are hidden.
12589 *
12590 * @return {string[]}
12591 */
12592 OO.ui.ActionWidget.prototype.getModes = function () {
12593 return this.modes.slice();
12594 };
12595
12596 /**
12597 * Emit a resize event if the size has changed.
12598 *
12599 * @private
12600 * @chainable
12601 */
12602 OO.ui.ActionWidget.prototype.propagateResize = function () {
12603 var width, height;
12604
12605 if ( this.isElementAttached() ) {
12606 width = this.$element.width();
12607 height = this.$element.height();
12608
12609 if ( width !== this.width || height !== this.height ) {
12610 this.width = width;
12611 this.height = height;
12612 this.emit( 'resize' );
12613 }
12614 }
12615
12616 return this;
12617 };
12618
12619 /**
12620 * @inheritdoc
12621 */
12622 OO.ui.ActionWidget.prototype.setIcon = function () {
12623 // Mixin method
12624 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12625 this.propagateResize();
12626
12627 return this;
12628 };
12629
12630 /**
12631 * @inheritdoc
12632 */
12633 OO.ui.ActionWidget.prototype.setLabel = function () {
12634 // Mixin method
12635 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12636 this.propagateResize();
12637
12638 return this;
12639 };
12640
12641 /**
12642 * @inheritdoc
12643 */
12644 OO.ui.ActionWidget.prototype.setFlags = function () {
12645 // Mixin method
12646 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12647 this.propagateResize();
12648
12649 return this;
12650 };
12651
12652 /**
12653 * @inheritdoc
12654 */
12655 OO.ui.ActionWidget.prototype.clearFlags = function () {
12656 // Mixin method
12657 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12658 this.propagateResize();
12659
12660 return this;
12661 };
12662
12663 /**
12664 * Toggle the visibility of the action button.
12665 *
12666 * @param {boolean} [show] Show button, omit to toggle visibility
12667 * @chainable
12668 */
12669 OO.ui.ActionWidget.prototype.toggle = function () {
12670 // Parent method
12671 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12672 this.propagateResize();
12673
12674 return this;
12675 };
12676
12677 /**
12678 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12679 * which is used to display additional information or options.
12680 *
12681 * @example
12682 * // Example of a popup button.
12683 * var popupButton = new OO.ui.PopupButtonWidget( {
12684 * label: 'Popup button with options',
12685 * icon: 'menu',
12686 * popup: {
12687 * $content: $( '<p>Additional options here.</p>' ),
12688 * padded: true,
12689 * align: 'force-left'
12690 * }
12691 * } );
12692 * // Append the button to the DOM.
12693 * $( 'body' ).append( popupButton.$element );
12694 *
12695 * @class
12696 * @extends OO.ui.ButtonWidget
12697 * @mixins OO.ui.mixin.PopupElement
12698 *
12699 * @constructor
12700 * @param {Object} [config] Configuration options
12701 */
12702 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12703 // Parent constructor
12704 OO.ui.PopupButtonWidget.parent.call( this, config );
12705
12706 // Mixin constructors
12707 OO.ui.mixin.PopupElement.call( this, config );
12708
12709 // Events
12710 this.connect( this, { click: 'onAction' } );
12711
12712 // Initialization
12713 this.$element
12714 .addClass( 'oo-ui-popupButtonWidget' )
12715 .attr( 'aria-haspopup', 'true' )
12716 .append( this.popup.$element );
12717 };
12718
12719 /* Setup */
12720
12721 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12722 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12723
12724 /* Methods */
12725
12726 /**
12727 * Handle the button action being triggered.
12728 *
12729 * @private
12730 */
12731 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12732 this.popup.toggle();
12733 };
12734
12735 /**
12736 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12737 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12738 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12739 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12740 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12741 * the [OOjs UI documentation][1] on MediaWiki for more information.
12742 *
12743 * @example
12744 * // Toggle buttons in the 'off' and 'on' state.
12745 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12746 * label: 'Toggle Button off'
12747 * } );
12748 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12749 * label: 'Toggle Button on',
12750 * value: true
12751 * } );
12752 * // Append the buttons to the DOM.
12753 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12754 *
12755 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12756 *
12757 * @class
12758 * @extends OO.ui.ToggleWidget
12759 * @mixins OO.ui.mixin.ButtonElement
12760 * @mixins OO.ui.mixin.IconElement
12761 * @mixins OO.ui.mixin.IndicatorElement
12762 * @mixins OO.ui.mixin.LabelElement
12763 * @mixins OO.ui.mixin.TitledElement
12764 * @mixins OO.ui.mixin.FlaggedElement
12765 * @mixins OO.ui.mixin.TabIndexedElement
12766 *
12767 * @constructor
12768 * @param {Object} [config] Configuration options
12769 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12770 * state. By default, the button is in the 'off' state.
12771 */
12772 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12773 // Configuration initialization
12774 config = config || {};
12775
12776 // Parent constructor
12777 OO.ui.ToggleButtonWidget.parent.call( this, config );
12778
12779 // Mixin constructors
12780 OO.ui.mixin.ButtonElement.call( this, config );
12781 OO.ui.mixin.IconElement.call( this, config );
12782 OO.ui.mixin.IndicatorElement.call( this, config );
12783 OO.ui.mixin.LabelElement.call( this, config );
12784 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12785 OO.ui.mixin.FlaggedElement.call( this, config );
12786 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12787
12788 // Events
12789 this.connect( this, { click: 'onAction' } );
12790
12791 // Initialization
12792 this.$button.append( this.$icon, this.$label, this.$indicator );
12793 this.$element
12794 .addClass( 'oo-ui-toggleButtonWidget' )
12795 .append( this.$button );
12796 };
12797
12798 /* Setup */
12799
12800 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
12801 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
12802 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
12803 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
12804 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
12805 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
12806 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
12807 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
12808
12809 /* Methods */
12810
12811 /**
12812 * Handle the button action being triggered.
12813 *
12814 * @private
12815 */
12816 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
12817 this.setValue( !this.value );
12818 };
12819
12820 /**
12821 * @inheritdoc
12822 */
12823 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
12824 value = !!value;
12825 if ( value !== this.value ) {
12826 // Might be called from parent constructor before ButtonElement constructor
12827 if ( this.$button ) {
12828 this.$button.attr( 'aria-pressed', value.toString() );
12829 }
12830 this.setActive( value );
12831 }
12832
12833 // Parent method
12834 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
12835
12836 return this;
12837 };
12838
12839 /**
12840 * @inheritdoc
12841 */
12842 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
12843 if ( this.$button ) {
12844 this.$button.removeAttr( 'aria-pressed' );
12845 }
12846 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
12847 this.$button.attr( 'aria-pressed', this.value.toString() );
12848 };
12849
12850 /**
12851 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12852 * that allows for selecting multiple values.
12853 *
12854 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12855 *
12856 * @example
12857 * // Example: A CapsuleMultiSelectWidget.
12858 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12859 * label: 'CapsuleMultiSelectWidget',
12860 * selected: [ 'Option 1', 'Option 3' ],
12861 * menu: {
12862 * items: [
12863 * new OO.ui.MenuOptionWidget( {
12864 * data: 'Option 1',
12865 * label: 'Option One'
12866 * } ),
12867 * new OO.ui.MenuOptionWidget( {
12868 * data: 'Option 2',
12869 * label: 'Option Two'
12870 * } ),
12871 * new OO.ui.MenuOptionWidget( {
12872 * data: 'Option 3',
12873 * label: 'Option Three'
12874 * } ),
12875 * new OO.ui.MenuOptionWidget( {
12876 * data: 'Option 4',
12877 * label: 'Option Four'
12878 * } ),
12879 * new OO.ui.MenuOptionWidget( {
12880 * data: 'Option 5',
12881 * label: 'Option Five'
12882 * } )
12883 * ]
12884 * }
12885 * } );
12886 * $( 'body' ).append( capsule.$element );
12887 *
12888 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12889 *
12890 * @class
12891 * @extends OO.ui.Widget
12892 * @mixins OO.ui.mixin.TabIndexedElement
12893 * @mixins OO.ui.mixin.GroupElement
12894 *
12895 * @constructor
12896 * @param {Object} [config] Configuration options
12897 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12898 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12899 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12900 * If specified, this popup will be shown instead of the menu (but the menu
12901 * will still be used for item labels and allowArbitrary=false). The widgets
12902 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12903 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12904 * This configuration is useful in cases where the expanded menu is larger than
12905 * its containing `<div>`. The specified overlay layer is usually on top of
12906 * the containing `<div>` and has a larger area. By default, the menu uses
12907 * relative positioning.
12908 */
12909 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
12910 var $tabFocus;
12911
12912 // Configuration initialization
12913 config = config || {};
12914
12915 // Parent constructor
12916 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
12917
12918 // Properties (must be set before mixin constructor calls)
12919 this.$input = config.popup ? null : $( '<input>' );
12920 this.$handle = $( '<div>' );
12921
12922 // Mixin constructors
12923 OO.ui.mixin.GroupElement.call( this, config );
12924 if ( config.popup ) {
12925 config.popup = $.extend( {}, config.popup, {
12926 align: 'forwards',
12927 anchor: false
12928 } );
12929 OO.ui.mixin.PopupElement.call( this, config );
12930 $tabFocus = $( '<span>' );
12931 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
12932 } else {
12933 this.popup = null;
12934 $tabFocus = null;
12935 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
12936 }
12937 OO.ui.mixin.IndicatorElement.call( this, config );
12938 OO.ui.mixin.IconElement.call( this, config );
12939
12940 // Properties
12941 this.allowArbitrary = !!config.allowArbitrary;
12942 this.$overlay = config.$overlay || this.$element;
12943 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
12944 {
12945 widget: this,
12946 $input: this.$input,
12947 $container: this.$element,
12948 filterFromInput: true,
12949 disabled: this.isDisabled()
12950 },
12951 config.menu
12952 ) );
12953
12954 // Events
12955 if ( this.popup ) {
12956 $tabFocus.on( {
12957 focus: this.onFocusForPopup.bind( this )
12958 } );
12959 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12960 if ( this.popup.$autoCloseIgnore ) {
12961 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12962 }
12963 this.popup.connect( this, {
12964 toggle: function ( visible ) {
12965 $tabFocus.toggle( !visible );
12966 }
12967 } );
12968 } else {
12969 this.$input.on( {
12970 focus: this.onInputFocus.bind( this ),
12971 blur: this.onInputBlur.bind( this ),
12972 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
12973 keydown: this.onKeyDown.bind( this ),
12974 keypress: this.onKeyPress.bind( this )
12975 } );
12976 }
12977 this.menu.connect( this, {
12978 choose: 'onMenuChoose',
12979 add: 'onMenuItemsChange',
12980 remove: 'onMenuItemsChange'
12981 } );
12982 this.$handle.on( {
12983 click: this.onClick.bind( this )
12984 } );
12985
12986 // Initialization
12987 if ( this.$input ) {
12988 this.$input.prop( 'disabled', this.isDisabled() );
12989 this.$input.attr( {
12990 role: 'combobox',
12991 'aria-autocomplete': 'list'
12992 } );
12993 this.$input.width( '1em' );
12994 }
12995 if ( config.data ) {
12996 this.setItemsFromData( config.data );
12997 }
12998 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12999 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13000 .append( this.$indicator, this.$icon, this.$group );
13001 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13002 .append( this.$handle );
13003 if ( this.popup ) {
13004 this.$handle.append( $tabFocus );
13005 this.$overlay.append( this.popup.$element );
13006 } else {
13007 this.$handle.append( this.$input );
13008 this.$overlay.append( this.menu.$element );
13009 }
13010 this.onMenuItemsChange();
13011 };
13012
13013 /* Setup */
13014
13015 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13016 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13017 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13018 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13019 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13020 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13021
13022 /* Events */
13023
13024 /**
13025 * @event change
13026 *
13027 * A change event is emitted when the set of selected items changes.
13028 *
13029 * @param {Mixed[]} datas Data of the now-selected items
13030 */
13031
13032 /* Methods */
13033
13034 /**
13035 * Get the data of the items in the capsule
13036 * @return {Mixed[]}
13037 */
13038 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13039 return $.map( this.getItems(), function ( e ) { return e.data; } );
13040 };
13041
13042 /**
13043 * Set the items in the capsule by providing data
13044 * @chainable
13045 * @param {Mixed[]} datas
13046 * @return {OO.ui.CapsuleMultiSelectWidget}
13047 */
13048 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13049 var widget = this,
13050 menu = this.menu,
13051 items = this.getItems();
13052
13053 $.each( datas, function ( i, data ) {
13054 var j, label,
13055 item = menu.getItemFromData( data );
13056
13057 if ( item ) {
13058 label = item.label;
13059 } else if ( widget.allowArbitrary ) {
13060 label = String( data );
13061 } else {
13062 return;
13063 }
13064
13065 item = null;
13066 for ( j = 0; j < items.length; j++ ) {
13067 if ( items[ j ].data === data && items[ j ].label === label ) {
13068 item = items[ j ];
13069 items.splice( j, 1 );
13070 break;
13071 }
13072 }
13073 if ( !item ) {
13074 item = new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13075 }
13076 widget.addItems( [ item ], i );
13077 } );
13078
13079 if ( items.length ) {
13080 widget.removeItems( items );
13081 }
13082
13083 return this;
13084 };
13085
13086 /**
13087 * Add items to the capsule by providing their data
13088 * @chainable
13089 * @param {Mixed[]} datas
13090 * @return {OO.ui.CapsuleMultiSelectWidget}
13091 */
13092 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13093 var widget = this,
13094 menu = this.menu,
13095 items = [];
13096
13097 $.each( datas, function ( i, data ) {
13098 var item;
13099
13100 if ( !widget.getItemFromData( data ) ) {
13101 item = menu.getItemFromData( data );
13102 if ( item ) {
13103 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: item.label } ) );
13104 } else if ( widget.allowArbitrary ) {
13105 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: String( data ) } ) );
13106 }
13107 }
13108 } );
13109
13110 if ( items.length ) {
13111 this.addItems( items );
13112 }
13113
13114 return this;
13115 };
13116
13117 /**
13118 * Remove items by data
13119 * @chainable
13120 * @param {Mixed[]} datas
13121 * @return {OO.ui.CapsuleMultiSelectWidget}
13122 */
13123 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13124 var widget = this,
13125 items = [];
13126
13127 $.each( datas, function ( i, data ) {
13128 var item = widget.getItemFromData( data );
13129 if ( item ) {
13130 items.push( item );
13131 }
13132 } );
13133
13134 if ( items.length ) {
13135 this.removeItems( items );
13136 }
13137
13138 return this;
13139 };
13140
13141 /**
13142 * @inheritdoc
13143 */
13144 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13145 var same, i, l,
13146 oldItems = this.items.slice();
13147
13148 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13149
13150 if ( this.items.length !== oldItems.length ) {
13151 same = false;
13152 } else {
13153 same = true;
13154 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13155 same = same && this.items[ i ] === oldItems[ i ];
13156 }
13157 }
13158 if ( !same ) {
13159 this.emit( 'change', this.getItemsData() );
13160 }
13161
13162 return this;
13163 };
13164
13165 /**
13166 * @inheritdoc
13167 */
13168 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13169 var same, i, l,
13170 oldItems = this.items.slice();
13171
13172 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13173
13174 if ( this.items.length !== oldItems.length ) {
13175 same = false;
13176 } else {
13177 same = true;
13178 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13179 same = same && this.items[ i ] === oldItems[ i ];
13180 }
13181 }
13182 if ( !same ) {
13183 this.emit( 'change', this.getItemsData() );
13184 }
13185
13186 return this;
13187 };
13188
13189 /**
13190 * @inheritdoc
13191 */
13192 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13193 if ( this.items.length ) {
13194 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13195 this.emit( 'change', this.getItemsData() );
13196 }
13197 return this;
13198 };
13199
13200 /**
13201 * Get the capsule widget's menu.
13202 * @return {OO.ui.MenuSelectWidget} Menu widget
13203 */
13204 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13205 return this.menu;
13206 };
13207
13208 /**
13209 * Handle focus events
13210 *
13211 * @private
13212 * @param {jQuery.Event} event
13213 */
13214 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13215 if ( !this.isDisabled() ) {
13216 this.menu.toggle( true );
13217 }
13218 };
13219
13220 /**
13221 * Handle blur events
13222 *
13223 * @private
13224 * @param {jQuery.Event} event
13225 */
13226 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13227 this.clearInput();
13228 };
13229
13230 /**
13231 * Handle focus events
13232 *
13233 * @private
13234 * @param {jQuery.Event} event
13235 */
13236 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13237 if ( !this.isDisabled() ) {
13238 this.popup.setSize( this.$handle.width() );
13239 this.popup.toggle( true );
13240 this.popup.$element.find( '*' )
13241 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13242 .first()
13243 .focus();
13244 }
13245 };
13246
13247 /**
13248 * Handles popup focus out events.
13249 *
13250 * @private
13251 * @param {Event} e Focus out event
13252 */
13253 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13254 var widget = this.popup;
13255
13256 setTimeout( function () {
13257 if (
13258 widget.isVisible() &&
13259 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13260 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13261 ) {
13262 widget.toggle( false );
13263 }
13264 } );
13265 };
13266
13267 /**
13268 * Handle mouse click events.
13269 *
13270 * @private
13271 * @param {jQuery.Event} e Mouse click event
13272 */
13273 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13274 if ( e.which === 1 ) {
13275 this.focus();
13276 return false;
13277 }
13278 };
13279
13280 /**
13281 * Handle key press events.
13282 *
13283 * @private
13284 * @param {jQuery.Event} e Key press event
13285 */
13286 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13287 var item;
13288
13289 if ( !this.isDisabled() ) {
13290 if ( e.which === OO.ui.Keys.ESCAPE ) {
13291 this.clearInput();
13292 return false;
13293 }
13294
13295 if ( !this.popup ) {
13296 this.menu.toggle( true );
13297 if ( e.which === OO.ui.Keys.ENTER ) {
13298 item = this.menu.getItemFromLabel( this.$input.val(), true );
13299 if ( item ) {
13300 this.addItemsFromData( [ item.data ] );
13301 this.clearInput();
13302 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13303 this.addItemsFromData( [ this.$input.val() ] );
13304 this.clearInput();
13305 }
13306 return false;
13307 }
13308
13309 // Make sure the input gets resized.
13310 setTimeout( this.onInputChange.bind( this ), 0 );
13311 }
13312 }
13313 };
13314
13315 /**
13316 * Handle key down events.
13317 *
13318 * @private
13319 * @param {jQuery.Event} e Key down event
13320 */
13321 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13322 if ( !this.isDisabled() ) {
13323 // 'keypress' event is not triggered for Backspace
13324 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13325 if ( this.items.length ) {
13326 this.removeItems( this.items.slice( -1 ) );
13327 }
13328 return false;
13329 }
13330 }
13331 };
13332
13333 /**
13334 * Handle input change events.
13335 *
13336 * @private
13337 * @param {jQuery.Event} e Event of some sort
13338 */
13339 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13340 if ( !this.isDisabled() ) {
13341 this.$input.width( this.$input.val().length + 'em' );
13342 }
13343 };
13344
13345 /**
13346 * Handle menu choose events.
13347 *
13348 * @private
13349 * @param {OO.ui.OptionWidget} item Chosen item
13350 */
13351 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13352 if ( item && item.isVisible() ) {
13353 this.addItemsFromData( [ item.getData() ] );
13354 this.clearInput();
13355 }
13356 };
13357
13358 /**
13359 * Handle menu item change events.
13360 *
13361 * @private
13362 */
13363 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13364 this.setItemsFromData( this.getItemsData() );
13365 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13366 };
13367
13368 /**
13369 * Clear the input field
13370 * @private
13371 */
13372 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13373 if ( this.$input ) {
13374 this.$input.val( '' );
13375 this.$input.width( '1em' );
13376 }
13377 if ( this.popup ) {
13378 this.popup.toggle( false );
13379 }
13380 this.menu.toggle( false );
13381 this.menu.selectItem();
13382 this.menu.highlightItem();
13383 };
13384
13385 /**
13386 * @inheritdoc
13387 */
13388 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13389 var i, len;
13390
13391 // Parent method
13392 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13393
13394 if ( this.$input ) {
13395 this.$input.prop( 'disabled', this.isDisabled() );
13396 }
13397 if ( this.menu ) {
13398 this.menu.setDisabled( this.isDisabled() );
13399 }
13400 if ( this.popup ) {
13401 this.popup.setDisabled( this.isDisabled() );
13402 }
13403
13404 if ( this.items ) {
13405 for ( i = 0, len = this.items.length; i < len; i++ ) {
13406 this.items[ i ].updateDisabled();
13407 }
13408 }
13409
13410 return this;
13411 };
13412
13413 /**
13414 * Focus the widget
13415 * @chainable
13416 * @return {OO.ui.CapsuleMultiSelectWidget}
13417 */
13418 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13419 if ( !this.isDisabled() ) {
13420 if ( this.popup ) {
13421 this.popup.setSize( this.$handle.width() );
13422 this.popup.toggle( true );
13423 this.popup.$element.find( '*' )
13424 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13425 .first()
13426 .focus();
13427 } else {
13428 this.menu.toggle( true );
13429 this.$input.focus();
13430 }
13431 }
13432 return this;
13433 };
13434
13435 /**
13436 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13437 * CapsuleMultiSelectWidget} to display the selected items.
13438 *
13439 * @class
13440 * @extends OO.ui.Widget
13441 * @mixins OO.ui.mixin.ItemWidget
13442 * @mixins OO.ui.mixin.IndicatorElement
13443 * @mixins OO.ui.mixin.LabelElement
13444 * @mixins OO.ui.mixin.FlaggedElement
13445 * @mixins OO.ui.mixin.TabIndexedElement
13446 *
13447 * @constructor
13448 * @param {Object} [config] Configuration options
13449 */
13450 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13451 // Configuration initialization
13452 config = config || {};
13453
13454 // Parent constructor
13455 OO.ui.CapsuleItemWidget.parent.call( this, config );
13456
13457 // Properties (must be set before mixin constructor calls)
13458 this.$indicator = $( '<span>' );
13459
13460 // Mixin constructors
13461 OO.ui.mixin.ItemWidget.call( this );
13462 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13463 OO.ui.mixin.LabelElement.call( this, config );
13464 OO.ui.mixin.FlaggedElement.call( this, config );
13465 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13466
13467 // Events
13468 this.$indicator.on( {
13469 keydown: this.onCloseKeyDown.bind( this ),
13470 click: this.onCloseClick.bind( this )
13471 } );
13472 this.$element.on( 'click', false );
13473
13474 // Initialization
13475 this.$element
13476 .addClass( 'oo-ui-capsuleItemWidget' )
13477 .append( this.$indicator, this.$label );
13478 };
13479
13480 /* Setup */
13481
13482 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13483 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13484 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13485 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13486 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13487 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13488
13489 /* Methods */
13490
13491 /**
13492 * Handle close icon clicks
13493 * @param {jQuery.Event} event
13494 */
13495 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13496 var element = this.getElementGroup();
13497
13498 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13499 element.removeItems( [ this ] );
13500 element.focus();
13501 }
13502 };
13503
13504 /**
13505 * Handle close keyboard events
13506 * @param {jQuery.Event} event Key down event
13507 */
13508 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13509 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13510 switch ( e.which ) {
13511 case OO.ui.Keys.ENTER:
13512 case OO.ui.Keys.BACKSPACE:
13513 case OO.ui.Keys.SPACE:
13514 this.getElementGroup().removeItems( [ this ] );
13515 return false;
13516 }
13517 }
13518 };
13519
13520 /**
13521 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13522 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13523 * users can interact with it.
13524 *
13525 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13526 * OO.ui.DropdownInputWidget instead.
13527 *
13528 * @example
13529 * // Example: A DropdownWidget with a menu that contains three options
13530 * var dropDown = new OO.ui.DropdownWidget( {
13531 * label: 'Dropdown menu: Select a menu option',
13532 * menu: {
13533 * items: [
13534 * new OO.ui.MenuOptionWidget( {
13535 * data: 'a',
13536 * label: 'First'
13537 * } ),
13538 * new OO.ui.MenuOptionWidget( {
13539 * data: 'b',
13540 * label: 'Second'
13541 * } ),
13542 * new OO.ui.MenuOptionWidget( {
13543 * data: 'c',
13544 * label: 'Third'
13545 * } )
13546 * ]
13547 * }
13548 * } );
13549 *
13550 * $( 'body' ).append( dropDown.$element );
13551 *
13552 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13553 *
13554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13555 *
13556 * @class
13557 * @extends OO.ui.Widget
13558 * @mixins OO.ui.mixin.IconElement
13559 * @mixins OO.ui.mixin.IndicatorElement
13560 * @mixins OO.ui.mixin.LabelElement
13561 * @mixins OO.ui.mixin.TitledElement
13562 * @mixins OO.ui.mixin.TabIndexedElement
13563 *
13564 * @constructor
13565 * @param {Object} [config] Configuration options
13566 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13567 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13568 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13569 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13570 */
13571 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13572 // Configuration initialization
13573 config = $.extend( { indicator: 'down' }, config );
13574
13575 // Parent constructor
13576 OO.ui.DropdownWidget.parent.call( this, config );
13577
13578 // Properties (must be set before TabIndexedElement constructor call)
13579 this.$handle = this.$( '<span>' );
13580 this.$overlay = config.$overlay || this.$element;
13581
13582 // Mixin constructors
13583 OO.ui.mixin.IconElement.call( this, config );
13584 OO.ui.mixin.IndicatorElement.call( this, config );
13585 OO.ui.mixin.LabelElement.call( this, config );
13586 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13587 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13588
13589 // Properties
13590 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13591 widget: this,
13592 $container: this.$element
13593 }, config.menu ) );
13594
13595 // Events
13596 this.$handle.on( {
13597 click: this.onClick.bind( this ),
13598 keypress: this.onKeyPress.bind( this )
13599 } );
13600 this.menu.connect( this, { select: 'onMenuSelect' } );
13601
13602 // Initialization
13603 this.$handle
13604 .addClass( 'oo-ui-dropdownWidget-handle' )
13605 .append( this.$icon, this.$label, this.$indicator );
13606 this.$element
13607 .addClass( 'oo-ui-dropdownWidget' )
13608 .append( this.$handle );
13609 this.$overlay.append( this.menu.$element );
13610 };
13611
13612 /* Setup */
13613
13614 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13615 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13616 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13617 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13618 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13619 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13620
13621 /* Methods */
13622
13623 /**
13624 * Get the menu.
13625 *
13626 * @return {OO.ui.MenuSelectWidget} Menu of widget
13627 */
13628 OO.ui.DropdownWidget.prototype.getMenu = function () {
13629 return this.menu;
13630 };
13631
13632 /**
13633 * Handles menu select events.
13634 *
13635 * @private
13636 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13637 */
13638 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13639 var selectedLabel;
13640
13641 if ( !item ) {
13642 this.setLabel( null );
13643 return;
13644 }
13645
13646 selectedLabel = item.getLabel();
13647
13648 // If the label is a DOM element, clone it, because setLabel will append() it
13649 if ( selectedLabel instanceof jQuery ) {
13650 selectedLabel = selectedLabel.clone();
13651 }
13652
13653 this.setLabel( selectedLabel );
13654 };
13655
13656 /**
13657 * Handle mouse click events.
13658 *
13659 * @private
13660 * @param {jQuery.Event} e Mouse click event
13661 */
13662 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13663 if ( !this.isDisabled() && e.which === 1 ) {
13664 this.menu.toggle();
13665 }
13666 return false;
13667 };
13668
13669 /**
13670 * Handle key press events.
13671 *
13672 * @private
13673 * @param {jQuery.Event} e Key press event
13674 */
13675 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13676 if ( !this.isDisabled() &&
13677 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13678 ) {
13679 this.menu.toggle();
13680 return false;
13681 }
13682 };
13683
13684 /**
13685 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13686 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13687 * OO.ui.mixin.IndicatorElement indicators}.
13688 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13689 *
13690 * @example
13691 * // Example of a file select widget
13692 * var selectFile = new OO.ui.SelectFileWidget();
13693 * $( 'body' ).append( selectFile.$element );
13694 *
13695 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13696 *
13697 * @class
13698 * @extends OO.ui.Widget
13699 * @mixins OO.ui.mixin.IconElement
13700 * @mixins OO.ui.mixin.IndicatorElement
13701 * @mixins OO.ui.mixin.PendingElement
13702 * @mixins OO.ui.mixin.LabelElement
13703 *
13704 * @constructor
13705 * @param {Object} [config] Configuration options
13706 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13707 * @cfg {string} [placeholder] Text to display when no file is selected.
13708 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13709 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13710 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13711 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13712 */
13713 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13714 var dragHandler;
13715
13716 // TODO: Remove in next release
13717 if ( config && config.dragDropUI ) {
13718 config.showDropTarget = true;
13719 }
13720
13721 // Configuration initialization
13722 config = $.extend( {
13723 accept: null,
13724 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13725 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13726 droppable: true,
13727 showDropTarget: false
13728 }, config );
13729
13730 // Parent constructor
13731 OO.ui.SelectFileWidget.parent.call( this, config );
13732
13733 // Mixin constructors
13734 OO.ui.mixin.IconElement.call( this, config );
13735 OO.ui.mixin.IndicatorElement.call( this, config );
13736 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
13737 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13738
13739 // Properties
13740 this.$info = $( '<span>' );
13741
13742 // Properties
13743 this.showDropTarget = config.showDropTarget;
13744 this.isSupported = this.constructor.static.isSupported();
13745 this.currentFile = null;
13746 if ( Array.isArray( config.accept ) ) {
13747 this.accept = config.accept;
13748 } else {
13749 this.accept = null;
13750 }
13751 this.placeholder = config.placeholder;
13752 this.notsupported = config.notsupported;
13753 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13754
13755 this.selectButton = new OO.ui.ButtonWidget( {
13756 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
13757 label: 'Select a file',
13758 disabled: this.disabled || !this.isSupported
13759 } );
13760
13761 this.clearButton = new OO.ui.ButtonWidget( {
13762 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13763 framed: false,
13764 icon: 'remove',
13765 disabled: this.disabled
13766 } );
13767
13768 // Events
13769 this.selectButton.$button.on( {
13770 keypress: this.onKeyPress.bind( this )
13771 } );
13772 this.clearButton.connect( this, {
13773 click: 'onClearClick'
13774 } );
13775 if ( config.droppable ) {
13776 dragHandler = this.onDragEnterOrOver.bind( this );
13777 this.$element.on( {
13778 dragenter: dragHandler,
13779 dragover: dragHandler,
13780 dragleave: this.onDragLeave.bind( this ),
13781 drop: this.onDrop.bind( this )
13782 } );
13783 }
13784
13785 // Initialization
13786 this.addInput();
13787 this.updateUI();
13788 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
13789 this.$info
13790 .addClass( 'oo-ui-selectFileWidget-info' )
13791 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
13792 this.$element
13793 .addClass( 'oo-ui-selectFileWidget' )
13794 .append( this.$info, this.selectButton.$element );
13795 if ( config.droppable && config.showDropTarget ) {
13796 this.$dropTarget = $( '<div>' )
13797 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
13798 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
13799 .on( {
13800 click: this.onDropTargetClick.bind( this )
13801 } );
13802 this.$element.prepend( this.$dropTarget );
13803 }
13804 };
13805
13806 /* Setup */
13807
13808 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
13809 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
13810 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
13811 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
13812 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
13813
13814 /* Static Properties */
13815
13816 /**
13817 * Check if this widget is supported
13818 *
13819 * @static
13820 * @return {boolean}
13821 */
13822 OO.ui.SelectFileWidget.static.isSupported = function () {
13823 var $input;
13824 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
13825 $input = $( '<input type="file">' );
13826 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
13827 }
13828 return OO.ui.SelectFileWidget.static.isSupportedCache;
13829 };
13830
13831 OO.ui.SelectFileWidget.static.isSupportedCache = null;
13832
13833 /* Events */
13834
13835 /**
13836 * @event change
13837 *
13838 * A change event is emitted when the on/off state of the toggle changes.
13839 *
13840 * @param {File|null} value New value
13841 */
13842
13843 /* Methods */
13844
13845 /**
13846 * Get the current value of the field
13847 *
13848 * @return {File|null}
13849 */
13850 OO.ui.SelectFileWidget.prototype.getValue = function () {
13851 return this.currentFile;
13852 };
13853
13854 /**
13855 * Set the current value of the field
13856 *
13857 * @param {File|null} file File to select
13858 */
13859 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
13860 if ( this.currentFile !== file ) {
13861 this.currentFile = file;
13862 this.updateUI();
13863 this.emit( 'change', this.currentFile );
13864 }
13865 };
13866
13867 /**
13868 * Update the user interface when a file is selected or unselected
13869 *
13870 * @protected
13871 */
13872 OO.ui.SelectFileWidget.prototype.updateUI = function () {
13873 if ( !this.isSupported ) {
13874 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
13875 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13876 this.setLabel( this.notsupported );
13877 } else {
13878 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
13879 if ( this.currentFile ) {
13880 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13881 this.setLabel( this.currentFile.name +
13882 ( this.currentFile.type !== '' ? OO.ui.msg( 'ooui-semicolon-separator' ) + this.currentFile.type : '' )
13883 );
13884 } else {
13885 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
13886 this.setLabel( this.placeholder );
13887 }
13888 }
13889
13890 if ( this.$input ) {
13891 this.$input.attr( 'title', this.getLabel() );
13892 }
13893 };
13894
13895 /**
13896 * Add the input to the widget
13897 *
13898 * @private
13899 */
13900 OO.ui.SelectFileWidget.prototype.addInput = function () {
13901 if ( this.$input ) {
13902 this.$input.remove();
13903 }
13904
13905 if ( !this.isSupported ) {
13906 this.$input = null;
13907 return;
13908 }
13909
13910 this.$input = $( '<input type="file">' );
13911 this.$input.on( 'change', this.onFileSelectedHandler );
13912 this.$input.attr( {
13913 tabindex: -1,
13914 title: this.getLabel()
13915 } );
13916 if ( this.accept ) {
13917 this.$input.attr( 'accept', this.accept.join( ', ' ) );
13918 }
13919 this.selectButton.$button.append( this.$input );
13920 };
13921
13922 /**
13923 * Determine if we should accept this file
13924 *
13925 * @private
13926 * @param {string} File MIME type
13927 * @return {boolean}
13928 */
13929 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
13930 var i, mimeTest;
13931
13932 if ( !this.accept || !mimeType ) {
13933 return true;
13934 }
13935
13936 for ( i = 0; i < this.accept.length; i++ ) {
13937 mimeTest = this.accept[ i ];
13938 if ( mimeTest === mimeType ) {
13939 return true;
13940 } else if ( mimeTest.substr( -2 ) === '/*' ) {
13941 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
13942 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
13943 return true;
13944 }
13945 }
13946 }
13947
13948 return false;
13949 };
13950
13951 /**
13952 * Handle file selection from the input
13953 *
13954 * @private
13955 * @param {jQuery.Event} e
13956 */
13957 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
13958 var file = OO.getProp( e.target, 'files', 0 ) || null;
13959
13960 if ( file && !this.isAllowedType( file.type ) ) {
13961 file = null;
13962 }
13963
13964 this.setValue( file );
13965 this.addInput();
13966 };
13967
13968 /**
13969 * Handle clear button click events.
13970 *
13971 * @private
13972 */
13973 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
13974 this.setValue( null );
13975 return false;
13976 };
13977
13978 /**
13979 * Handle key press events.
13980 *
13981 * @private
13982 * @param {jQuery.Event} e Key press event
13983 */
13984 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
13985 if ( this.isSupported && !this.isDisabled() && this.$input &&
13986 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
13987 ) {
13988 this.$input.click();
13989 return false;
13990 }
13991 };
13992
13993 /**
13994 * Handle drop target click events.
13995 *
13996 * @private
13997 * @param {jQuery.Event} e Key press event
13998 */
13999 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
14000 if ( this.isSupported && !this.isDisabled() && this.$input ) {
14001 this.$input.click();
14002 return false;
14003 }
14004 };
14005
14006 /**
14007 * Handle drag enter and over events
14008 *
14009 * @private
14010 * @param {jQuery.Event} e Drag event
14011 */
14012 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14013 var itemOrFile,
14014 droppableFile = false,
14015 dt = e.originalEvent.dataTransfer;
14016
14017 e.preventDefault();
14018 e.stopPropagation();
14019
14020 if ( this.isDisabled() || !this.isSupported ) {
14021 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14022 dt.dropEffect = 'none';
14023 return false;
14024 }
14025
14026 // DataTransferItem and File both have a type property, but in Chrome files
14027 // have no information at this point.
14028 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14029 if ( itemOrFile ) {
14030 if ( this.isAllowedType( itemOrFile.type ) ) {
14031 droppableFile = true;
14032 }
14033 // dt.types is Array-like, but not an Array
14034 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14035 // File information is not available at this point for security so just assume
14036 // it is acceptable for now.
14037 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14038 droppableFile = true;
14039 }
14040
14041 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14042 if ( !droppableFile ) {
14043 dt.dropEffect = 'none';
14044 }
14045
14046 return false;
14047 };
14048
14049 /**
14050 * Handle drag leave events
14051 *
14052 * @private
14053 * @param {jQuery.Event} e Drag event
14054 */
14055 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14056 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14057 };
14058
14059 /**
14060 * Handle drop events
14061 *
14062 * @private
14063 * @param {jQuery.Event} e Drop event
14064 */
14065 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14066 var file = null,
14067 dt = e.originalEvent.dataTransfer;
14068
14069 e.preventDefault();
14070 e.stopPropagation();
14071 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14072
14073 if ( this.isDisabled() || !this.isSupported ) {
14074 return false;
14075 }
14076
14077 file = OO.getProp( dt, 'files', 0 );
14078 if ( file && !this.isAllowedType( file.type ) ) {
14079 file = null;
14080 }
14081 if ( file ) {
14082 this.setValue( file );
14083 }
14084
14085 return false;
14086 };
14087
14088 /**
14089 * @inheritdoc
14090 */
14091 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14092 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14093 if ( this.selectButton ) {
14094 this.selectButton.setDisabled( disabled );
14095 }
14096 if ( this.clearButton ) {
14097 this.clearButton.setDisabled( disabled );
14098 }
14099 return this;
14100 };
14101
14102 /**
14103 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14104 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14105 * for a list of icons included in the library.
14106 *
14107 * @example
14108 * // An icon widget with a label
14109 * var myIcon = new OO.ui.IconWidget( {
14110 * icon: 'help',
14111 * iconTitle: 'Help'
14112 * } );
14113 * // Create a label.
14114 * var iconLabel = new OO.ui.LabelWidget( {
14115 * label: 'Help'
14116 * } );
14117 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14118 *
14119 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14120 *
14121 * @class
14122 * @extends OO.ui.Widget
14123 * @mixins OO.ui.mixin.IconElement
14124 * @mixins OO.ui.mixin.TitledElement
14125 * @mixins OO.ui.mixin.FlaggedElement
14126 *
14127 * @constructor
14128 * @param {Object} [config] Configuration options
14129 */
14130 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14131 // Configuration initialization
14132 config = config || {};
14133
14134 // Parent constructor
14135 OO.ui.IconWidget.parent.call( this, config );
14136
14137 // Mixin constructors
14138 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14139 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14140 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14141
14142 // Initialization
14143 this.$element.addClass( 'oo-ui-iconWidget' );
14144 };
14145
14146 /* Setup */
14147
14148 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14149 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14150 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14151 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14152
14153 /* Static Properties */
14154
14155 OO.ui.IconWidget.static.tagName = 'span';
14156
14157 /**
14158 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14159 * attention to the status of an item or to clarify the function of a control. For a list of
14160 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14161 *
14162 * @example
14163 * // Example of an indicator widget
14164 * var indicator1 = new OO.ui.IndicatorWidget( {
14165 * indicator: 'alert'
14166 * } );
14167 *
14168 * // Create a fieldset layout to add a label
14169 * var fieldset = new OO.ui.FieldsetLayout();
14170 * fieldset.addItems( [
14171 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14172 * ] );
14173 * $( 'body' ).append( fieldset.$element );
14174 *
14175 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14176 *
14177 * @class
14178 * @extends OO.ui.Widget
14179 * @mixins OO.ui.mixin.IndicatorElement
14180 * @mixins OO.ui.mixin.TitledElement
14181 *
14182 * @constructor
14183 * @param {Object} [config] Configuration options
14184 */
14185 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14186 // Configuration initialization
14187 config = config || {};
14188
14189 // Parent constructor
14190 OO.ui.IndicatorWidget.parent.call( this, config );
14191
14192 // Mixin constructors
14193 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14194 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14195
14196 // Initialization
14197 this.$element.addClass( 'oo-ui-indicatorWidget' );
14198 };
14199
14200 /* Setup */
14201
14202 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14203 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14204 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14205
14206 /* Static Properties */
14207
14208 OO.ui.IndicatorWidget.static.tagName = 'span';
14209
14210 /**
14211 * InputWidget is the base class for all input widgets, which
14212 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14213 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14214 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14215 *
14216 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14217 *
14218 * @abstract
14219 * @class
14220 * @extends OO.ui.Widget
14221 * @mixins OO.ui.mixin.FlaggedElement
14222 * @mixins OO.ui.mixin.TabIndexedElement
14223 * @mixins OO.ui.mixin.TitledElement
14224 * @mixins OO.ui.mixin.AccessKeyedElement
14225 *
14226 * @constructor
14227 * @param {Object} [config] Configuration options
14228 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14229 * @cfg {string} [value=''] The value of the input.
14230 * @cfg {string} [accessKey=''] The access key of the input.
14231 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14232 * before it is accepted.
14233 */
14234 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14235 // Configuration initialization
14236 config = config || {};
14237
14238 // Parent constructor
14239 OO.ui.InputWidget.parent.call( this, config );
14240
14241 // Properties
14242 this.$input = this.getInputElement( config );
14243 this.value = '';
14244 this.inputFilter = config.inputFilter;
14245
14246 // Mixin constructors
14247 OO.ui.mixin.FlaggedElement.call( this, config );
14248 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14249 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14250 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14251
14252 // Events
14253 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14254
14255 // Initialization
14256 this.$input
14257 .addClass( 'oo-ui-inputWidget-input' )
14258 .attr( 'name', config.name )
14259 .prop( 'disabled', this.isDisabled() );
14260 this.$element
14261 .addClass( 'oo-ui-inputWidget' )
14262 .append( this.$input );
14263 this.setValue( config.value );
14264 this.setAccessKey( config.accessKey );
14265 };
14266
14267 /* Setup */
14268
14269 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14270 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14271 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14272 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14273 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14274
14275 /* Static Properties */
14276
14277 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14278
14279 /* Events */
14280
14281 /**
14282 * @event change
14283 *
14284 * A change event is emitted when the value of the input changes.
14285 *
14286 * @param {string} value
14287 */
14288
14289 /* Methods */
14290
14291 /**
14292 * Get input element.
14293 *
14294 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14295 * different circumstances. The element must have a `value` property (like form elements).
14296 *
14297 * @protected
14298 * @param {Object} config Configuration options
14299 * @return {jQuery} Input element
14300 */
14301 OO.ui.InputWidget.prototype.getInputElement = function () {
14302 return $( '<input>' );
14303 };
14304
14305 /**
14306 * Handle potentially value-changing events.
14307 *
14308 * @private
14309 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14310 */
14311 OO.ui.InputWidget.prototype.onEdit = function () {
14312 var widget = this;
14313 if ( !this.isDisabled() ) {
14314 // Allow the stack to clear so the value will be updated
14315 setTimeout( function () {
14316 widget.setValue( widget.$input.val() );
14317 } );
14318 }
14319 };
14320
14321 /**
14322 * Get the value of the input.
14323 *
14324 * @return {string} Input value
14325 */
14326 OO.ui.InputWidget.prototype.getValue = function () {
14327 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14328 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14329 var value = this.$input.val();
14330 if ( this.value !== value ) {
14331 this.setValue( value );
14332 }
14333 return this.value;
14334 };
14335
14336 /**
14337 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14338 *
14339 * @param {boolean} isRTL
14340 * Direction is right-to-left
14341 */
14342 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14343 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14344 };
14345
14346 /**
14347 * Set the value of the input.
14348 *
14349 * @param {string} value New value
14350 * @fires change
14351 * @chainable
14352 */
14353 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14354 value = this.cleanUpValue( value );
14355 // Update the DOM if it has changed. Note that with cleanUpValue, it
14356 // is possible for the DOM value to change without this.value changing.
14357 if ( this.$input.val() !== value ) {
14358 this.$input.val( value );
14359 }
14360 if ( this.value !== value ) {
14361 this.value = value;
14362 this.emit( 'change', this.value );
14363 }
14364 return this;
14365 };
14366
14367 /**
14368 * Set the input's access key.
14369 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14370 *
14371 * @param {string} accessKey Input's access key, use empty string to remove
14372 * @chainable
14373 */
14374 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14375 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14376
14377 if ( this.accessKey !== accessKey ) {
14378 if ( this.$input ) {
14379 if ( accessKey !== null ) {
14380 this.$input.attr( 'accesskey', accessKey );
14381 } else {
14382 this.$input.removeAttr( 'accesskey' );
14383 }
14384 }
14385 this.accessKey = accessKey;
14386 }
14387
14388 return this;
14389 };
14390
14391 /**
14392 * Clean up incoming value.
14393 *
14394 * Ensures value is a string, and converts undefined and null to empty string.
14395 *
14396 * @private
14397 * @param {string} value Original value
14398 * @return {string} Cleaned up value
14399 */
14400 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14401 if ( value === undefined || value === null ) {
14402 return '';
14403 } else if ( this.inputFilter ) {
14404 return this.inputFilter( String( value ) );
14405 } else {
14406 return String( value );
14407 }
14408 };
14409
14410 /**
14411 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14412 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14413 * called directly.
14414 */
14415 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14416 if ( !this.isDisabled() ) {
14417 if ( this.$input.is( ':checkbox, :radio' ) ) {
14418 this.$input.click();
14419 }
14420 if ( this.$input.is( ':input' ) ) {
14421 this.$input[ 0 ].focus();
14422 }
14423 }
14424 };
14425
14426 /**
14427 * @inheritdoc
14428 */
14429 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14430 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14431 if ( this.$input ) {
14432 this.$input.prop( 'disabled', this.isDisabled() );
14433 }
14434 return this;
14435 };
14436
14437 /**
14438 * Focus the input.
14439 *
14440 * @chainable
14441 */
14442 OO.ui.InputWidget.prototype.focus = function () {
14443 this.$input[ 0 ].focus();
14444 return this;
14445 };
14446
14447 /**
14448 * Blur the input.
14449 *
14450 * @chainable
14451 */
14452 OO.ui.InputWidget.prototype.blur = function () {
14453 this.$input[ 0 ].blur();
14454 return this;
14455 };
14456
14457 /**
14458 * @inheritdoc
14459 */
14460 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14461 var
14462 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14463 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14464 state.value = $input.val();
14465 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14466 state.focus = $input.is( ':focus' );
14467 return state;
14468 };
14469
14470 /**
14471 * @inheritdoc
14472 */
14473 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14474 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14475 if ( state.value !== undefined && state.value !== this.getValue() ) {
14476 this.setValue( state.value );
14477 }
14478 if ( state.focus ) {
14479 this.focus();
14480 }
14481 };
14482
14483 /**
14484 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14485 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14486 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14487 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14488 * [OOjs UI documentation on MediaWiki] [1] for more information.
14489 *
14490 * @example
14491 * // A ButtonInputWidget rendered as an HTML button, the default.
14492 * var button = new OO.ui.ButtonInputWidget( {
14493 * label: 'Input button',
14494 * icon: 'check',
14495 * value: 'check'
14496 * } );
14497 * $( 'body' ).append( button.$element );
14498 *
14499 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14500 *
14501 * @class
14502 * @extends OO.ui.InputWidget
14503 * @mixins OO.ui.mixin.ButtonElement
14504 * @mixins OO.ui.mixin.IconElement
14505 * @mixins OO.ui.mixin.IndicatorElement
14506 * @mixins OO.ui.mixin.LabelElement
14507 * @mixins OO.ui.mixin.TitledElement
14508 *
14509 * @constructor
14510 * @param {Object} [config] Configuration options
14511 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14512 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14513 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14514 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14515 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14516 */
14517 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14518 // Configuration initialization
14519 config = $.extend( { type: 'button', useInputTag: false }, config );
14520
14521 // Properties (must be set before parent constructor, which calls #setValue)
14522 this.useInputTag = config.useInputTag;
14523
14524 // Parent constructor
14525 OO.ui.ButtonInputWidget.parent.call( this, config );
14526
14527 // Mixin constructors
14528 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14529 OO.ui.mixin.IconElement.call( this, config );
14530 OO.ui.mixin.IndicatorElement.call( this, config );
14531 OO.ui.mixin.LabelElement.call( this, config );
14532 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14533
14534 // Initialization
14535 if ( !config.useInputTag ) {
14536 this.$input.append( this.$icon, this.$label, this.$indicator );
14537 }
14538 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14539 };
14540
14541 /* Setup */
14542
14543 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14544 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14545 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14546 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14547 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14548 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14549
14550 /* Static Properties */
14551
14552 /**
14553 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14554 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14555 */
14556 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14557
14558 /* Methods */
14559
14560 /**
14561 * @inheritdoc
14562 * @protected
14563 */
14564 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14565 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14566 config.type :
14567 'button';
14568 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14569 };
14570
14571 /**
14572 * Set label value.
14573 *
14574 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14575 *
14576 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14577 * text, or `null` for no label
14578 * @chainable
14579 */
14580 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14581 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14582
14583 if ( this.useInputTag ) {
14584 if ( typeof label === 'function' ) {
14585 label = OO.ui.resolveMsg( label );
14586 }
14587 if ( label instanceof jQuery ) {
14588 label = label.text();
14589 }
14590 if ( !label ) {
14591 label = '';
14592 }
14593 this.$input.val( label );
14594 }
14595
14596 return this;
14597 };
14598
14599 /**
14600 * Set the value of the input.
14601 *
14602 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14603 * they do not support {@link #value values}.
14604 *
14605 * @param {string} value New value
14606 * @chainable
14607 */
14608 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14609 if ( !this.useInputTag ) {
14610 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14611 }
14612 return this;
14613 };
14614
14615 /**
14616 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14617 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14618 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14619 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14620 *
14621 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14622 *
14623 * @example
14624 * // An example of selected, unselected, and disabled checkbox inputs
14625 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14626 * value: 'a',
14627 * selected: true
14628 * } );
14629 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14630 * value: 'b'
14631 * } );
14632 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14633 * value:'c',
14634 * disabled: true
14635 * } );
14636 * // Create a fieldset layout with fields for each checkbox.
14637 * var fieldset = new OO.ui.FieldsetLayout( {
14638 * label: 'Checkboxes'
14639 * } );
14640 * fieldset.addItems( [
14641 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14642 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14643 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14644 * ] );
14645 * $( 'body' ).append( fieldset.$element );
14646 *
14647 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14648 *
14649 * @class
14650 * @extends OO.ui.InputWidget
14651 *
14652 * @constructor
14653 * @param {Object} [config] Configuration options
14654 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14655 */
14656 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14657 // Configuration initialization
14658 config = config || {};
14659
14660 // Parent constructor
14661 OO.ui.CheckboxInputWidget.parent.call( this, config );
14662
14663 // Initialization
14664 this.$element
14665 .addClass( 'oo-ui-checkboxInputWidget' )
14666 // Required for pretty styling in MediaWiki theme
14667 .append( $( '<span>' ) );
14668 this.setSelected( config.selected !== undefined ? config.selected : false );
14669 };
14670
14671 /* Setup */
14672
14673 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14674
14675 /* Methods */
14676
14677 /**
14678 * @inheritdoc
14679 * @protected
14680 */
14681 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14682 return $( '<input type="checkbox" />' );
14683 };
14684
14685 /**
14686 * @inheritdoc
14687 */
14688 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14689 var widget = this;
14690 if ( !this.isDisabled() ) {
14691 // Allow the stack to clear so the value will be updated
14692 setTimeout( function () {
14693 widget.setSelected( widget.$input.prop( 'checked' ) );
14694 } );
14695 }
14696 };
14697
14698 /**
14699 * Set selection state of this checkbox.
14700 *
14701 * @param {boolean} state `true` for selected
14702 * @chainable
14703 */
14704 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14705 state = !!state;
14706 if ( this.selected !== state ) {
14707 this.selected = state;
14708 this.$input.prop( 'checked', this.selected );
14709 this.emit( 'change', this.selected );
14710 }
14711 return this;
14712 };
14713
14714 /**
14715 * Check if this checkbox is selected.
14716 *
14717 * @return {boolean} Checkbox is selected
14718 */
14719 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14720 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14721 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14722 var selected = this.$input.prop( 'checked' );
14723 if ( this.selected !== selected ) {
14724 this.setSelected( selected );
14725 }
14726 return this.selected;
14727 };
14728
14729 /**
14730 * @inheritdoc
14731 */
14732 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14733 var
14734 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14735 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14736 state.$input = $input; // shortcut for performance, used in InputWidget
14737 state.checked = $input.prop( 'checked' );
14738 return state;
14739 };
14740
14741 /**
14742 * @inheritdoc
14743 */
14744 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14745 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14746 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14747 this.setSelected( state.checked );
14748 }
14749 };
14750
14751 /**
14752 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14753 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14754 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14755 * more information about input widgets.
14756 *
14757 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14758 * are no options. If no `value` configuration option is provided, the first option is selected.
14759 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14760 *
14761 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14762 *
14763 * @example
14764 * // Example: A DropdownInputWidget with three options
14765 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14766 * options: [
14767 * { data: 'a', label: 'First' },
14768 * { data: 'b', label: 'Second'},
14769 * { data: 'c', label: 'Third' }
14770 * ]
14771 * } );
14772 * $( 'body' ).append( dropdownInput.$element );
14773 *
14774 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14775 *
14776 * @class
14777 * @extends OO.ui.InputWidget
14778 * @mixins OO.ui.mixin.TitledElement
14779 *
14780 * @constructor
14781 * @param {Object} [config] Configuration options
14782 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14783 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
14784 */
14785 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
14786 // Configuration initialization
14787 config = config || {};
14788
14789 // Properties (must be done before parent constructor which calls #setDisabled)
14790 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
14791
14792 // Parent constructor
14793 OO.ui.DropdownInputWidget.parent.call( this, config );
14794
14795 // Mixin constructors
14796 OO.ui.mixin.TitledElement.call( this, config );
14797
14798 // Events
14799 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
14800
14801 // Initialization
14802 this.setOptions( config.options || [] );
14803 this.$element
14804 .addClass( 'oo-ui-dropdownInputWidget' )
14805 .append( this.dropdownWidget.$element );
14806 };
14807
14808 /* Setup */
14809
14810 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
14811 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
14812
14813 /* Methods */
14814
14815 /**
14816 * @inheritdoc
14817 * @protected
14818 */
14819 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
14820 return $( '<input type="hidden">' );
14821 };
14822
14823 /**
14824 * Handles menu select events.
14825 *
14826 * @private
14827 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14828 */
14829 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
14830 this.setValue( item.getData() );
14831 };
14832
14833 /**
14834 * @inheritdoc
14835 */
14836 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
14837 value = this.cleanUpValue( value );
14838 this.dropdownWidget.getMenu().selectItemByData( value );
14839 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
14840 return this;
14841 };
14842
14843 /**
14844 * @inheritdoc
14845 */
14846 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
14847 this.dropdownWidget.setDisabled( state );
14848 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
14849 return this;
14850 };
14851
14852 /**
14853 * Set the options available for this input.
14854 *
14855 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14856 * @chainable
14857 */
14858 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
14859 var
14860 value = this.getValue(),
14861 widget = this;
14862
14863 // Rebuild the dropdown menu
14864 this.dropdownWidget.getMenu()
14865 .clearItems()
14866 .addItems( options.map( function ( opt ) {
14867 var optValue = widget.cleanUpValue( opt.data );
14868 return new OO.ui.MenuOptionWidget( {
14869 data: optValue,
14870 label: opt.label !== undefined ? opt.label : optValue
14871 } );
14872 } ) );
14873
14874 // Restore the previous value, or reset to something sensible
14875 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
14876 // Previous value is still available, ensure consistency with the dropdown
14877 this.setValue( value );
14878 } else {
14879 // No longer valid, reset
14880 if ( options.length ) {
14881 this.setValue( options[ 0 ].data );
14882 }
14883 }
14884
14885 return this;
14886 };
14887
14888 /**
14889 * @inheritdoc
14890 */
14891 OO.ui.DropdownInputWidget.prototype.focus = function () {
14892 this.dropdownWidget.getMenu().toggle( true );
14893 return this;
14894 };
14895
14896 /**
14897 * @inheritdoc
14898 */
14899 OO.ui.DropdownInputWidget.prototype.blur = function () {
14900 this.dropdownWidget.getMenu().toggle( false );
14901 return this;
14902 };
14903
14904 /**
14905 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14906 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14907 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14908 * please see the [OOjs UI documentation on MediaWiki][1].
14909 *
14910 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14911 *
14912 * @example
14913 * // An example of selected, unselected, and disabled radio inputs
14914 * var radio1 = new OO.ui.RadioInputWidget( {
14915 * value: 'a',
14916 * selected: true
14917 * } );
14918 * var radio2 = new OO.ui.RadioInputWidget( {
14919 * value: 'b'
14920 * } );
14921 * var radio3 = new OO.ui.RadioInputWidget( {
14922 * value: 'c',
14923 * disabled: true
14924 * } );
14925 * // Create a fieldset layout with fields for each radio button.
14926 * var fieldset = new OO.ui.FieldsetLayout( {
14927 * label: 'Radio inputs'
14928 * } );
14929 * fieldset.addItems( [
14930 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14931 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14932 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14933 * ] );
14934 * $( 'body' ).append( fieldset.$element );
14935 *
14936 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14937 *
14938 * @class
14939 * @extends OO.ui.InputWidget
14940 *
14941 * @constructor
14942 * @param {Object} [config] Configuration options
14943 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14944 */
14945 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
14946 // Configuration initialization
14947 config = config || {};
14948
14949 // Parent constructor
14950 OO.ui.RadioInputWidget.parent.call( this, config );
14951
14952 // Initialization
14953 this.$element
14954 .addClass( 'oo-ui-radioInputWidget' )
14955 // Required for pretty styling in MediaWiki theme
14956 .append( $( '<span>' ) );
14957 this.setSelected( config.selected !== undefined ? config.selected : false );
14958 };
14959
14960 /* Setup */
14961
14962 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
14963
14964 /* Methods */
14965
14966 /**
14967 * @inheritdoc
14968 * @protected
14969 */
14970 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
14971 return $( '<input type="radio" />' );
14972 };
14973
14974 /**
14975 * @inheritdoc
14976 */
14977 OO.ui.RadioInputWidget.prototype.onEdit = function () {
14978 // RadioInputWidget doesn't track its state.
14979 };
14980
14981 /**
14982 * Set selection state of this radio button.
14983 *
14984 * @param {boolean} state `true` for selected
14985 * @chainable
14986 */
14987 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
14988 // RadioInputWidget doesn't track its state.
14989 this.$input.prop( 'checked', state );
14990 return this;
14991 };
14992
14993 /**
14994 * Check if this radio button is selected.
14995 *
14996 * @return {boolean} Radio is selected
14997 */
14998 OO.ui.RadioInputWidget.prototype.isSelected = function () {
14999 return this.$input.prop( 'checked' );
15000 };
15001
15002 /**
15003 * @inheritdoc
15004 */
15005 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15006 var
15007 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15008 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15009 state.$input = $input; // shortcut for performance, used in InputWidget
15010 state.checked = $input.prop( 'checked' );
15011 return state;
15012 };
15013
15014 /**
15015 * @inheritdoc
15016 */
15017 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15018 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15019 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15020 this.setSelected( state.checked );
15021 }
15022 };
15023
15024 /**
15025 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15026 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15027 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15028 * more information about input widgets.
15029 *
15030 * This and OO.ui.DropdownInputWidget support the same configuration options.
15031 *
15032 * @example
15033 * // Example: A RadioSelectInputWidget with three options
15034 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15035 * options: [
15036 * { data: 'a', label: 'First' },
15037 * { data: 'b', label: 'Second'},
15038 * { data: 'c', label: 'Third' }
15039 * ]
15040 * } );
15041 * $( 'body' ).append( radioSelectInput.$element );
15042 *
15043 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15044 *
15045 * @class
15046 * @extends OO.ui.InputWidget
15047 *
15048 * @constructor
15049 * @param {Object} [config] Configuration options
15050 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15051 */
15052 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15053 // Configuration initialization
15054 config = config || {};
15055
15056 // Properties (must be done before parent constructor which calls #setDisabled)
15057 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15058
15059 // Parent constructor
15060 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15061
15062 // Events
15063 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15064
15065 // Initialization
15066 this.setOptions( config.options || [] );
15067 this.$element
15068 .addClass( 'oo-ui-radioSelectInputWidget' )
15069 .append( this.radioSelectWidget.$element );
15070 };
15071
15072 /* Setup */
15073
15074 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15075
15076 /* Static Properties */
15077
15078 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15079
15080 /* Methods */
15081
15082 /**
15083 * @inheritdoc
15084 * @protected
15085 */
15086 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15087 return $( '<input type="hidden">' );
15088 };
15089
15090 /**
15091 * Handles menu select events.
15092 *
15093 * @private
15094 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15095 */
15096 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15097 this.setValue( item.getData() );
15098 };
15099
15100 /**
15101 * @inheritdoc
15102 */
15103 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15104 value = this.cleanUpValue( value );
15105 this.radioSelectWidget.selectItemByData( value );
15106 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15107 return this;
15108 };
15109
15110 /**
15111 * @inheritdoc
15112 */
15113 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15114 this.radioSelectWidget.setDisabled( state );
15115 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15116 return this;
15117 };
15118
15119 /**
15120 * Set the options available for this input.
15121 *
15122 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15123 * @chainable
15124 */
15125 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15126 var
15127 value = this.getValue(),
15128 widget = this;
15129
15130 // Rebuild the radioSelect menu
15131 this.radioSelectWidget
15132 .clearItems()
15133 .addItems( options.map( function ( opt ) {
15134 var optValue = widget.cleanUpValue( opt.data );
15135 return new OO.ui.RadioOptionWidget( {
15136 data: optValue,
15137 label: opt.label !== undefined ? opt.label : optValue
15138 } );
15139 } ) );
15140
15141 // Restore the previous value, or reset to something sensible
15142 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15143 // Previous value is still available, ensure consistency with the radioSelect
15144 this.setValue( value );
15145 } else {
15146 // No longer valid, reset
15147 if ( options.length ) {
15148 this.setValue( options[ 0 ].data );
15149 }
15150 }
15151
15152 return this;
15153 };
15154
15155 /**
15156 * @inheritdoc
15157 */
15158 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15159 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15160 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15161 return state;
15162 };
15163
15164 /**
15165 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15166 * size of the field as well as its presentation. In addition, these widgets can be configured
15167 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15168 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15169 * which modifies incoming values rather than validating them.
15170 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15171 *
15172 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15173 *
15174 * @example
15175 * // Example of a text input widget
15176 * var textInput = new OO.ui.TextInputWidget( {
15177 * value: 'Text input'
15178 * } )
15179 * $( 'body' ).append( textInput.$element );
15180 *
15181 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15182 *
15183 * @class
15184 * @extends OO.ui.InputWidget
15185 * @mixins OO.ui.mixin.IconElement
15186 * @mixins OO.ui.mixin.IndicatorElement
15187 * @mixins OO.ui.mixin.PendingElement
15188 * @mixins OO.ui.mixin.LabelElement
15189 *
15190 * @constructor
15191 * @param {Object} [config] Configuration options
15192 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15193 * 'email' or 'url'. Ignored if `multiline` is true.
15194 *
15195 * Some values of `type` result in additional behaviors:
15196 *
15197 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15198 * empties the text field
15199 * @cfg {string} [placeholder] Placeholder text
15200 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15201 * instruct the browser to focus this widget.
15202 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15203 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15204 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15205 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15206 * specifies minimum number of rows to display.
15207 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15208 * Use the #maxRows config to specify a maximum number of displayed rows.
15209 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15210 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15211 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15212 * the value or placeholder text: `'before'` or `'after'`
15213 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15214 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15215 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15216 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15217 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15218 * value for it to be considered valid; when Function, a function receiving the value as parameter
15219 * that must return true, or promise resolving to true, for it to be considered valid.
15220 */
15221 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15222 // Configuration initialization
15223 config = $.extend( {
15224 type: 'text',
15225 labelPosition: 'after'
15226 }, config );
15227 if ( config.type === 'search' ) {
15228 if ( config.icon === undefined ) {
15229 config.icon = 'search';
15230 }
15231 // indicator: 'clear' is set dynamically later, depending on value
15232 }
15233 if ( config.required ) {
15234 if ( config.indicator === undefined ) {
15235 config.indicator = 'required';
15236 }
15237 }
15238
15239 // Parent constructor
15240 OO.ui.TextInputWidget.parent.call( this, config );
15241
15242 // Mixin constructors
15243 OO.ui.mixin.IconElement.call( this, config );
15244 OO.ui.mixin.IndicatorElement.call( this, config );
15245 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15246 OO.ui.mixin.LabelElement.call( this, config );
15247
15248 // Properties
15249 this.type = this.getSaneType( config );
15250 this.readOnly = false;
15251 this.multiline = !!config.multiline;
15252 this.autosize = !!config.autosize;
15253 this.minRows = config.rows !== undefined ? config.rows : '';
15254 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15255 this.validate = null;
15256
15257 // Clone for resizing
15258 if ( this.autosize ) {
15259 this.$clone = this.$input
15260 .clone()
15261 .insertAfter( this.$input )
15262 .attr( 'aria-hidden', 'true' )
15263 .addClass( 'oo-ui-element-hidden' );
15264 }
15265
15266 this.setValidation( config.validate );
15267 this.setLabelPosition( config.labelPosition );
15268
15269 // Events
15270 this.$input.on( {
15271 keypress: this.onKeyPress.bind( this ),
15272 blur: this.onBlur.bind( this )
15273 } );
15274 this.$input.one( {
15275 focus: this.onElementAttach.bind( this )
15276 } );
15277 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15278 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15279 this.on( 'labelChange', this.updatePosition.bind( this ) );
15280 this.connect( this, {
15281 change: 'onChange',
15282 disable: 'onDisable'
15283 } );
15284
15285 // Initialization
15286 this.$element
15287 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15288 .append( this.$icon, this.$indicator );
15289 this.setReadOnly( !!config.readOnly );
15290 this.updateSearchIndicator();
15291 if ( config.placeholder ) {
15292 this.$input.attr( 'placeholder', config.placeholder );
15293 }
15294 if ( config.maxLength !== undefined ) {
15295 this.$input.attr( 'maxlength', config.maxLength );
15296 }
15297 if ( config.autofocus ) {
15298 this.$input.attr( 'autofocus', 'autofocus' );
15299 }
15300 if ( config.required ) {
15301 this.$input.attr( 'required', 'required' );
15302 this.$input.attr( 'aria-required', 'true' );
15303 }
15304 if ( config.autocomplete === false ) {
15305 this.$input.attr( 'autocomplete', 'off' );
15306 }
15307 if ( this.multiline && config.rows ) {
15308 this.$input.attr( 'rows', config.rows );
15309 }
15310 if ( this.label || config.autosize ) {
15311 this.installParentChangeDetector();
15312 }
15313 };
15314
15315 /* Setup */
15316
15317 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15318 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15319 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15320 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15321 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15322
15323 /* Static Properties */
15324
15325 OO.ui.TextInputWidget.static.validationPatterns = {
15326 'non-empty': /.+/,
15327 integer: /^\d+$/
15328 };
15329
15330 /* Events */
15331
15332 /**
15333 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15334 *
15335 * Not emitted if the input is multiline.
15336 *
15337 * @event enter
15338 */
15339
15340 /* Methods */
15341
15342 /**
15343 * Handle icon mouse down events.
15344 *
15345 * @private
15346 * @param {jQuery.Event} e Mouse down event
15347 * @fires icon
15348 */
15349 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15350 if ( e.which === 1 ) {
15351 this.$input[ 0 ].focus();
15352 return false;
15353 }
15354 };
15355
15356 /**
15357 * Handle indicator mouse down events.
15358 *
15359 * @private
15360 * @param {jQuery.Event} e Mouse down event
15361 * @fires indicator
15362 */
15363 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15364 if ( e.which === 1 ) {
15365 if ( this.type === 'search' ) {
15366 // Clear the text field
15367 this.setValue( '' );
15368 }
15369 this.$input[ 0 ].focus();
15370 return false;
15371 }
15372 };
15373
15374 /**
15375 * Handle key press events.
15376 *
15377 * @private
15378 * @param {jQuery.Event} e Key press event
15379 * @fires enter If enter key is pressed and input is not multiline
15380 */
15381 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15382 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15383 this.emit( 'enter', e );
15384 }
15385 };
15386
15387 /**
15388 * Handle blur events.
15389 *
15390 * @private
15391 * @param {jQuery.Event} e Blur event
15392 */
15393 OO.ui.TextInputWidget.prototype.onBlur = function () {
15394 this.setValidityFlag();
15395 };
15396
15397 /**
15398 * Handle element attach events.
15399 *
15400 * @private
15401 * @param {jQuery.Event} e Element attach event
15402 */
15403 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15404 // Any previously calculated size is now probably invalid if we reattached elsewhere
15405 this.valCache = null;
15406 this.adjustSize();
15407 this.positionLabel();
15408 };
15409
15410 /**
15411 * Handle change events.
15412 *
15413 * @param {string} value
15414 * @private
15415 */
15416 OO.ui.TextInputWidget.prototype.onChange = function () {
15417 this.updateSearchIndicator();
15418 this.setValidityFlag();
15419 this.adjustSize();
15420 };
15421
15422 /**
15423 * Handle disable events.
15424 *
15425 * @param {boolean} disabled Element is disabled
15426 * @private
15427 */
15428 OO.ui.TextInputWidget.prototype.onDisable = function () {
15429 this.updateSearchIndicator();
15430 };
15431
15432 /**
15433 * Check if the input is {@link #readOnly read-only}.
15434 *
15435 * @return {boolean}
15436 */
15437 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15438 return this.readOnly;
15439 };
15440
15441 /**
15442 * Set the {@link #readOnly read-only} state of the input.
15443 *
15444 * @param {boolean} state Make input read-only
15445 * @chainable
15446 */
15447 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15448 this.readOnly = !!state;
15449 this.$input.prop( 'readOnly', this.readOnly );
15450 this.updateSearchIndicator();
15451 return this;
15452 };
15453
15454 /**
15455 * Support function for making #onElementAttach work across browsers.
15456 *
15457 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15458 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15459 *
15460 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15461 * first time that the element gets attached to the documented.
15462 */
15463 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15464 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15465 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15466 widget = this;
15467
15468 if ( MutationObserver ) {
15469 // The new way. If only it wasn't so ugly.
15470
15471 if ( this.$element.closest( 'html' ).length ) {
15472 // Widget is attached already, do nothing. This breaks the functionality of this function when
15473 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15474 // would require observation of the whole document, which would hurt performance of other,
15475 // more important code.
15476 return;
15477 }
15478
15479 // Find topmost node in the tree
15480 topmostNode = this.$element[ 0 ];
15481 while ( topmostNode.parentNode ) {
15482 topmostNode = topmostNode.parentNode;
15483 }
15484
15485 // We have no way to detect the $element being attached somewhere without observing the entire
15486 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15487 // parent node of $element, and instead detect when $element is removed from it (and thus
15488 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15489 // doesn't get attached, we end up back here and create the parent.
15490
15491 mutationObserver = new MutationObserver( function ( mutations ) {
15492 var i, j, removedNodes;
15493 for ( i = 0; i < mutations.length; i++ ) {
15494 removedNodes = mutations[ i ].removedNodes;
15495 for ( j = 0; j < removedNodes.length; j++ ) {
15496 if ( removedNodes[ j ] === topmostNode ) {
15497 setTimeout( onRemove, 0 );
15498 return;
15499 }
15500 }
15501 }
15502 } );
15503
15504 onRemove = function () {
15505 // If the node was attached somewhere else, report it
15506 if ( widget.$element.closest( 'html' ).length ) {
15507 widget.onElementAttach();
15508 }
15509 mutationObserver.disconnect();
15510 widget.installParentChangeDetector();
15511 };
15512
15513 // Create a fake parent and observe it
15514 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15515 mutationObserver.observe( fakeParentNode, { childList: true } );
15516 } else {
15517 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15518 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15519 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15520 }
15521 };
15522
15523 /**
15524 * Automatically adjust the size of the text input.
15525 *
15526 * This only affects #multiline inputs that are {@link #autosize autosized}.
15527 *
15528 * @chainable
15529 */
15530 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15531 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15532
15533 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15534 this.$clone
15535 .val( this.$input.val() )
15536 .attr( 'rows', this.minRows )
15537 // Set inline height property to 0 to measure scroll height
15538 .css( 'height', 0 );
15539
15540 this.$clone.removeClass( 'oo-ui-element-hidden' );
15541
15542 this.valCache = this.$input.val();
15543
15544 scrollHeight = this.$clone[ 0 ].scrollHeight;
15545
15546 // Remove inline height property to measure natural heights
15547 this.$clone.css( 'height', '' );
15548 innerHeight = this.$clone.innerHeight();
15549 outerHeight = this.$clone.outerHeight();
15550
15551 // Measure max rows height
15552 this.$clone
15553 .attr( 'rows', this.maxRows )
15554 .css( 'height', 'auto' )
15555 .val( '' );
15556 maxInnerHeight = this.$clone.innerHeight();
15557
15558 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15559 // Equals 1 on Blink-based browsers and 0 everywhere else
15560 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15561 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15562
15563 this.$clone.addClass( 'oo-ui-element-hidden' );
15564
15565 // Only apply inline height when expansion beyond natural height is needed
15566 if ( idealHeight > innerHeight ) {
15567 // Use the difference between the inner and outer height as a buffer
15568 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15569 } else {
15570 this.$input.css( 'height', '' );
15571 }
15572 }
15573 return this;
15574 };
15575
15576 /**
15577 * @inheritdoc
15578 * @protected
15579 */
15580 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15581 return config.multiline ?
15582 $( '<textarea>' ) :
15583 $( '<input type="' + this.getSaneType( config ) + '" />' );
15584 };
15585
15586 /**
15587 * Get sanitized value for 'type' for given config.
15588 *
15589 * @param {Object} config Configuration options
15590 * @return {string|null}
15591 * @private
15592 */
15593 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15594 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15595 config.type :
15596 'text';
15597 return config.multiline ? 'multiline' : type;
15598 };
15599
15600 /**
15601 * Check if the input supports multiple lines.
15602 *
15603 * @return {boolean}
15604 */
15605 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15606 return !!this.multiline;
15607 };
15608
15609 /**
15610 * Check if the input automatically adjusts its size.
15611 *
15612 * @return {boolean}
15613 */
15614 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15615 return !!this.autosize;
15616 };
15617
15618 /**
15619 * Select the entire text of the input.
15620 *
15621 * @chainable
15622 */
15623 OO.ui.TextInputWidget.prototype.select = function () {
15624 this.$input.select();
15625 return this;
15626 };
15627
15628 /**
15629 * Focus the input and move the cursor to the end.
15630 */
15631 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15632 var textRange,
15633 element = this.$input[ 0 ];
15634 this.focus();
15635 if ( element.selectionStart !== undefined ) {
15636 element.selectionStart = element.selectionEnd = element.value.length;
15637 } else if ( element.createTextRange ) {
15638 // IE 8 and below
15639 textRange = element.createTextRange();
15640 textRange.collapse( false );
15641 textRange.select();
15642 }
15643 };
15644
15645 /**
15646 * Set the validation pattern.
15647 *
15648 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15649 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15650 * value must contain only numbers).
15651 *
15652 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15653 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15654 */
15655 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15656 if ( validate instanceof RegExp || validate instanceof Function ) {
15657 this.validate = validate;
15658 } else {
15659 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15660 }
15661 };
15662
15663 /**
15664 * Sets the 'invalid' flag appropriately.
15665 *
15666 * @param {boolean} [isValid] Optionally override validation result
15667 */
15668 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15669 var widget = this,
15670 setFlag = function ( valid ) {
15671 if ( !valid ) {
15672 widget.$input.attr( 'aria-invalid', 'true' );
15673 } else {
15674 widget.$input.removeAttr( 'aria-invalid' );
15675 }
15676 widget.setFlags( { invalid: !valid } );
15677 };
15678
15679 if ( isValid !== undefined ) {
15680 setFlag( isValid );
15681 } else {
15682 this.getValidity().then( function () {
15683 setFlag( true );
15684 }, function () {
15685 setFlag( false );
15686 } );
15687 }
15688 };
15689
15690 /**
15691 * Check if a value is valid.
15692 *
15693 * This method returns a promise that resolves with a boolean `true` if the current value is
15694 * considered valid according to the supplied {@link #validate validation pattern}.
15695 *
15696 * @deprecated
15697 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15698 */
15699 OO.ui.TextInputWidget.prototype.isValid = function () {
15700 var result;
15701
15702 if ( this.validate instanceof Function ) {
15703 result = this.validate( this.getValue() );
15704 if ( $.isFunction( result.promise ) ) {
15705 return result.promise();
15706 } else {
15707 return $.Deferred().resolve( !!result ).promise();
15708 }
15709 } else {
15710 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15711 }
15712 };
15713
15714 /**
15715 * Get the validity of current value.
15716 *
15717 * This method returns a promise that resolves if the value is valid and rejects if
15718 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15719 *
15720 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15721 */
15722 OO.ui.TextInputWidget.prototype.getValidity = function () {
15723 var result, promise;
15724
15725 function rejectOrResolve( valid ) {
15726 if ( valid ) {
15727 return $.Deferred().resolve().promise();
15728 } else {
15729 return $.Deferred().reject().promise();
15730 }
15731 }
15732
15733 if ( this.validate instanceof Function ) {
15734 result = this.validate( this.getValue() );
15735
15736 if ( $.isFunction( result.promise ) ) {
15737 promise = $.Deferred();
15738
15739 result.then( function ( valid ) {
15740 if ( valid ) {
15741 promise.resolve();
15742 } else {
15743 promise.reject();
15744 }
15745 }, function () {
15746 promise.reject();
15747 } );
15748
15749 return promise.promise();
15750 } else {
15751 return rejectOrResolve( result );
15752 }
15753 } else {
15754 return rejectOrResolve( this.getValue().match( this.validate ) );
15755 }
15756 };
15757
15758 /**
15759 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15760 *
15761 * @param {string} labelPosition Label position, 'before' or 'after'
15762 * @chainable
15763 */
15764 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
15765 this.labelPosition = labelPosition;
15766 this.updatePosition();
15767 return this;
15768 };
15769
15770 /**
15771 * Deprecated alias of #setLabelPosition
15772 *
15773 * @deprecated Use setLabelPosition instead.
15774 */
15775 OO.ui.TextInputWidget.prototype.setPosition =
15776 OO.ui.TextInputWidget.prototype.setLabelPosition;
15777
15778 /**
15779 * Update the position of the inline label.
15780 *
15781 * This method is called by #setLabelPosition, and can also be called on its own if
15782 * something causes the label to be mispositioned.
15783 *
15784 * @chainable
15785 */
15786 OO.ui.TextInputWidget.prototype.updatePosition = function () {
15787 var after = this.labelPosition === 'after';
15788
15789 this.$element
15790 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
15791 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
15792
15793 this.positionLabel();
15794
15795 return this;
15796 };
15797
15798 /**
15799 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15800 * already empty or when it's not editable.
15801 */
15802 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
15803 if ( this.type === 'search' ) {
15804 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15805 this.setIndicator( null );
15806 } else {
15807 this.setIndicator( 'clear' );
15808 }
15809 }
15810 };
15811
15812 /**
15813 * Position the label by setting the correct padding on the input.
15814 *
15815 * @private
15816 * @chainable
15817 */
15818 OO.ui.TextInputWidget.prototype.positionLabel = function () {
15819 var after, rtl, property;
15820 // Clear old values
15821 this.$input
15822 // Clear old values if present
15823 .css( {
15824 'padding-right': '',
15825 'padding-left': ''
15826 } );
15827
15828 if ( this.label ) {
15829 this.$element.append( this.$label );
15830 } else {
15831 this.$label.detach();
15832 return;
15833 }
15834
15835 after = this.labelPosition === 'after';
15836 rtl = this.$element.css( 'direction' ) === 'rtl';
15837 property = after === rtl ? 'padding-left' : 'padding-right';
15838
15839 this.$input.css( property, this.$label.outerWidth( true ) );
15840
15841 return this;
15842 };
15843
15844 /**
15845 * @inheritdoc
15846 */
15847 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15848 var
15849 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15850 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15851 state.$input = $input; // shortcut for performance, used in InputWidget
15852 if ( this.multiline ) {
15853 state.scrollTop = $input.scrollTop();
15854 }
15855 return state;
15856 };
15857
15858 /**
15859 * @inheritdoc
15860 */
15861 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
15862 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15863 if ( state.scrollTop !== undefined ) {
15864 this.$input.scrollTop( state.scrollTop );
15865 }
15866 };
15867
15868 /**
15869 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15870 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15871 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15872 *
15873 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15874 * option, that option will appear to be selected.
15875 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15876 * input field.
15877 *
15878 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15879 *
15880 * @example
15881 * // Example: A ComboBoxWidget.
15882 * var comboBox = new OO.ui.ComboBoxWidget( {
15883 * label: 'ComboBoxWidget',
15884 * input: { value: 'Option One' },
15885 * menu: {
15886 * items: [
15887 * new OO.ui.MenuOptionWidget( {
15888 * data: 'Option 1',
15889 * label: 'Option One'
15890 * } ),
15891 * new OO.ui.MenuOptionWidget( {
15892 * data: 'Option 2',
15893 * label: 'Option Two'
15894 * } ),
15895 * new OO.ui.MenuOptionWidget( {
15896 * data: 'Option 3',
15897 * label: 'Option Three'
15898 * } ),
15899 * new OO.ui.MenuOptionWidget( {
15900 * data: 'Option 4',
15901 * label: 'Option Four'
15902 * } ),
15903 * new OO.ui.MenuOptionWidget( {
15904 * data: 'Option 5',
15905 * label: 'Option Five'
15906 * } )
15907 * ]
15908 * }
15909 * } );
15910 * $( 'body' ).append( comboBox.$element );
15911 *
15912 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15913 *
15914 * @class
15915 * @extends OO.ui.Widget
15916 * @mixins OO.ui.mixin.TabIndexedElement
15917 *
15918 * @constructor
15919 * @param {Object} [config] Configuration options
15920 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15921 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15922 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15923 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15924 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15925 */
15926 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
15927 // Configuration initialization
15928 config = config || {};
15929
15930 // Parent constructor
15931 OO.ui.ComboBoxWidget.parent.call( this, config );
15932
15933 // Properties (must be set before TabIndexedElement constructor call)
15934 this.$indicator = this.$( '<span>' );
15935
15936 // Mixin constructors
15937 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
15938
15939 // Properties
15940 this.$overlay = config.$overlay || this.$element;
15941 this.input = new OO.ui.TextInputWidget( $.extend(
15942 {
15943 indicator: 'down',
15944 $indicator: this.$indicator,
15945 disabled: this.isDisabled()
15946 },
15947 config.input
15948 ) );
15949 this.input.$input.eq( 0 ).attr( {
15950 role: 'combobox',
15951 'aria-autocomplete': 'list'
15952 } );
15953 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
15954 {
15955 widget: this,
15956 input: this.input,
15957 $container: this.input.$element,
15958 disabled: this.isDisabled()
15959 },
15960 config.menu
15961 ) );
15962
15963 // Events
15964 this.$indicator.on( {
15965 click: this.onClick.bind( this ),
15966 keypress: this.onKeyPress.bind( this )
15967 } );
15968 this.input.connect( this, {
15969 change: 'onInputChange',
15970 enter: 'onInputEnter'
15971 } );
15972 this.menu.connect( this, {
15973 choose: 'onMenuChoose',
15974 add: 'onMenuItemsChange',
15975 remove: 'onMenuItemsChange'
15976 } );
15977
15978 // Initialization
15979 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
15980 this.$overlay.append( this.menu.$element );
15981 this.onMenuItemsChange();
15982 };
15983
15984 /* Setup */
15985
15986 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
15987 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
15988
15989 /* Methods */
15990
15991 /**
15992 * Get the combobox's menu.
15993 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
15994 */
15995 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
15996 return this.menu;
15997 };
15998
15999 /**
16000 * Get the combobox's text input widget.
16001 * @return {OO.ui.TextInputWidget} Text input widget
16002 */
16003 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16004 return this.input;
16005 };
16006
16007 /**
16008 * Handle input change events.
16009 *
16010 * @private
16011 * @param {string} value New value
16012 */
16013 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16014 var match = this.menu.getItemFromData( value );
16015
16016 this.menu.selectItem( match );
16017 if ( this.menu.getHighlightedItem() ) {
16018 this.menu.highlightItem( match );
16019 }
16020
16021 if ( !this.isDisabled() ) {
16022 this.menu.toggle( true );
16023 }
16024 };
16025
16026 /**
16027 * Handle mouse click events.
16028 *
16029 *
16030 * @private
16031 * @param {jQuery.Event} e Mouse click event
16032 */
16033 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16034 if ( !this.isDisabled() && e.which === 1 ) {
16035 this.menu.toggle();
16036 this.input.$input[ 0 ].focus();
16037 }
16038 return false;
16039 };
16040
16041 /**
16042 * Handle key press events.
16043 *
16044 *
16045 * @private
16046 * @param {jQuery.Event} e Key press event
16047 */
16048 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16049 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16050 this.menu.toggle();
16051 this.input.$input[ 0 ].focus();
16052 return false;
16053 }
16054 };
16055
16056 /**
16057 * Handle input enter events.
16058 *
16059 * @private
16060 */
16061 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16062 if ( !this.isDisabled() ) {
16063 this.menu.toggle( false );
16064 }
16065 };
16066
16067 /**
16068 * Handle menu choose events.
16069 *
16070 * @private
16071 * @param {OO.ui.OptionWidget} item Chosen item
16072 */
16073 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16074 this.input.setValue( item.getData() );
16075 };
16076
16077 /**
16078 * Handle menu item change events.
16079 *
16080 * @private
16081 */
16082 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16083 var match = this.menu.getItemFromData( this.input.getValue() );
16084 this.menu.selectItem( match );
16085 if ( this.menu.getHighlightedItem() ) {
16086 this.menu.highlightItem( match );
16087 }
16088 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16089 };
16090
16091 /**
16092 * @inheritdoc
16093 */
16094 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16095 // Parent method
16096 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16097
16098 if ( this.input ) {
16099 this.input.setDisabled( this.isDisabled() );
16100 }
16101 if ( this.menu ) {
16102 this.menu.setDisabled( this.isDisabled() );
16103 }
16104
16105 return this;
16106 };
16107
16108 /**
16109 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16110 * be configured with a `label` option that is set to a string, a label node, or a function:
16111 *
16112 * - String: a plaintext string
16113 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16114 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16115 * - Function: a function that will produce a string in the future. Functions are used
16116 * in cases where the value of the label is not currently defined.
16117 *
16118 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16119 * will come into focus when the label is clicked.
16120 *
16121 * @example
16122 * // Examples of LabelWidgets
16123 * var label1 = new OO.ui.LabelWidget( {
16124 * label: 'plaintext label'
16125 * } );
16126 * var label2 = new OO.ui.LabelWidget( {
16127 * label: $( '<a href="default.html">jQuery label</a>' )
16128 * } );
16129 * // Create a fieldset layout with fields for each example
16130 * var fieldset = new OO.ui.FieldsetLayout();
16131 * fieldset.addItems( [
16132 * new OO.ui.FieldLayout( label1 ),
16133 * new OO.ui.FieldLayout( label2 )
16134 * ] );
16135 * $( 'body' ).append( fieldset.$element );
16136 *
16137 *
16138 * @class
16139 * @extends OO.ui.Widget
16140 * @mixins OO.ui.mixin.LabelElement
16141 *
16142 * @constructor
16143 * @param {Object} [config] Configuration options
16144 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16145 * Clicking the label will focus the specified input field.
16146 */
16147 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16148 // Configuration initialization
16149 config = config || {};
16150
16151 // Parent constructor
16152 OO.ui.LabelWidget.parent.call( this, config );
16153
16154 // Mixin constructors
16155 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16156 OO.ui.mixin.TitledElement.call( this, config );
16157
16158 // Properties
16159 this.input = config.input;
16160
16161 // Events
16162 if ( this.input instanceof OO.ui.InputWidget ) {
16163 this.$element.on( 'click', this.onClick.bind( this ) );
16164 }
16165
16166 // Initialization
16167 this.$element.addClass( 'oo-ui-labelWidget' );
16168 };
16169
16170 /* Setup */
16171
16172 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16173 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16174 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16175
16176 /* Static Properties */
16177
16178 OO.ui.LabelWidget.static.tagName = 'span';
16179
16180 /* Methods */
16181
16182 /**
16183 * Handles label mouse click events.
16184 *
16185 * @private
16186 * @param {jQuery.Event} e Mouse click event
16187 */
16188 OO.ui.LabelWidget.prototype.onClick = function () {
16189 this.input.simulateLabelClick();
16190 return false;
16191 };
16192
16193 /**
16194 * OptionWidgets are special elements that can be selected and configured with data. The
16195 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16196 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16197 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16198 *
16199 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16200 *
16201 * @class
16202 * @extends OO.ui.Widget
16203 * @mixins OO.ui.mixin.LabelElement
16204 * @mixins OO.ui.mixin.FlaggedElement
16205 *
16206 * @constructor
16207 * @param {Object} [config] Configuration options
16208 */
16209 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16210 // Configuration initialization
16211 config = config || {};
16212
16213 // Parent constructor
16214 OO.ui.OptionWidget.parent.call( this, config );
16215
16216 // Mixin constructors
16217 OO.ui.mixin.ItemWidget.call( this );
16218 OO.ui.mixin.LabelElement.call( this, config );
16219 OO.ui.mixin.FlaggedElement.call( this, config );
16220
16221 // Properties
16222 this.selected = false;
16223 this.highlighted = false;
16224 this.pressed = false;
16225
16226 // Initialization
16227 this.$element
16228 .data( 'oo-ui-optionWidget', this )
16229 .attr( 'role', 'option' )
16230 .attr( 'aria-selected', 'false' )
16231 .addClass( 'oo-ui-optionWidget' )
16232 .append( this.$label );
16233 };
16234
16235 /* Setup */
16236
16237 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16238 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16239 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16240 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16241
16242 /* Static Properties */
16243
16244 OO.ui.OptionWidget.static.selectable = true;
16245
16246 OO.ui.OptionWidget.static.highlightable = true;
16247
16248 OO.ui.OptionWidget.static.pressable = true;
16249
16250 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16251
16252 /* Methods */
16253
16254 /**
16255 * Check if the option can be selected.
16256 *
16257 * @return {boolean} Item is selectable
16258 */
16259 OO.ui.OptionWidget.prototype.isSelectable = function () {
16260 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16261 };
16262
16263 /**
16264 * Check if the option can be highlighted. A highlight indicates that the option
16265 * may be selected when a user presses enter or clicks. Disabled items cannot
16266 * be highlighted.
16267 *
16268 * @return {boolean} Item is highlightable
16269 */
16270 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16271 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16272 };
16273
16274 /**
16275 * Check if the option can be pressed. The pressed state occurs when a user mouses
16276 * down on an item, but has not yet let go of the mouse.
16277 *
16278 * @return {boolean} Item is pressable
16279 */
16280 OO.ui.OptionWidget.prototype.isPressable = function () {
16281 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16282 };
16283
16284 /**
16285 * Check if the option is selected.
16286 *
16287 * @return {boolean} Item is selected
16288 */
16289 OO.ui.OptionWidget.prototype.isSelected = function () {
16290 return this.selected;
16291 };
16292
16293 /**
16294 * Check if the option is highlighted. A highlight indicates that the
16295 * item may be selected when a user presses enter or clicks.
16296 *
16297 * @return {boolean} Item is highlighted
16298 */
16299 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16300 return this.highlighted;
16301 };
16302
16303 /**
16304 * Check if the option is pressed. The pressed state occurs when a user mouses
16305 * down on an item, but has not yet let go of the mouse. The item may appear
16306 * selected, but it will not be selected until the user releases the mouse.
16307 *
16308 * @return {boolean} Item is pressed
16309 */
16310 OO.ui.OptionWidget.prototype.isPressed = function () {
16311 return this.pressed;
16312 };
16313
16314 /**
16315 * Set the option’s selected state. In general, all modifications to the selection
16316 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16317 * method instead of this method.
16318 *
16319 * @param {boolean} [state=false] Select option
16320 * @chainable
16321 */
16322 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16323 if ( this.constructor.static.selectable ) {
16324 this.selected = !!state;
16325 this.$element
16326 .toggleClass( 'oo-ui-optionWidget-selected', state )
16327 .attr( 'aria-selected', state.toString() );
16328 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16329 this.scrollElementIntoView();
16330 }
16331 this.updateThemeClasses();
16332 }
16333 return this;
16334 };
16335
16336 /**
16337 * Set the option’s highlighted state. In general, all programmatic
16338 * modifications to the highlight should be handled by the
16339 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16340 * method instead of this method.
16341 *
16342 * @param {boolean} [state=false] Highlight option
16343 * @chainable
16344 */
16345 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16346 if ( this.constructor.static.highlightable ) {
16347 this.highlighted = !!state;
16348 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16349 this.updateThemeClasses();
16350 }
16351 return this;
16352 };
16353
16354 /**
16355 * Set the option’s pressed state. In general, all
16356 * programmatic modifications to the pressed state should be handled by the
16357 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16358 * method instead of this method.
16359 *
16360 * @param {boolean} [state=false] Press option
16361 * @chainable
16362 */
16363 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16364 if ( this.constructor.static.pressable ) {
16365 this.pressed = !!state;
16366 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16367 this.updateThemeClasses();
16368 }
16369 return this;
16370 };
16371
16372 /**
16373 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16374 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16375 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16376 * options. For more information about options and selects, please see the
16377 * [OOjs UI documentation on MediaWiki][1].
16378 *
16379 * @example
16380 * // Decorated options in a select widget
16381 * var select = new OO.ui.SelectWidget( {
16382 * items: [
16383 * new OO.ui.DecoratedOptionWidget( {
16384 * data: 'a',
16385 * label: 'Option with icon',
16386 * icon: 'help'
16387 * } ),
16388 * new OO.ui.DecoratedOptionWidget( {
16389 * data: 'b',
16390 * label: 'Option with indicator',
16391 * indicator: 'next'
16392 * } )
16393 * ]
16394 * } );
16395 * $( 'body' ).append( select.$element );
16396 *
16397 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16398 *
16399 * @class
16400 * @extends OO.ui.OptionWidget
16401 * @mixins OO.ui.mixin.IconElement
16402 * @mixins OO.ui.mixin.IndicatorElement
16403 *
16404 * @constructor
16405 * @param {Object} [config] Configuration options
16406 */
16407 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16408 // Parent constructor
16409 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16410
16411 // Mixin constructors
16412 OO.ui.mixin.IconElement.call( this, config );
16413 OO.ui.mixin.IndicatorElement.call( this, config );
16414
16415 // Initialization
16416 this.$element
16417 .addClass( 'oo-ui-decoratedOptionWidget' )
16418 .prepend( this.$icon )
16419 .append( this.$indicator );
16420 };
16421
16422 /* Setup */
16423
16424 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16425 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16426 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16427
16428 /**
16429 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16430 * can be selected and configured with data. The class is
16431 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16432 * [OOjs UI documentation on MediaWiki] [1] for more information.
16433 *
16434 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16435 *
16436 * @class
16437 * @extends OO.ui.DecoratedOptionWidget
16438 * @mixins OO.ui.mixin.ButtonElement
16439 * @mixins OO.ui.mixin.TabIndexedElement
16440 * @mixins OO.ui.mixin.TitledElement
16441 *
16442 * @constructor
16443 * @param {Object} [config] Configuration options
16444 */
16445 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16446 // Configuration initialization
16447 config = config || {};
16448
16449 // Parent constructor
16450 OO.ui.ButtonOptionWidget.parent.call( this, config );
16451
16452 // Mixin constructors
16453 OO.ui.mixin.ButtonElement.call( this, config );
16454 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16455 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16456 $tabIndexed: this.$button,
16457 tabIndex: -1
16458 } ) );
16459
16460 // Initialization
16461 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16462 this.$button.append( this.$element.contents() );
16463 this.$element.append( this.$button );
16464 };
16465
16466 /* Setup */
16467
16468 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16469 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16470 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16471 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16472
16473 /* Static Properties */
16474
16475 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16476 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16477
16478 OO.ui.ButtonOptionWidget.static.highlightable = false;
16479
16480 /* Methods */
16481
16482 /**
16483 * @inheritdoc
16484 */
16485 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16486 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16487
16488 if ( this.constructor.static.selectable ) {
16489 this.setActive( state );
16490 }
16491
16492 return this;
16493 };
16494
16495 /**
16496 * RadioOptionWidget is an option widget that looks like a radio button.
16497 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16498 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16499 *
16500 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16501 *
16502 * @class
16503 * @extends OO.ui.OptionWidget
16504 *
16505 * @constructor
16506 * @param {Object} [config] Configuration options
16507 */
16508 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16509 // Configuration initialization
16510 config = config || {};
16511
16512 // Properties (must be done before parent constructor which calls #setDisabled)
16513 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16514
16515 // Parent constructor
16516 OO.ui.RadioOptionWidget.parent.call( this, config );
16517
16518 // Events
16519 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16520
16521 // Initialization
16522 // Remove implicit role, we're handling it ourselves
16523 this.radio.$input.attr( 'role', 'presentation' );
16524 this.$element
16525 .addClass( 'oo-ui-radioOptionWidget' )
16526 .attr( 'role', 'radio' )
16527 .attr( 'aria-checked', 'false' )
16528 .removeAttr( 'aria-selected' )
16529 .prepend( this.radio.$element );
16530 };
16531
16532 /* Setup */
16533
16534 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16535
16536 /* Static Properties */
16537
16538 OO.ui.RadioOptionWidget.static.highlightable = false;
16539
16540 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16541
16542 OO.ui.RadioOptionWidget.static.pressable = false;
16543
16544 OO.ui.RadioOptionWidget.static.tagName = 'label';
16545
16546 /* Methods */
16547
16548 /**
16549 * @param {jQuery.Event} e Focus event
16550 * @private
16551 */
16552 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16553 this.radio.$input.blur();
16554 this.$element.parent().focus();
16555 };
16556
16557 /**
16558 * @inheritdoc
16559 */
16560 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16561 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16562
16563 this.radio.setSelected( state );
16564 this.$element
16565 .attr( 'aria-checked', state.toString() )
16566 .removeAttr( 'aria-selected' );
16567
16568 return this;
16569 };
16570
16571 /**
16572 * @inheritdoc
16573 */
16574 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16575 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16576
16577 this.radio.setDisabled( this.isDisabled() );
16578
16579 return this;
16580 };
16581
16582 /**
16583 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16584 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16585 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16586 *
16587 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16588 *
16589 * @class
16590 * @extends OO.ui.DecoratedOptionWidget
16591 *
16592 * @constructor
16593 * @param {Object} [config] Configuration options
16594 */
16595 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16596 // Configuration initialization
16597 config = $.extend( { icon: 'check' }, config );
16598
16599 // Parent constructor
16600 OO.ui.MenuOptionWidget.parent.call( this, config );
16601
16602 // Initialization
16603 this.$element
16604 .attr( 'role', 'menuitem' )
16605 .addClass( 'oo-ui-menuOptionWidget' );
16606 };
16607
16608 /* Setup */
16609
16610 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16611
16612 /* Static Properties */
16613
16614 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16615
16616 /**
16617 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16618 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16619 *
16620 * @example
16621 * var myDropdown = new OO.ui.DropdownWidget( {
16622 * menu: {
16623 * items: [
16624 * new OO.ui.MenuSectionOptionWidget( {
16625 * label: 'Dogs'
16626 * } ),
16627 * new OO.ui.MenuOptionWidget( {
16628 * data: 'corgi',
16629 * label: 'Welsh Corgi'
16630 * } ),
16631 * new OO.ui.MenuOptionWidget( {
16632 * data: 'poodle',
16633 * label: 'Standard Poodle'
16634 * } ),
16635 * new OO.ui.MenuSectionOptionWidget( {
16636 * label: 'Cats'
16637 * } ),
16638 * new OO.ui.MenuOptionWidget( {
16639 * data: 'lion',
16640 * label: 'Lion'
16641 * } )
16642 * ]
16643 * }
16644 * } );
16645 * $( 'body' ).append( myDropdown.$element );
16646 *
16647 *
16648 * @class
16649 * @extends OO.ui.DecoratedOptionWidget
16650 *
16651 * @constructor
16652 * @param {Object} [config] Configuration options
16653 */
16654 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16655 // Parent constructor
16656 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16657
16658 // Initialization
16659 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16660 };
16661
16662 /* Setup */
16663
16664 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16665
16666 /* Static Properties */
16667
16668 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16669
16670 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16671
16672 /**
16673 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16674 *
16675 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16676 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16677 * for an example.
16678 *
16679 * @class
16680 * @extends OO.ui.DecoratedOptionWidget
16681 *
16682 * @constructor
16683 * @param {Object} [config] Configuration options
16684 * @cfg {number} [level] Indentation level
16685 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16686 */
16687 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16688 // Configuration initialization
16689 config = config || {};
16690
16691 // Parent constructor
16692 OO.ui.OutlineOptionWidget.parent.call( this, config );
16693
16694 // Properties
16695 this.level = 0;
16696 this.movable = !!config.movable;
16697 this.removable = !!config.removable;
16698
16699 // Initialization
16700 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16701 this.setLevel( config.level );
16702 };
16703
16704 /* Setup */
16705
16706 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16707
16708 /* Static Properties */
16709
16710 OO.ui.OutlineOptionWidget.static.highlightable = false;
16711
16712 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16713
16714 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16715
16716 OO.ui.OutlineOptionWidget.static.levels = 3;
16717
16718 /* Methods */
16719
16720 /**
16721 * Check if item is movable.
16722 *
16723 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16724 *
16725 * @return {boolean} Item is movable
16726 */
16727 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16728 return this.movable;
16729 };
16730
16731 /**
16732 * Check if item is removable.
16733 *
16734 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16735 *
16736 * @return {boolean} Item is removable
16737 */
16738 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16739 return this.removable;
16740 };
16741
16742 /**
16743 * Get indentation level.
16744 *
16745 * @return {number} Indentation level
16746 */
16747 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16748 return this.level;
16749 };
16750
16751 /**
16752 * Set movability.
16753 *
16754 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16755 *
16756 * @param {boolean} movable Item is movable
16757 * @chainable
16758 */
16759 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16760 this.movable = !!movable;
16761 this.updateThemeClasses();
16762 return this;
16763 };
16764
16765 /**
16766 * Set removability.
16767 *
16768 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16769 *
16770 * @param {boolean} movable Item is removable
16771 * @chainable
16772 */
16773 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
16774 this.removable = !!removable;
16775 this.updateThemeClasses();
16776 return this;
16777 };
16778
16779 /**
16780 * Set indentation level.
16781 *
16782 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16783 * @chainable
16784 */
16785 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
16786 var levels = this.constructor.static.levels,
16787 levelClass = this.constructor.static.levelClass,
16788 i = levels;
16789
16790 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
16791 while ( i-- ) {
16792 if ( this.level === i ) {
16793 this.$element.addClass( levelClass + i );
16794 } else {
16795 this.$element.removeClass( levelClass + i );
16796 }
16797 }
16798 this.updateThemeClasses();
16799
16800 return this;
16801 };
16802
16803 /**
16804 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16805 *
16806 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16807 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16808 * for an example.
16809 *
16810 * @class
16811 * @extends OO.ui.OptionWidget
16812 *
16813 * @constructor
16814 * @param {Object} [config] Configuration options
16815 */
16816 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
16817 // Configuration initialization
16818 config = config || {};
16819
16820 // Parent constructor
16821 OO.ui.TabOptionWidget.parent.call( this, config );
16822
16823 // Initialization
16824 this.$element.addClass( 'oo-ui-tabOptionWidget' );
16825 };
16826
16827 /* Setup */
16828
16829 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
16830
16831 /* Static Properties */
16832
16833 OO.ui.TabOptionWidget.static.highlightable = false;
16834
16835 /**
16836 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16837 * By default, each popup has an anchor that points toward its origin.
16838 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16839 *
16840 * @example
16841 * // A popup widget.
16842 * var popup = new OO.ui.PopupWidget( {
16843 * $content: $( '<p>Hi there!</p>' ),
16844 * padded: true,
16845 * width: 300
16846 * } );
16847 *
16848 * $( 'body' ).append( popup.$element );
16849 * // To display the popup, toggle the visibility to 'true'.
16850 * popup.toggle( true );
16851 *
16852 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16853 *
16854 * @class
16855 * @extends OO.ui.Widget
16856 * @mixins OO.ui.mixin.LabelElement
16857 *
16858 * @constructor
16859 * @param {Object} [config] Configuration options
16860 * @cfg {number} [width=320] Width of popup in pixels
16861 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16862 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16863 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16864 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16865 * popup is leaning towards the right of the screen.
16866 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16867 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16868 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16869 * sentence in the given language.
16870 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16871 * See the [OOjs UI docs on MediaWiki][3] for an example.
16872 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16873 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16874 * @cfg {jQuery} [$content] Content to append to the popup's body
16875 * @cfg {jQuery} [$footer] Content to append to the popup's footer
16876 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16877 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16878 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16879 * for an example.
16880 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16881 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16882 * button.
16883 * @cfg {boolean} [padded] Add padding to the popup's body
16884 */
16885 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
16886 // Configuration initialization
16887 config = config || {};
16888
16889 // Parent constructor
16890 OO.ui.PopupWidget.parent.call( this, config );
16891
16892 // Properties (must be set before ClippableElement constructor call)
16893 this.$body = $( '<div>' );
16894 this.$popup = $( '<div>' );
16895
16896 // Mixin constructors
16897 OO.ui.mixin.LabelElement.call( this, config );
16898 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
16899 $clippable: this.$body,
16900 $clippableContainer: this.$popup
16901 } ) );
16902
16903 // Properties
16904 this.$head = $( '<div>' );
16905 this.$footer = $( '<div>' );
16906 this.$anchor = $( '<div>' );
16907 // If undefined, will be computed lazily in updateDimensions()
16908 this.$container = config.$container;
16909 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
16910 this.autoClose = !!config.autoClose;
16911 this.$autoCloseIgnore = config.$autoCloseIgnore;
16912 this.transitionTimeout = null;
16913 this.anchor = null;
16914 this.width = config.width !== undefined ? config.width : 320;
16915 this.height = config.height !== undefined ? config.height : null;
16916 this.setAlignment( config.align );
16917 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
16918 this.onMouseDownHandler = this.onMouseDown.bind( this );
16919 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
16920
16921 // Events
16922 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
16923
16924 // Initialization
16925 this.toggleAnchor( config.anchor === undefined || config.anchor );
16926 this.$body.addClass( 'oo-ui-popupWidget-body' );
16927 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
16928 this.$head
16929 .addClass( 'oo-ui-popupWidget-head' )
16930 .append( this.$label, this.closeButton.$element );
16931 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
16932 if ( !config.head ) {
16933 this.$head.addClass( 'oo-ui-element-hidden' );
16934 }
16935 if ( !config.$footer ) {
16936 this.$footer.addClass( 'oo-ui-element-hidden' );
16937 }
16938 this.$popup
16939 .addClass( 'oo-ui-popupWidget-popup' )
16940 .append( this.$head, this.$body, this.$footer );
16941 this.$element
16942 .addClass( 'oo-ui-popupWidget' )
16943 .append( this.$popup, this.$anchor );
16944 // Move content, which was added to #$element by OO.ui.Widget, to the body
16945 if ( config.$content instanceof jQuery ) {
16946 this.$body.append( config.$content );
16947 }
16948 if ( config.$footer instanceof jQuery ) {
16949 this.$footer.append( config.$footer );
16950 }
16951 if ( config.padded ) {
16952 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
16953 }
16954
16955 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16956 // that reference properties not initialized at that time of parent class construction
16957 // TODO: Find a better way to handle post-constructor setup
16958 this.visible = false;
16959 this.$element.addClass( 'oo-ui-element-hidden' );
16960 };
16961
16962 /* Setup */
16963
16964 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
16965 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
16966 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
16967
16968 /* Methods */
16969
16970 /**
16971 * Handles mouse down events.
16972 *
16973 * @private
16974 * @param {MouseEvent} e Mouse down event
16975 */
16976 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
16977 if (
16978 this.isVisible() &&
16979 !$.contains( this.$element[ 0 ], e.target ) &&
16980 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
16981 ) {
16982 this.toggle( false );
16983 }
16984 };
16985
16986 /**
16987 * Bind mouse down listener.
16988 *
16989 * @private
16990 */
16991 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
16992 // Capture clicks outside popup
16993 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
16994 };
16995
16996 /**
16997 * Handles close button click events.
16998 *
16999 * @private
17000 */
17001 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17002 if ( this.isVisible() ) {
17003 this.toggle( false );
17004 }
17005 };
17006
17007 /**
17008 * Unbind mouse down listener.
17009 *
17010 * @private
17011 */
17012 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17013 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17014 };
17015
17016 /**
17017 * Handles key down events.
17018 *
17019 * @private
17020 * @param {KeyboardEvent} e Key down event
17021 */
17022 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17023 if (
17024 e.which === OO.ui.Keys.ESCAPE &&
17025 this.isVisible()
17026 ) {
17027 this.toggle( false );
17028 e.preventDefault();
17029 e.stopPropagation();
17030 }
17031 };
17032
17033 /**
17034 * Bind key down listener.
17035 *
17036 * @private
17037 */
17038 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17039 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17040 };
17041
17042 /**
17043 * Unbind key down listener.
17044 *
17045 * @private
17046 */
17047 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17048 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17049 };
17050
17051 /**
17052 * Show, hide, or toggle the visibility of the anchor.
17053 *
17054 * @param {boolean} [show] Show anchor, omit to toggle
17055 */
17056 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17057 show = show === undefined ? !this.anchored : !!show;
17058
17059 if ( this.anchored !== show ) {
17060 if ( show ) {
17061 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17062 } else {
17063 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17064 }
17065 this.anchored = show;
17066 }
17067 };
17068
17069 /**
17070 * Check if the anchor is visible.
17071 *
17072 * @return {boolean} Anchor is visible
17073 */
17074 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17075 return this.anchor;
17076 };
17077
17078 /**
17079 * @inheritdoc
17080 */
17081 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17082 var change;
17083 show = show === undefined ? !this.isVisible() : !!show;
17084
17085 change = show !== this.isVisible();
17086
17087 // Parent method
17088 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17089
17090 if ( change ) {
17091 if ( show ) {
17092 if ( this.autoClose ) {
17093 this.bindMouseDownListener();
17094 this.bindKeyDownListener();
17095 }
17096 this.updateDimensions();
17097 this.toggleClipping( true );
17098 } else {
17099 this.toggleClipping( false );
17100 if ( this.autoClose ) {
17101 this.unbindMouseDownListener();
17102 this.unbindKeyDownListener();
17103 }
17104 }
17105 }
17106
17107 return this;
17108 };
17109
17110 /**
17111 * Set the size of the popup.
17112 *
17113 * Changing the size may also change the popup's position depending on the alignment.
17114 *
17115 * @param {number} width Width in pixels
17116 * @param {number} height Height in pixels
17117 * @param {boolean} [transition=false] Use a smooth transition
17118 * @chainable
17119 */
17120 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17121 this.width = width;
17122 this.height = height !== undefined ? height : null;
17123 if ( this.isVisible() ) {
17124 this.updateDimensions( transition );
17125 }
17126 };
17127
17128 /**
17129 * Update the size and position.
17130 *
17131 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17132 * be called automatically.
17133 *
17134 * @param {boolean} [transition=false] Use a smooth transition
17135 * @chainable
17136 */
17137 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17138 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17139 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17140 align = this.align,
17141 widget = this;
17142
17143 if ( !this.$container ) {
17144 // Lazy-initialize $container if not specified in constructor
17145 this.$container = $( this.getClosestScrollableElementContainer() );
17146 }
17147
17148 // Set height and width before measuring things, since it might cause our measurements
17149 // to change (e.g. due to scrollbars appearing or disappearing)
17150 this.$popup.css( {
17151 width: this.width,
17152 height: this.height !== null ? this.height : 'auto'
17153 } );
17154
17155 // If we are in RTL, we need to flip the alignment, unless it is center
17156 if ( align === 'forwards' || align === 'backwards' ) {
17157 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17158 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17159 } else {
17160 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17161 }
17162
17163 }
17164
17165 // Compute initial popupOffset based on alignment
17166 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17167
17168 // Figure out if this will cause the popup to go beyond the edge of the container
17169 originOffset = this.$element.offset().left;
17170 containerLeft = this.$container.offset().left;
17171 containerWidth = this.$container.innerWidth();
17172 containerRight = containerLeft + containerWidth;
17173 popupLeft = popupOffset - this.containerPadding;
17174 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17175 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17176 overlapRight = containerRight - ( originOffset + popupRight );
17177
17178 // Adjust offset to make the popup not go beyond the edge, if needed
17179 if ( overlapRight < 0 ) {
17180 popupOffset += overlapRight;
17181 } else if ( overlapLeft < 0 ) {
17182 popupOffset -= overlapLeft;
17183 }
17184
17185 // Adjust offset to avoid anchor being rendered too close to the edge
17186 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17187 // TODO: Find a measurement that works for CSS anchors and image anchors
17188 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17189 if ( popupOffset + this.width < anchorWidth ) {
17190 popupOffset = anchorWidth - this.width;
17191 } else if ( -popupOffset < anchorWidth ) {
17192 popupOffset = -anchorWidth;
17193 }
17194
17195 // Prevent transition from being interrupted
17196 clearTimeout( this.transitionTimeout );
17197 if ( transition ) {
17198 // Enable transition
17199 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17200 }
17201
17202 // Position body relative to anchor
17203 this.$popup.css( 'margin-left', popupOffset );
17204
17205 if ( transition ) {
17206 // Prevent transitioning after transition is complete
17207 this.transitionTimeout = setTimeout( function () {
17208 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17209 }, 200 );
17210 } else {
17211 // Prevent transitioning immediately
17212 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17213 }
17214
17215 // Reevaluate clipping state since we've relocated and resized the popup
17216 this.clip();
17217
17218 return this;
17219 };
17220
17221 /**
17222 * Set popup alignment
17223 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17224 * `backwards` or `forwards`.
17225 */
17226 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17227 // Validate alignment and transform deprecated values
17228 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17229 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17230 } else {
17231 this.align = 'center';
17232 }
17233 };
17234
17235 /**
17236 * Get popup alignment
17237 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17238 * `backwards` or `forwards`.
17239 */
17240 OO.ui.PopupWidget.prototype.getAlignment = function () {
17241 return this.align;
17242 };
17243
17244 /**
17245 * Progress bars visually display the status of an operation, such as a download,
17246 * and can be either determinate or indeterminate:
17247 *
17248 * - **determinate** process bars show the percent of an operation that is complete.
17249 *
17250 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17251 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17252 * not use percentages.
17253 *
17254 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17255 *
17256 * @example
17257 * // Examples of determinate and indeterminate progress bars.
17258 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17259 * progress: 33
17260 * } );
17261 * var progressBar2 = new OO.ui.ProgressBarWidget();
17262 *
17263 * // Create a FieldsetLayout to layout progress bars
17264 * var fieldset = new OO.ui.FieldsetLayout;
17265 * fieldset.addItems( [
17266 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17267 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17268 * ] );
17269 * $( 'body' ).append( fieldset.$element );
17270 *
17271 * @class
17272 * @extends OO.ui.Widget
17273 *
17274 * @constructor
17275 * @param {Object} [config] Configuration options
17276 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17277 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17278 * By default, the progress bar is indeterminate.
17279 */
17280 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17281 // Configuration initialization
17282 config = config || {};
17283
17284 // Parent constructor
17285 OO.ui.ProgressBarWidget.parent.call( this, config );
17286
17287 // Properties
17288 this.$bar = $( '<div>' );
17289 this.progress = null;
17290
17291 // Initialization
17292 this.setProgress( config.progress !== undefined ? config.progress : false );
17293 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17294 this.$element
17295 .attr( {
17296 role: 'progressbar',
17297 'aria-valuemin': 0,
17298 'aria-valuemax': 100
17299 } )
17300 .addClass( 'oo-ui-progressBarWidget' )
17301 .append( this.$bar );
17302 };
17303
17304 /* Setup */
17305
17306 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17307
17308 /* Static Properties */
17309
17310 OO.ui.ProgressBarWidget.static.tagName = 'div';
17311
17312 /* Methods */
17313
17314 /**
17315 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17316 *
17317 * @return {number|boolean} Progress percent
17318 */
17319 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17320 return this.progress;
17321 };
17322
17323 /**
17324 * Set the percent of the process completed or `false` for an indeterminate process.
17325 *
17326 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17327 */
17328 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17329 this.progress = progress;
17330
17331 if ( progress !== false ) {
17332 this.$bar.css( 'width', this.progress + '%' );
17333 this.$element.attr( 'aria-valuenow', this.progress );
17334 } else {
17335 this.$bar.css( 'width', '' );
17336 this.$element.removeAttr( 'aria-valuenow' );
17337 }
17338 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17339 };
17340
17341 /**
17342 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17343 * and a menu of search results, which is displayed beneath the query
17344 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17345 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17346 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17347 *
17348 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17349 * the [OOjs UI demos][1] for an example.
17350 *
17351 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17352 *
17353 * @class
17354 * @extends OO.ui.Widget
17355 *
17356 * @constructor
17357 * @param {Object} [config] Configuration options
17358 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17359 * @cfg {string} [value] Initial query value
17360 */
17361 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17362 // Configuration initialization
17363 config = config || {};
17364
17365 // Parent constructor
17366 OO.ui.SearchWidget.parent.call( this, config );
17367
17368 // Properties
17369 this.query = new OO.ui.TextInputWidget( {
17370 icon: 'search',
17371 placeholder: config.placeholder,
17372 value: config.value
17373 } );
17374 this.results = new OO.ui.SelectWidget();
17375 this.$query = $( '<div>' );
17376 this.$results = $( '<div>' );
17377
17378 // Events
17379 this.query.connect( this, {
17380 change: 'onQueryChange',
17381 enter: 'onQueryEnter'
17382 } );
17383 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17384
17385 // Initialization
17386 this.$query
17387 .addClass( 'oo-ui-searchWidget-query' )
17388 .append( this.query.$element );
17389 this.$results
17390 .addClass( 'oo-ui-searchWidget-results' )
17391 .append( this.results.$element );
17392 this.$element
17393 .addClass( 'oo-ui-searchWidget' )
17394 .append( this.$results, this.$query );
17395 };
17396
17397 /* Setup */
17398
17399 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17400
17401 /* Methods */
17402
17403 /**
17404 * Handle query key down events.
17405 *
17406 * @private
17407 * @param {jQuery.Event} e Key down event
17408 */
17409 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17410 var highlightedItem, nextItem,
17411 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17412
17413 if ( dir ) {
17414 highlightedItem = this.results.getHighlightedItem();
17415 if ( !highlightedItem ) {
17416 highlightedItem = this.results.getSelectedItem();
17417 }
17418 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17419 this.results.highlightItem( nextItem );
17420 nextItem.scrollElementIntoView();
17421 }
17422 };
17423
17424 /**
17425 * Handle select widget select events.
17426 *
17427 * Clears existing results. Subclasses should repopulate items according to new query.
17428 *
17429 * @private
17430 * @param {string} value New value
17431 */
17432 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17433 // Reset
17434 this.results.clearItems();
17435 };
17436
17437 /**
17438 * Handle select widget enter key events.
17439 *
17440 * Chooses highlighted item.
17441 *
17442 * @private
17443 * @param {string} value New value
17444 */
17445 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17446 // Reset
17447 this.results.chooseItem( this.results.getHighlightedItem() );
17448 };
17449
17450 /**
17451 * Get the query input.
17452 *
17453 * @return {OO.ui.TextInputWidget} Query input
17454 */
17455 OO.ui.SearchWidget.prototype.getQuery = function () {
17456 return this.query;
17457 };
17458
17459 /**
17460 * Get the search results menu.
17461 *
17462 * @return {OO.ui.SelectWidget} Menu of search results
17463 */
17464 OO.ui.SearchWidget.prototype.getResults = function () {
17465 return this.results;
17466 };
17467
17468 /**
17469 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17470 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17471 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17472 * menu selects}.
17473 *
17474 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17475 * information, please see the [OOjs UI documentation on MediaWiki][1].
17476 *
17477 * @example
17478 * // Example of a select widget with three options
17479 * var select = new OO.ui.SelectWidget( {
17480 * items: [
17481 * new OO.ui.OptionWidget( {
17482 * data: 'a',
17483 * label: 'Option One',
17484 * } ),
17485 * new OO.ui.OptionWidget( {
17486 * data: 'b',
17487 * label: 'Option Two',
17488 * } ),
17489 * new OO.ui.OptionWidget( {
17490 * data: 'c',
17491 * label: 'Option Three',
17492 * } )
17493 * ]
17494 * } );
17495 * $( 'body' ).append( select.$element );
17496 *
17497 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17498 *
17499 * @abstract
17500 * @class
17501 * @extends OO.ui.Widget
17502 * @mixins OO.ui.mixin.GroupWidget
17503 *
17504 * @constructor
17505 * @param {Object} [config] Configuration options
17506 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17507 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17508 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17509 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17510 */
17511 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17512 // Configuration initialization
17513 config = config || {};
17514
17515 // Parent constructor
17516 OO.ui.SelectWidget.parent.call( this, config );
17517
17518 // Mixin constructors
17519 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17520
17521 // Properties
17522 this.pressed = false;
17523 this.selecting = null;
17524 this.onMouseUpHandler = this.onMouseUp.bind( this );
17525 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17526 this.onKeyDownHandler = this.onKeyDown.bind( this );
17527 this.onKeyPressHandler = this.onKeyPress.bind( this );
17528 this.keyPressBuffer = '';
17529 this.keyPressBufferTimer = null;
17530
17531 // Events
17532 this.connect( this, {
17533 toggle: 'onToggle'
17534 } );
17535 this.$element.on( {
17536 mousedown: this.onMouseDown.bind( this ),
17537 mouseover: this.onMouseOver.bind( this ),
17538 mouseleave: this.onMouseLeave.bind( this )
17539 } );
17540
17541 // Initialization
17542 this.$element
17543 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17544 .attr( 'role', 'listbox' );
17545 if ( Array.isArray( config.items ) ) {
17546 this.addItems( config.items );
17547 }
17548 };
17549
17550 /* Setup */
17551
17552 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17553
17554 // Need to mixin base class as well
17555 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17556 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17557
17558 /* Static */
17559 OO.ui.SelectWidget.static.passAllFilter = function () {
17560 return true;
17561 };
17562
17563 /* Events */
17564
17565 /**
17566 * @event highlight
17567 *
17568 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17569 *
17570 * @param {OO.ui.OptionWidget|null} item Highlighted item
17571 */
17572
17573 /**
17574 * @event press
17575 *
17576 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17577 * pressed state of an option.
17578 *
17579 * @param {OO.ui.OptionWidget|null} item Pressed item
17580 */
17581
17582 /**
17583 * @event select
17584 *
17585 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17586 *
17587 * @param {OO.ui.OptionWidget|null} item Selected item
17588 */
17589
17590 /**
17591 * @event choose
17592 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17593 * @param {OO.ui.OptionWidget} item Chosen item
17594 */
17595
17596 /**
17597 * @event add
17598 *
17599 * An `add` event is emitted when options are added to the select with the #addItems method.
17600 *
17601 * @param {OO.ui.OptionWidget[]} items Added items
17602 * @param {number} index Index of insertion point
17603 */
17604
17605 /**
17606 * @event remove
17607 *
17608 * A `remove` event is emitted when options are removed from the select with the #clearItems
17609 * or #removeItems methods.
17610 *
17611 * @param {OO.ui.OptionWidget[]} items Removed items
17612 */
17613
17614 /* Methods */
17615
17616 /**
17617 * Handle mouse down events.
17618 *
17619 * @private
17620 * @param {jQuery.Event} e Mouse down event
17621 */
17622 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17623 var item;
17624
17625 if ( !this.isDisabled() && e.which === 1 ) {
17626 this.togglePressed( true );
17627 item = this.getTargetItem( e );
17628 if ( item && item.isSelectable() ) {
17629 this.pressItem( item );
17630 this.selecting = item;
17631 OO.ui.addCaptureEventListener(
17632 this.getElementDocument(),
17633 'mouseup',
17634 this.onMouseUpHandler
17635 );
17636 OO.ui.addCaptureEventListener(
17637 this.getElementDocument(),
17638 'mousemove',
17639 this.onMouseMoveHandler
17640 );
17641 }
17642 }
17643 return false;
17644 };
17645
17646 /**
17647 * Handle mouse up events.
17648 *
17649 * @private
17650 * @param {jQuery.Event} e Mouse up event
17651 */
17652 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17653 var item;
17654
17655 this.togglePressed( false );
17656 if ( !this.selecting ) {
17657 item = this.getTargetItem( e );
17658 if ( item && item.isSelectable() ) {
17659 this.selecting = item;
17660 }
17661 }
17662 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17663 this.pressItem( null );
17664 this.chooseItem( this.selecting );
17665 this.selecting = null;
17666 }
17667
17668 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17669 this.onMouseUpHandler );
17670 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17671 this.onMouseMoveHandler );
17672
17673 return false;
17674 };
17675
17676 /**
17677 * Handle mouse move events.
17678 *
17679 * @private
17680 * @param {jQuery.Event} e Mouse move event
17681 */
17682 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17683 var item;
17684
17685 if ( !this.isDisabled() && this.pressed ) {
17686 item = this.getTargetItem( e );
17687 if ( item && item !== this.selecting && item.isSelectable() ) {
17688 this.pressItem( item );
17689 this.selecting = item;
17690 }
17691 }
17692 return false;
17693 };
17694
17695 /**
17696 * Handle mouse over events.
17697 *
17698 * @private
17699 * @param {jQuery.Event} e Mouse over event
17700 */
17701 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17702 var item;
17703
17704 if ( !this.isDisabled() ) {
17705 item = this.getTargetItem( e );
17706 this.highlightItem( item && item.isHighlightable() ? item : null );
17707 }
17708 return false;
17709 };
17710
17711 /**
17712 * Handle mouse leave events.
17713 *
17714 * @private
17715 * @param {jQuery.Event} e Mouse over event
17716 */
17717 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17718 if ( !this.isDisabled() ) {
17719 this.highlightItem( null );
17720 }
17721 return false;
17722 };
17723
17724 /**
17725 * Handle key down events.
17726 *
17727 * @protected
17728 * @param {jQuery.Event} e Key down event
17729 */
17730 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17731 var nextItem,
17732 handled = false,
17733 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17734
17735 if ( !this.isDisabled() && this.isVisible() ) {
17736 switch ( e.keyCode ) {
17737 case OO.ui.Keys.ENTER:
17738 if ( currentItem && currentItem.constructor.static.highlightable ) {
17739 // Was only highlighted, now let's select it. No-op if already selected.
17740 this.chooseItem( currentItem );
17741 handled = true;
17742 }
17743 break;
17744 case OO.ui.Keys.UP:
17745 case OO.ui.Keys.LEFT:
17746 this.clearKeyPressBuffer();
17747 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17748 handled = true;
17749 break;
17750 case OO.ui.Keys.DOWN:
17751 case OO.ui.Keys.RIGHT:
17752 this.clearKeyPressBuffer();
17753 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17754 handled = true;
17755 break;
17756 case OO.ui.Keys.ESCAPE:
17757 case OO.ui.Keys.TAB:
17758 if ( currentItem && currentItem.constructor.static.highlightable ) {
17759 currentItem.setHighlighted( false );
17760 }
17761 this.unbindKeyDownListener();
17762 this.unbindKeyPressListener();
17763 // Don't prevent tabbing away / defocusing
17764 handled = false;
17765 break;
17766 }
17767
17768 if ( nextItem ) {
17769 if ( nextItem.constructor.static.highlightable ) {
17770 this.highlightItem( nextItem );
17771 } else {
17772 this.chooseItem( nextItem );
17773 }
17774 nextItem.scrollElementIntoView();
17775 }
17776
17777 if ( handled ) {
17778 // Can't just return false, because e is not always a jQuery event
17779 e.preventDefault();
17780 e.stopPropagation();
17781 }
17782 }
17783 };
17784
17785 /**
17786 * Bind key down listener.
17787 *
17788 * @protected
17789 */
17790 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
17791 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17792 };
17793
17794 /**
17795 * Unbind key down listener.
17796 *
17797 * @protected
17798 */
17799 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
17800 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17801 };
17802
17803 /**
17804 * Clear the key-press buffer
17805 *
17806 * @protected
17807 */
17808 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
17809 if ( this.keyPressBufferTimer ) {
17810 clearTimeout( this.keyPressBufferTimer );
17811 this.keyPressBufferTimer = null;
17812 }
17813 this.keyPressBuffer = '';
17814 };
17815
17816 /**
17817 * Handle key press events.
17818 *
17819 * @protected
17820 * @param {jQuery.Event} e Key press event
17821 */
17822 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
17823 var c, filter, item;
17824
17825 if ( !e.charCode ) {
17826 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
17827 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
17828 return false;
17829 }
17830 return;
17831 }
17832 if ( String.fromCodePoint ) {
17833 c = String.fromCodePoint( e.charCode );
17834 } else {
17835 c = String.fromCharCode( e.charCode );
17836 }
17837
17838 if ( this.keyPressBufferTimer ) {
17839 clearTimeout( this.keyPressBufferTimer );
17840 }
17841 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
17842
17843 item = this.getHighlightedItem() || this.getSelectedItem();
17844
17845 if ( this.keyPressBuffer === c ) {
17846 // Common (if weird) special case: typing "xxxx" will cycle through all
17847 // the items beginning with "x".
17848 if ( item ) {
17849 item = this.getRelativeSelectableItem( item, 1 );
17850 }
17851 } else {
17852 this.keyPressBuffer += c;
17853 }
17854
17855 filter = this.getItemMatcher( this.keyPressBuffer, false );
17856 if ( !item || !filter( item ) ) {
17857 item = this.getRelativeSelectableItem( item, 1, filter );
17858 }
17859 if ( item ) {
17860 if ( item.constructor.static.highlightable ) {
17861 this.highlightItem( item );
17862 } else {
17863 this.chooseItem( item );
17864 }
17865 item.scrollElementIntoView();
17866 }
17867
17868 return false;
17869 };
17870
17871 /**
17872 * Get a matcher for the specific string
17873 *
17874 * @protected
17875 * @param {string} s String to match against items
17876 * @param {boolean} [exact=false] Only accept exact matches
17877 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17878 */
17879 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
17880 var re;
17881
17882 if ( s.normalize ) {
17883 s = s.normalize();
17884 }
17885 s = exact ? s.trim() : s.replace( /^\s+/, '' );
17886 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17887 if ( exact ) {
17888 re += '\\s*$';
17889 }
17890 re = new RegExp( re, 'i' );
17891 return function ( item ) {
17892 var l = item.getLabel();
17893 if ( typeof l !== 'string' ) {
17894 l = item.$label.text();
17895 }
17896 if ( l.normalize ) {
17897 l = l.normalize();
17898 }
17899 return re.test( l );
17900 };
17901 };
17902
17903 /**
17904 * Bind key press listener.
17905 *
17906 * @protected
17907 */
17908 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
17909 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17910 };
17911
17912 /**
17913 * Unbind key down listener.
17914 *
17915 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17916 * implementation.
17917 *
17918 * @protected
17919 */
17920 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
17921 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17922 this.clearKeyPressBuffer();
17923 };
17924
17925 /**
17926 * Visibility change handler
17927 *
17928 * @protected
17929 * @param {boolean} visible
17930 */
17931 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
17932 if ( !visible ) {
17933 this.clearKeyPressBuffer();
17934 }
17935 };
17936
17937 /**
17938 * Get the closest item to a jQuery.Event.
17939 *
17940 * @private
17941 * @param {jQuery.Event} e
17942 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17943 */
17944 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
17945 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17946 };
17947
17948 /**
17949 * Get selected item.
17950 *
17951 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17952 */
17953 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
17954 var i, len;
17955
17956 for ( i = 0, len = this.items.length; i < len; i++ ) {
17957 if ( this.items[ i ].isSelected() ) {
17958 return this.items[ i ];
17959 }
17960 }
17961 return null;
17962 };
17963
17964 /**
17965 * Get highlighted item.
17966 *
17967 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17968 */
17969 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
17970 var i, len;
17971
17972 for ( i = 0, len = this.items.length; i < len; i++ ) {
17973 if ( this.items[ i ].isHighlighted() ) {
17974 return this.items[ i ];
17975 }
17976 }
17977 return null;
17978 };
17979
17980 /**
17981 * Toggle pressed state.
17982 *
17983 * Press is a state that occurs when a user mouses down on an item, but
17984 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17985 * until the user releases the mouse.
17986 *
17987 * @param {boolean} pressed An option is being pressed
17988 */
17989 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
17990 if ( pressed === undefined ) {
17991 pressed = !this.pressed;
17992 }
17993 if ( pressed !== this.pressed ) {
17994 this.$element
17995 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
17996 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
17997 this.pressed = pressed;
17998 }
17999 };
18000
18001 /**
18002 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18003 * and any existing highlight will be removed. The highlight is mutually exclusive.
18004 *
18005 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18006 * @fires highlight
18007 * @chainable
18008 */
18009 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18010 var i, len, highlighted,
18011 changed = false;
18012
18013 for ( i = 0, len = this.items.length; i < len; i++ ) {
18014 highlighted = this.items[ i ] === item;
18015 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18016 this.items[ i ].setHighlighted( highlighted );
18017 changed = true;
18018 }
18019 }
18020 if ( changed ) {
18021 this.emit( 'highlight', item );
18022 }
18023
18024 return this;
18025 };
18026
18027 /**
18028 * Fetch an item by its label.
18029 *
18030 * @param {string} label Label of the item to select.
18031 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18032 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18033 */
18034 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18035 var i, item, found,
18036 len = this.items.length,
18037 filter = this.getItemMatcher( label, true );
18038
18039 for ( i = 0; i < len; i++ ) {
18040 item = this.items[ i ];
18041 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18042 return item;
18043 }
18044 }
18045
18046 if ( prefix ) {
18047 found = null;
18048 filter = this.getItemMatcher( label, false );
18049 for ( i = 0; i < len; i++ ) {
18050 item = this.items[ i ];
18051 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18052 if ( found ) {
18053 return null;
18054 }
18055 found = item;
18056 }
18057 }
18058 if ( found ) {
18059 return found;
18060 }
18061 }
18062
18063 return null;
18064 };
18065
18066 /**
18067 * Programmatically select an option by its label. If the item does not exist,
18068 * all options will be deselected.
18069 *
18070 * @param {string} [label] Label of the item to select.
18071 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18072 * @fires select
18073 * @chainable
18074 */
18075 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18076 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18077 if ( label === undefined || !itemFromLabel ) {
18078 return this.selectItem();
18079 }
18080 return this.selectItem( itemFromLabel );
18081 };
18082
18083 /**
18084 * Programmatically select an option by its data. If the `data` parameter is omitted,
18085 * or if the item does not exist, all options will be deselected.
18086 *
18087 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18088 * @fires select
18089 * @chainable
18090 */
18091 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18092 var itemFromData = this.getItemFromData( data );
18093 if ( data === undefined || !itemFromData ) {
18094 return this.selectItem();
18095 }
18096 return this.selectItem( itemFromData );
18097 };
18098
18099 /**
18100 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18101 * all options will be deselected.
18102 *
18103 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18104 * @fires select
18105 * @chainable
18106 */
18107 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18108 var i, len, selected,
18109 changed = false;
18110
18111 for ( i = 0, len = this.items.length; i < len; i++ ) {
18112 selected = this.items[ i ] === item;
18113 if ( this.items[ i ].isSelected() !== selected ) {
18114 this.items[ i ].setSelected( selected );
18115 changed = true;
18116 }
18117 }
18118 if ( changed ) {
18119 this.emit( 'select', item );
18120 }
18121
18122 return this;
18123 };
18124
18125 /**
18126 * Press an item.
18127 *
18128 * Press is a state that occurs when a user mouses down on an item, but has not
18129 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18130 * releases the mouse.
18131 *
18132 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18133 * @fires press
18134 * @chainable
18135 */
18136 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18137 var i, len, pressed,
18138 changed = false;
18139
18140 for ( i = 0, len = this.items.length; i < len; i++ ) {
18141 pressed = this.items[ i ] === item;
18142 if ( this.items[ i ].isPressed() !== pressed ) {
18143 this.items[ i ].setPressed( pressed );
18144 changed = true;
18145 }
18146 }
18147 if ( changed ) {
18148 this.emit( 'press', item );
18149 }
18150
18151 return this;
18152 };
18153
18154 /**
18155 * Choose an item.
18156 *
18157 * Note that ‘choose’ should never be modified programmatically. A user can choose
18158 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18159 * use the #selectItem method.
18160 *
18161 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18162 * when users choose an item with the keyboard or mouse.
18163 *
18164 * @param {OO.ui.OptionWidget} item Item to choose
18165 * @fires choose
18166 * @chainable
18167 */
18168 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18169 this.selectItem( item );
18170 this.emit( 'choose', item );
18171
18172 return this;
18173 };
18174
18175 /**
18176 * Get an option by its position relative to the specified item (or to the start of the option array,
18177 * if item is `null`). The direction in which to search through the option array is specified with a
18178 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18179 * `null` if there are no options in the array.
18180 *
18181 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18182 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18183 * @param {Function} filter Only consider items for which this function returns
18184 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18185 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18186 */
18187 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18188 var currentIndex, nextIndex, i,
18189 increase = direction > 0 ? 1 : -1,
18190 len = this.items.length;
18191
18192 if ( !$.isFunction( filter ) ) {
18193 filter = OO.ui.SelectWidget.static.passAllFilter;
18194 }
18195
18196 if ( item instanceof OO.ui.OptionWidget ) {
18197 currentIndex = this.items.indexOf( item );
18198 nextIndex = ( currentIndex + increase + len ) % len;
18199 } else {
18200 // If no item is selected and moving forward, start at the beginning.
18201 // If moving backward, start at the end.
18202 nextIndex = direction > 0 ? 0 : len - 1;
18203 }
18204
18205 for ( i = 0; i < len; i++ ) {
18206 item = this.items[ nextIndex ];
18207 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18208 return item;
18209 }
18210 nextIndex = ( nextIndex + increase + len ) % len;
18211 }
18212 return null;
18213 };
18214
18215 /**
18216 * Get the next selectable item or `null` if there are no selectable items.
18217 * Disabled options and menu-section markers and breaks are not selectable.
18218 *
18219 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18220 */
18221 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18222 var i, len, item;
18223
18224 for ( i = 0, len = this.items.length; i < len; i++ ) {
18225 item = this.items[ i ];
18226 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18227 return item;
18228 }
18229 }
18230
18231 return null;
18232 };
18233
18234 /**
18235 * Add an array of options to the select. Optionally, an index number can be used to
18236 * specify an insertion point.
18237 *
18238 * @param {OO.ui.OptionWidget[]} items Items to add
18239 * @param {number} [index] Index to insert items after
18240 * @fires add
18241 * @chainable
18242 */
18243 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18244 // Mixin method
18245 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18246
18247 // Always provide an index, even if it was omitted
18248 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18249
18250 return this;
18251 };
18252
18253 /**
18254 * Remove the specified array of options from the select. Options will be detached
18255 * from the DOM, not removed, so they can be reused later. To remove all options from
18256 * the select, you may wish to use the #clearItems method instead.
18257 *
18258 * @param {OO.ui.OptionWidget[]} items Items to remove
18259 * @fires remove
18260 * @chainable
18261 */
18262 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18263 var i, len, item;
18264
18265 // Deselect items being removed
18266 for ( i = 0, len = items.length; i < len; i++ ) {
18267 item = items[ i ];
18268 if ( item.isSelected() ) {
18269 this.selectItem( null );
18270 }
18271 }
18272
18273 // Mixin method
18274 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18275
18276 this.emit( 'remove', items );
18277
18278 return this;
18279 };
18280
18281 /**
18282 * Clear all options from the select. Options will be detached from the DOM, not removed,
18283 * so that they can be reused later. To remove a subset of options from the select, use
18284 * the #removeItems method.
18285 *
18286 * @fires remove
18287 * @chainable
18288 */
18289 OO.ui.SelectWidget.prototype.clearItems = function () {
18290 var items = this.items.slice();
18291
18292 // Mixin method
18293 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18294
18295 // Clear selection
18296 this.selectItem( null );
18297
18298 this.emit( 'remove', items );
18299
18300 return this;
18301 };
18302
18303 /**
18304 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18305 * button options and is used together with
18306 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18307 * highlighting, choosing, and selecting mutually exclusive options. Please see
18308 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18309 *
18310 * @example
18311 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18312 * var option1 = new OO.ui.ButtonOptionWidget( {
18313 * data: 1,
18314 * label: 'Option 1',
18315 * title: 'Button option 1'
18316 * } );
18317 *
18318 * var option2 = new OO.ui.ButtonOptionWidget( {
18319 * data: 2,
18320 * label: 'Option 2',
18321 * title: 'Button option 2'
18322 * } );
18323 *
18324 * var option3 = new OO.ui.ButtonOptionWidget( {
18325 * data: 3,
18326 * label: 'Option 3',
18327 * title: 'Button option 3'
18328 * } );
18329 *
18330 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18331 * items: [ option1, option2, option3 ]
18332 * } );
18333 * $( 'body' ).append( buttonSelect.$element );
18334 *
18335 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18336 *
18337 * @class
18338 * @extends OO.ui.SelectWidget
18339 * @mixins OO.ui.mixin.TabIndexedElement
18340 *
18341 * @constructor
18342 * @param {Object} [config] Configuration options
18343 */
18344 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18345 // Parent constructor
18346 OO.ui.ButtonSelectWidget.parent.call( this, config );
18347
18348 // Mixin constructors
18349 OO.ui.mixin.TabIndexedElement.call( this, config );
18350
18351 // Events
18352 this.$element.on( {
18353 focus: this.bindKeyDownListener.bind( this ),
18354 blur: this.unbindKeyDownListener.bind( this )
18355 } );
18356
18357 // Initialization
18358 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18359 };
18360
18361 /* Setup */
18362
18363 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18364 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18365
18366 /**
18367 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18368 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18369 * an interface for adding, removing and selecting options.
18370 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18371 *
18372 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18373 * OO.ui.RadioSelectInputWidget instead.
18374 *
18375 * @example
18376 * // A RadioSelectWidget with RadioOptions.
18377 * var option1 = new OO.ui.RadioOptionWidget( {
18378 * data: 'a',
18379 * label: 'Selected radio option'
18380 * } );
18381 *
18382 * var option2 = new OO.ui.RadioOptionWidget( {
18383 * data: 'b',
18384 * label: 'Unselected radio option'
18385 * } );
18386 *
18387 * var radioSelect=new OO.ui.RadioSelectWidget( {
18388 * items: [ option1, option2 ]
18389 * } );
18390 *
18391 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18392 * radioSelect.selectItem( option1 );
18393 *
18394 * $( 'body' ).append( radioSelect.$element );
18395 *
18396 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18397
18398 *
18399 * @class
18400 * @extends OO.ui.SelectWidget
18401 * @mixins OO.ui.mixin.TabIndexedElement
18402 *
18403 * @constructor
18404 * @param {Object} [config] Configuration options
18405 */
18406 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18407 // Parent constructor
18408 OO.ui.RadioSelectWidget.parent.call( this, config );
18409
18410 // Mixin constructors
18411 OO.ui.mixin.TabIndexedElement.call( this, config );
18412
18413 // Events
18414 this.$element.on( {
18415 focus: this.bindKeyDownListener.bind( this ),
18416 blur: this.unbindKeyDownListener.bind( this )
18417 } );
18418
18419 // Initialization
18420 this.$element
18421 .addClass( 'oo-ui-radioSelectWidget' )
18422 .attr( 'role', 'radiogroup' );
18423 };
18424
18425 /* Setup */
18426
18427 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18428 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18429
18430 /**
18431 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18432 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18433 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18434 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18435 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18436 * and customized to be opened, closed, and displayed as needed.
18437 *
18438 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18439 * mouse outside the menu.
18440 *
18441 * Menus also have support for keyboard interaction:
18442 *
18443 * - Enter/Return key: choose and select a menu option
18444 * - Up-arrow key: highlight the previous menu option
18445 * - Down-arrow key: highlight the next menu option
18446 * - Esc key: hide the menu
18447 *
18448 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18449 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18450 *
18451 * @class
18452 * @extends OO.ui.SelectWidget
18453 * @mixins OO.ui.mixin.ClippableElement
18454 *
18455 * @constructor
18456 * @param {Object} [config] Configuration options
18457 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18458 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18459 * and {@link OO.ui.mixin.LookupElement LookupElement}
18460 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18461 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18462 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18463 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18464 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18465 * that button, unless the button (or its parent widget) is passed in here.
18466 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18467 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18468 */
18469 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18470 // Configuration initialization
18471 config = config || {};
18472
18473 // Parent constructor
18474 OO.ui.MenuSelectWidget.parent.call( this, config );
18475
18476 // Mixin constructors
18477 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18478
18479 // Properties
18480 this.newItems = null;
18481 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18482 this.filterFromInput = !!config.filterFromInput;
18483 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18484 this.$widget = config.widget ? config.widget.$element : null;
18485 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18486 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18487
18488 // Initialization
18489 this.$element
18490 .addClass( 'oo-ui-menuSelectWidget' )
18491 .attr( 'role', 'menu' );
18492
18493 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18494 // that reference properties not initialized at that time of parent class construction
18495 // TODO: Find a better way to handle post-constructor setup
18496 this.visible = false;
18497 this.$element.addClass( 'oo-ui-element-hidden' );
18498 };
18499
18500 /* Setup */
18501
18502 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18503 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18504
18505 /* Methods */
18506
18507 /**
18508 * Handles document mouse down events.
18509 *
18510 * @protected
18511 * @param {jQuery.Event} e Key down event
18512 */
18513 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18514 if (
18515 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18516 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18517 ) {
18518 this.toggle( false );
18519 }
18520 };
18521
18522 /**
18523 * @inheritdoc
18524 */
18525 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18526 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18527
18528 if ( !this.isDisabled() && this.isVisible() ) {
18529 switch ( e.keyCode ) {
18530 case OO.ui.Keys.LEFT:
18531 case OO.ui.Keys.RIGHT:
18532 // Do nothing if a text field is associated, arrow keys will be handled natively
18533 if ( !this.$input ) {
18534 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18535 }
18536 break;
18537 case OO.ui.Keys.ESCAPE:
18538 case OO.ui.Keys.TAB:
18539 if ( currentItem ) {
18540 currentItem.setHighlighted( false );
18541 }
18542 this.toggle( false );
18543 // Don't prevent tabbing away, prevent defocusing
18544 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18545 e.preventDefault();
18546 e.stopPropagation();
18547 }
18548 break;
18549 default:
18550 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18551 return;
18552 }
18553 }
18554 };
18555
18556 /**
18557 * Update menu item visibility after input changes.
18558 * @protected
18559 */
18560 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18561 var i, item,
18562 len = this.items.length,
18563 showAll = !this.isVisible(),
18564 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18565
18566 for ( i = 0; i < len; i++ ) {
18567 item = this.items[ i ];
18568 if ( item instanceof OO.ui.OptionWidget ) {
18569 item.toggle( showAll || filter( item ) );
18570 }
18571 }
18572
18573 // Reevaluate clipping
18574 this.clip();
18575 };
18576
18577 /**
18578 * @inheritdoc
18579 */
18580 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18581 if ( this.$input ) {
18582 this.$input.on( 'keydown', this.onKeyDownHandler );
18583 } else {
18584 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18585 }
18586 };
18587
18588 /**
18589 * @inheritdoc
18590 */
18591 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18592 if ( this.$input ) {
18593 this.$input.off( 'keydown', this.onKeyDownHandler );
18594 } else {
18595 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18596 }
18597 };
18598
18599 /**
18600 * @inheritdoc
18601 */
18602 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18603 if ( this.$input ) {
18604 if ( this.filterFromInput ) {
18605 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18606 }
18607 } else {
18608 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18609 }
18610 };
18611
18612 /**
18613 * @inheritdoc
18614 */
18615 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18616 if ( this.$input ) {
18617 if ( this.filterFromInput ) {
18618 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18619 this.updateItemVisibility();
18620 }
18621 } else {
18622 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18623 }
18624 };
18625
18626 /**
18627 * Choose an item.
18628 *
18629 * When a user chooses an item, the menu is closed.
18630 *
18631 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18632 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18633 * @param {OO.ui.OptionWidget} item Item to choose
18634 * @chainable
18635 */
18636 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18637 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18638 this.toggle( false );
18639 return this;
18640 };
18641
18642 /**
18643 * @inheritdoc
18644 */
18645 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18646 var i, len, item;
18647
18648 // Parent method
18649 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18650
18651 // Auto-initialize
18652 if ( !this.newItems ) {
18653 this.newItems = [];
18654 }
18655
18656 for ( i = 0, len = items.length; i < len; i++ ) {
18657 item = items[ i ];
18658 if ( this.isVisible() ) {
18659 // Defer fitting label until item has been attached
18660 item.fitLabel();
18661 } else {
18662 this.newItems.push( item );
18663 }
18664 }
18665
18666 // Reevaluate clipping
18667 this.clip();
18668
18669 return this;
18670 };
18671
18672 /**
18673 * @inheritdoc
18674 */
18675 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18676 // Parent method
18677 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18678
18679 // Reevaluate clipping
18680 this.clip();
18681
18682 return this;
18683 };
18684
18685 /**
18686 * @inheritdoc
18687 */
18688 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18689 // Parent method
18690 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18691
18692 // Reevaluate clipping
18693 this.clip();
18694
18695 return this;
18696 };
18697
18698 /**
18699 * @inheritdoc
18700 */
18701 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18702 var i, len, change;
18703
18704 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18705 change = visible !== this.isVisible();
18706
18707 // Parent method
18708 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18709
18710 if ( change ) {
18711 if ( visible ) {
18712 this.bindKeyDownListener();
18713 this.bindKeyPressListener();
18714
18715 if ( this.newItems && this.newItems.length ) {
18716 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18717 this.newItems[ i ].fitLabel();
18718 }
18719 this.newItems = null;
18720 }
18721 this.toggleClipping( true );
18722
18723 // Auto-hide
18724 if ( this.autoHide ) {
18725 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18726 }
18727 } else {
18728 this.unbindKeyDownListener();
18729 this.unbindKeyPressListener();
18730 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18731 this.toggleClipping( false );
18732 }
18733 }
18734
18735 return this;
18736 };
18737
18738 /**
18739 * FloatingMenuSelectWidget is a menu that will stick under a specified
18740 * container, even when it is inserted elsewhere in the document (for example,
18741 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18742 * menu from being clipped too aggresively.
18743 *
18744 * The menu's position is automatically calculated and maintained when the menu
18745 * is toggled or the window is resized.
18746 *
18747 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18748 *
18749 * @class
18750 * @extends OO.ui.MenuSelectWidget
18751 *
18752 * @constructor
18753 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18754 * Deprecated, omit this parameter and specify `$container` instead.
18755 * @param {Object} [config] Configuration options
18756 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18757 */
18758 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
18759 // Allow 'inputWidget' parameter and config for backwards compatibility
18760 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18761 config = inputWidget;
18762 inputWidget = config.inputWidget;
18763 }
18764
18765 // Configuration initialization
18766 config = config || {};
18767
18768 // Parent constructor
18769 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
18770
18771 // Properties
18772 this.inputWidget = inputWidget; // For backwards compatibility
18773 this.$container = config.$container || this.inputWidget.$element;
18774 this.onWindowResizeHandler = this.onWindowResize.bind( this );
18775
18776 // Initialization
18777 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
18778 // For backwards compatibility
18779 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
18780 };
18781
18782 /* Setup */
18783
18784 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
18785
18786 // For backwards compatibility
18787 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
18788
18789 /* Methods */
18790
18791 /**
18792 * Handle window resize event.
18793 *
18794 * @private
18795 * @param {jQuery.Event} e Window resize event
18796 */
18797 OO.ui.FloatingMenuSelectWidget.prototype.onWindowResize = function () {
18798 this.position();
18799 };
18800
18801 /**
18802 * @inheritdoc
18803 */
18804 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
18805 var change;
18806 visible = visible === undefined ? !this.isVisible() : !!visible;
18807
18808 change = visible !== this.isVisible();
18809
18810 if ( change && visible ) {
18811 // Make sure the width is set before the parent method runs.
18812 // After this we have to call this.position(); again to actually
18813 // position ourselves correctly.
18814 this.position();
18815 }
18816
18817 // Parent method
18818 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
18819
18820 if ( change ) {
18821 if ( this.isVisible() ) {
18822 this.position();
18823 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
18824 } else {
18825 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
18826 }
18827 }
18828
18829 return this;
18830 };
18831
18832 /**
18833 * Position the menu.
18834 *
18835 * @private
18836 * @chainable
18837 */
18838 OO.ui.FloatingMenuSelectWidget.prototype.position = function () {
18839 var $container = this.$container,
18840 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
18841
18842 // Position under input
18843 pos.top += $container.height();
18844 this.$element.css( pos );
18845
18846 // Set width
18847 this.setIdealSize( $container.width() );
18848 // We updated the position, so re-evaluate the clipping state
18849 this.clip();
18850
18851 return this;
18852 };
18853
18854 /**
18855 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18856 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18857 *
18858 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18859 *
18860 * @class
18861 * @extends OO.ui.SelectWidget
18862 * @mixins OO.ui.mixin.TabIndexedElement
18863 *
18864 * @constructor
18865 * @param {Object} [config] Configuration options
18866 */
18867 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
18868 // Parent constructor
18869 OO.ui.OutlineSelectWidget.parent.call( this, config );
18870
18871 // Mixin constructors
18872 OO.ui.mixin.TabIndexedElement.call( this, config );
18873
18874 // Events
18875 this.$element.on( {
18876 focus: this.bindKeyDownListener.bind( this ),
18877 blur: this.unbindKeyDownListener.bind( this )
18878 } );
18879
18880 // Initialization
18881 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
18882 };
18883
18884 /* Setup */
18885
18886 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
18887 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
18888
18889 /**
18890 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18891 *
18892 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18893 *
18894 * @class
18895 * @extends OO.ui.SelectWidget
18896 * @mixins OO.ui.mixin.TabIndexedElement
18897 *
18898 * @constructor
18899 * @param {Object} [config] Configuration options
18900 */
18901 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
18902 // Parent constructor
18903 OO.ui.TabSelectWidget.parent.call( this, config );
18904
18905 // Mixin constructors
18906 OO.ui.mixin.TabIndexedElement.call( this, config );
18907
18908 // Events
18909 this.$element.on( {
18910 focus: this.bindKeyDownListener.bind( this ),
18911 blur: this.unbindKeyDownListener.bind( this )
18912 } );
18913
18914 // Initialization
18915 this.$element.addClass( 'oo-ui-tabSelectWidget' );
18916 };
18917
18918 /* Setup */
18919
18920 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
18921 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
18922
18923 /**
18924 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18925 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18926 * (to adjust the value in increments) to allow the user to enter a number.
18927 *
18928 * @example
18929 * // Example: A NumberInputWidget.
18930 * var numberInput = new OO.ui.NumberInputWidget( {
18931 * label: 'NumberInputWidget',
18932 * input: { value: 5, min: 1, max: 10 }
18933 * } );
18934 * $( 'body' ).append( numberInput.$element );
18935 *
18936 * @class
18937 * @extends OO.ui.Widget
18938 *
18939 * @constructor
18940 * @param {Object} [config] Configuration options
18941 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18942 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18943 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18944 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18945 * @cfg {number} [min=-Infinity] Minimum allowed value
18946 * @cfg {number} [max=Infinity] Maximum allowed value
18947 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18948 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18949 */
18950 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
18951 // Configuration initialization
18952 config = $.extend( {
18953 isInteger: false,
18954 min: -Infinity,
18955 max: Infinity,
18956 step: 1,
18957 pageStep: null
18958 }, config );
18959
18960 // Parent constructor
18961 OO.ui.NumberInputWidget.parent.call( this, config );
18962
18963 // Properties
18964 this.input = new OO.ui.TextInputWidget( $.extend(
18965 {
18966 disabled: this.isDisabled()
18967 },
18968 config.input
18969 ) );
18970 this.minusButton = new OO.ui.ButtonWidget( $.extend(
18971 {
18972 disabled: this.isDisabled(),
18973 tabIndex: -1
18974 },
18975 config.minusButton,
18976 {
18977 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
18978 label: '−'
18979 }
18980 ) );
18981 this.plusButton = new OO.ui.ButtonWidget( $.extend(
18982 {
18983 disabled: this.isDisabled(),
18984 tabIndex: -1
18985 },
18986 config.plusButton,
18987 {
18988 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
18989 label: '+'
18990 }
18991 ) );
18992
18993 // Events
18994 this.input.connect( this, {
18995 change: this.emit.bind( this, 'change' ),
18996 enter: this.emit.bind( this, 'enter' )
18997 } );
18998 this.input.$input.on( {
18999 keydown: this.onKeyDown.bind( this ),
19000 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
19001 } );
19002 this.plusButton.connect( this, {
19003 click: [ 'onButtonClick', +1 ]
19004 } );
19005 this.minusButton.connect( this, {
19006 click: [ 'onButtonClick', -1 ]
19007 } );
19008
19009 // Initialization
19010 this.setIsInteger( !!config.isInteger );
19011 this.setRange( config.min, config.max );
19012 this.setStep( config.step, config.pageStep );
19013
19014 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19015 .append(
19016 this.minusButton.$element,
19017 this.input.$element,
19018 this.plusButton.$element
19019 );
19020 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19021 this.input.setValidation( this.validateNumber.bind( this ) );
19022 };
19023
19024 /* Setup */
19025
19026 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19027
19028 /* Events */
19029
19030 /**
19031 * A `change` event is emitted when the value of the input changes.
19032 *
19033 * @event change
19034 */
19035
19036 /**
19037 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19038 *
19039 * @event enter
19040 */
19041
19042 /* Methods */
19043
19044 /**
19045 * Set whether only integers are allowed
19046 * @param {boolean} flag
19047 */
19048 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19049 this.isInteger = !!flag;
19050 this.input.setValidityFlag();
19051 };
19052
19053 /**
19054 * Get whether only integers are allowed
19055 * @return {boolean} Flag value
19056 */
19057 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19058 return this.isInteger;
19059 };
19060
19061 /**
19062 * Set the range of allowed values
19063 * @param {number} min Minimum allowed value
19064 * @param {number} max Maximum allowed value
19065 */
19066 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19067 if ( min > max ) {
19068 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19069 }
19070 this.min = min;
19071 this.max = max;
19072 this.input.setValidityFlag();
19073 };
19074
19075 /**
19076 * Get the current range
19077 * @return {number[]} Minimum and maximum values
19078 */
19079 OO.ui.NumberInputWidget.prototype.getRange = function () {
19080 return [ this.min, this.max ];
19081 };
19082
19083 /**
19084 * Set the stepping deltas
19085 * @param {number} step Normal step
19086 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19087 */
19088 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19089 if ( step <= 0 ) {
19090 throw new Error( 'Step value must be positive' );
19091 }
19092 if ( pageStep === null ) {
19093 pageStep = step * 10;
19094 } else if ( pageStep <= 0 ) {
19095 throw new Error( 'Page step value must be positive' );
19096 }
19097 this.step = step;
19098 this.pageStep = pageStep;
19099 };
19100
19101 /**
19102 * Get the current stepping values
19103 * @return {number[]} Step and page step
19104 */
19105 OO.ui.NumberInputWidget.prototype.getStep = function () {
19106 return [ this.step, this.pageStep ];
19107 };
19108
19109 /**
19110 * Get the current value of the widget
19111 * @return {string}
19112 */
19113 OO.ui.NumberInputWidget.prototype.getValue = function () {
19114 return this.input.getValue();
19115 };
19116
19117 /**
19118 * Get the current value of the widget as a number
19119 * @return {number} May be NaN, or an invalid number
19120 */
19121 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19122 return +this.input.getValue();
19123 };
19124
19125 /**
19126 * Set the value of the widget
19127 * @param {string} value Invalid values are allowed
19128 */
19129 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19130 this.input.setValue( value );
19131 };
19132
19133 /**
19134 * Adjust the value of the widget
19135 * @param {number} delta Adjustment amount
19136 */
19137 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19138 var n, v = this.getNumericValue();
19139
19140 delta = +delta;
19141 if ( isNaN( delta ) || !isFinite( delta ) ) {
19142 throw new Error( 'Delta must be a finite number' );
19143 }
19144
19145 if ( isNaN( v ) ) {
19146 n = 0;
19147 } else {
19148 n = v + delta;
19149 n = Math.max( Math.min( n, this.max ), this.min );
19150 if ( this.isInteger ) {
19151 n = Math.round( n );
19152 }
19153 }
19154
19155 if ( n !== v ) {
19156 this.setValue( n );
19157 }
19158 };
19159
19160 /**
19161 * Validate input
19162 * @private
19163 * @param {string} value Field value
19164 * @return {boolean}
19165 */
19166 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19167 var n = +value;
19168 if ( isNaN( n ) || !isFinite( n ) ) {
19169 return false;
19170 }
19171
19172 /*jshint bitwise: false */
19173 if ( this.isInteger && ( n | 0 ) !== n ) {
19174 return false;
19175 }
19176 /*jshint bitwise: true */
19177
19178 if ( n < this.min || n > this.max ) {
19179 return false;
19180 }
19181
19182 return true;
19183 };
19184
19185 /**
19186 * Handle mouse click events.
19187 *
19188 * @private
19189 * @param {number} dir +1 or -1
19190 */
19191 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19192 this.adjustValue( dir * this.step );
19193 };
19194
19195 /**
19196 * Handle mouse wheel events.
19197 *
19198 * @private
19199 * @param {jQuery.Event} event
19200 */
19201 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19202 var delta = 0;
19203
19204 // Standard 'wheel' event
19205 if ( event.originalEvent.deltaMode !== undefined ) {
19206 this.sawWheelEvent = true;
19207 }
19208 if ( event.originalEvent.deltaY ) {
19209 delta = -event.originalEvent.deltaY;
19210 } else if ( event.originalEvent.deltaX ) {
19211 delta = event.originalEvent.deltaX;
19212 }
19213
19214 // Non-standard events
19215 if ( !this.sawWheelEvent ) {
19216 if ( event.originalEvent.wheelDeltaX ) {
19217 delta = -event.originalEvent.wheelDeltaX;
19218 } else if ( event.originalEvent.wheelDeltaY ) {
19219 delta = event.originalEvent.wheelDeltaY;
19220 } else if ( event.originalEvent.wheelDelta ) {
19221 delta = event.originalEvent.wheelDelta;
19222 } else if ( event.originalEvent.detail ) {
19223 delta = -event.originalEvent.detail;
19224 }
19225 }
19226
19227 if ( delta ) {
19228 delta = delta < 0 ? -1 : 1;
19229 this.adjustValue( delta * this.step );
19230 }
19231
19232 return false;
19233 };
19234
19235 /**
19236 * Handle key down events.
19237 *
19238 *
19239 * @private
19240 * @param {jQuery.Event} e Key down event
19241 */
19242 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19243 if ( !this.isDisabled() ) {
19244 switch ( e.which ) {
19245 case OO.ui.Keys.UP:
19246 this.adjustValue( this.step );
19247 return false;
19248 case OO.ui.Keys.DOWN:
19249 this.adjustValue( -this.step );
19250 return false;
19251 case OO.ui.Keys.PAGEUP:
19252 this.adjustValue( this.pageStep );
19253 return false;
19254 case OO.ui.Keys.PAGEDOWN:
19255 this.adjustValue( -this.pageStep );
19256 return false;
19257 }
19258 }
19259 };
19260
19261 /**
19262 * @inheritdoc
19263 */
19264 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19265 // Parent method
19266 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19267
19268 if ( this.input ) {
19269 this.input.setDisabled( this.isDisabled() );
19270 }
19271 if ( this.minusButton ) {
19272 this.minusButton.setDisabled( this.isDisabled() );
19273 }
19274 if ( this.plusButton ) {
19275 this.plusButton.setDisabled( this.isDisabled() );
19276 }
19277
19278 return this;
19279 };
19280
19281 /**
19282 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19283 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19284 * visually by a slider in the leftmost position.
19285 *
19286 * @example
19287 * // Toggle switches in the 'off' and 'on' position.
19288 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19289 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19290 * value: true
19291 * } );
19292 *
19293 * // Create a FieldsetLayout to layout and label switches
19294 * var fieldset = new OO.ui.FieldsetLayout( {
19295 * label: 'Toggle switches'
19296 * } );
19297 * fieldset.addItems( [
19298 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19299 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19300 * ] );
19301 * $( 'body' ).append( fieldset.$element );
19302 *
19303 * @class
19304 * @extends OO.ui.ToggleWidget
19305 * @mixins OO.ui.mixin.TabIndexedElement
19306 *
19307 * @constructor
19308 * @param {Object} [config] Configuration options
19309 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19310 * By default, the toggle switch is in the 'off' position.
19311 */
19312 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19313 // Parent constructor
19314 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19315
19316 // Mixin constructors
19317 OO.ui.mixin.TabIndexedElement.call( this, config );
19318
19319 // Properties
19320 this.dragging = false;
19321 this.dragStart = null;
19322 this.sliding = false;
19323 this.$glow = $( '<span>' );
19324 this.$grip = $( '<span>' );
19325
19326 // Events
19327 this.$element.on( {
19328 click: this.onClick.bind( this ),
19329 keypress: this.onKeyPress.bind( this )
19330 } );
19331
19332 // Initialization
19333 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19334 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19335 this.$element
19336 .addClass( 'oo-ui-toggleSwitchWidget' )
19337 .attr( 'role', 'checkbox' )
19338 .append( this.$glow, this.$grip );
19339 };
19340
19341 /* Setup */
19342
19343 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19344 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19345
19346 /* Methods */
19347
19348 /**
19349 * Handle mouse click events.
19350 *
19351 * @private
19352 * @param {jQuery.Event} e Mouse click event
19353 */
19354 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19355 if ( !this.isDisabled() && e.which === 1 ) {
19356 this.setValue( !this.value );
19357 }
19358 return false;
19359 };
19360
19361 /**
19362 * Handle key press events.
19363 *
19364 * @private
19365 * @param {jQuery.Event} e Key press event
19366 */
19367 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19368 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19369 this.setValue( !this.value );
19370 return false;
19371 }
19372 };
19373
19374 /*!
19375 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19376 */
19377
19378 /**
19379 * @inheritdoc OO.ui.mixin.ButtonElement
19380 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19381 */
19382 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19383
19384 /**
19385 * @inheritdoc OO.ui.mixin.ClippableElement
19386 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19387 */
19388 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19389
19390 /**
19391 * @inheritdoc OO.ui.mixin.DraggableElement
19392 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19393 */
19394 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19395
19396 /**
19397 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19398 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19399 */
19400 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19401
19402 /**
19403 * @inheritdoc OO.ui.mixin.FlaggedElement
19404 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19405 */
19406 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19407
19408 /**
19409 * @inheritdoc OO.ui.mixin.GroupElement
19410 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19411 */
19412 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19413
19414 /**
19415 * @inheritdoc OO.ui.mixin.GroupWidget
19416 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19417 */
19418 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19419
19420 /**
19421 * @inheritdoc OO.ui.mixin.IconElement
19422 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19423 */
19424 OO.ui.IconElement = OO.ui.mixin.IconElement;
19425
19426 /**
19427 * @inheritdoc OO.ui.mixin.IndicatorElement
19428 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19429 */
19430 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19431
19432 /**
19433 * @inheritdoc OO.ui.mixin.ItemWidget
19434 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19435 */
19436 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19437
19438 /**
19439 * @inheritdoc OO.ui.mixin.LabelElement
19440 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19441 */
19442 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19443
19444 /**
19445 * @inheritdoc OO.ui.mixin.LookupElement
19446 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19447 */
19448 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19449
19450 /**
19451 * @inheritdoc OO.ui.mixin.PendingElement
19452 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19453 */
19454 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19455
19456 /**
19457 * @inheritdoc OO.ui.mixin.PopupElement
19458 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19459 */
19460 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19461
19462 /**
19463 * @inheritdoc OO.ui.mixin.TabIndexedElement
19464 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19465 */
19466 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19467
19468 /**
19469 * @inheritdoc OO.ui.mixin.TitledElement
19470 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19471 */
19472 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19473
19474 }( OO ) );