Merge "Move HTMLForm-specific styles out of mediawiki.legacy.shared"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.12.7
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-01T23:25:30Z
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 this.initialized = true;
7563 this.narrowThreshold = this.$group.width() + this.$actions.width();
7564 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7565 this.onWindowResize();
7566 };
7567
7568 /**
7569 * Set up the toolbar.
7570 *
7571 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7572 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7573 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7574 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7575 *
7576 * @param {Object.<string,Array>} groups List of toolgroup configurations
7577 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7578 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7579 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7580 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7581 */
7582 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7583 var i, len, type, group,
7584 items = [],
7585 defaultType = 'bar';
7586
7587 // Cleanup previous groups
7588 this.reset();
7589
7590 // Build out new groups
7591 for ( i = 0, len = groups.length; i < len; i++ ) {
7592 group = groups[ i ];
7593 if ( group.include === '*' ) {
7594 // Apply defaults to catch-all groups
7595 if ( group.type === undefined ) {
7596 group.type = 'list';
7597 }
7598 if ( group.label === undefined ) {
7599 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7600 }
7601 }
7602 // Check type has been registered
7603 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7604 items.push(
7605 this.getToolGroupFactory().create( type, this, group )
7606 );
7607 }
7608 this.addItems( items );
7609 };
7610
7611 /**
7612 * Remove all tools and toolgroups from the toolbar.
7613 */
7614 OO.ui.Toolbar.prototype.reset = function () {
7615 var i, len;
7616
7617 this.groups = [];
7618 this.tools = {};
7619 for ( i = 0, len = this.items.length; i < len; i++ ) {
7620 this.items[ i ].destroy();
7621 }
7622 this.clearItems();
7623 };
7624
7625 /**
7626 * Destroy the toolbar.
7627 *
7628 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7629 * this method whenever you are done using a toolbar.
7630 */
7631 OO.ui.Toolbar.prototype.destroy = function () {
7632 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7633 this.reset();
7634 this.$element.remove();
7635 };
7636
7637 /**
7638 * Check if the tool is available.
7639 *
7640 * Available tools are ones that have not yet been added to the toolbar.
7641 *
7642 * @param {string} name Symbolic name of tool
7643 * @return {boolean} Tool is available
7644 */
7645 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7646 return !this.tools[ name ];
7647 };
7648
7649 /**
7650 * Prevent tool from being used again.
7651 *
7652 * @param {OO.ui.Tool} tool Tool to reserve
7653 */
7654 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7655 this.tools[ tool.getName() ] = tool;
7656 };
7657
7658 /**
7659 * Allow tool to be used again.
7660 *
7661 * @param {OO.ui.Tool} tool Tool to release
7662 */
7663 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7664 delete this.tools[ tool.getName() ];
7665 };
7666
7667 /**
7668 * Get accelerator label for tool.
7669 *
7670 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7671 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7672 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7673 *
7674 * @param {string} name Symbolic name of tool
7675 * @return {string|undefined} Tool accelerator label if available
7676 */
7677 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7678 return undefined;
7679 };
7680
7681 /**
7682 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7683 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7684 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7685 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7686 *
7687 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7688 *
7689 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7690 *
7691 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7692 *
7693 * 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.)
7694 *
7695 * include: [ { group: 'group-name' } ]
7696 *
7697 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7698 *
7699 * include: '*'
7700 *
7701 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7702 * please see the [OOjs UI documentation on MediaWiki][1].
7703 *
7704 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7705 *
7706 * @abstract
7707 * @class
7708 * @extends OO.ui.Widget
7709 * @mixins OO.ui.mixin.GroupElement
7710 *
7711 * @constructor
7712 * @param {OO.ui.Toolbar} toolbar
7713 * @param {Object} [config] Configuration options
7714 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7715 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7716 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7717 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7718 * This setting is particularly useful when tools have been added to the toolgroup
7719 * en masse (e.g., via the catch-all selector).
7720 */
7721 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7722 // Allow passing positional parameters inside the config object
7723 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7724 config = toolbar;
7725 toolbar = config.toolbar;
7726 }
7727
7728 // Configuration initialization
7729 config = config || {};
7730
7731 // Parent constructor
7732 OO.ui.ToolGroup.parent.call( this, config );
7733
7734 // Mixin constructors
7735 OO.ui.mixin.GroupElement.call( this, config );
7736
7737 // Properties
7738 this.toolbar = toolbar;
7739 this.tools = {};
7740 this.pressed = null;
7741 this.autoDisabled = false;
7742 this.include = config.include || [];
7743 this.exclude = config.exclude || [];
7744 this.promote = config.promote || [];
7745 this.demote = config.demote || [];
7746 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7747
7748 // Events
7749 this.$element.on( {
7750 mousedown: this.onMouseKeyDown.bind( this ),
7751 mouseup: this.onMouseKeyUp.bind( this ),
7752 keydown: this.onMouseKeyDown.bind( this ),
7753 keyup: this.onMouseKeyUp.bind( this ),
7754 focus: this.onMouseOverFocus.bind( this ),
7755 blur: this.onMouseOutBlur.bind( this ),
7756 mouseover: this.onMouseOverFocus.bind( this ),
7757 mouseout: this.onMouseOutBlur.bind( this )
7758 } );
7759 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7760 this.aggregate( { disable: 'itemDisable' } );
7761 this.connect( this, { itemDisable: 'updateDisabled' } );
7762
7763 // Initialization
7764 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7765 this.$element
7766 .addClass( 'oo-ui-toolGroup' )
7767 .append( this.$group );
7768 this.populate();
7769 };
7770
7771 /* Setup */
7772
7773 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7774 OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
7775
7776 /* Events */
7777
7778 /**
7779 * @event update
7780 */
7781
7782 /* Static Properties */
7783
7784 /**
7785 * Show labels in tooltips.
7786 *
7787 * @static
7788 * @inheritable
7789 * @property {boolean}
7790 */
7791 OO.ui.ToolGroup.static.titleTooltips = false;
7792
7793 /**
7794 * Show acceleration labels in tooltips.
7795 *
7796 * Note: The OOjs UI library does not include an accelerator system, but does contain
7797 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7798 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7799 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7800 *
7801 * @static
7802 * @inheritable
7803 * @property {boolean}
7804 */
7805 OO.ui.ToolGroup.static.accelTooltips = false;
7806
7807 /**
7808 * Automatically disable the toolgroup when all tools are disabled
7809 *
7810 * @static
7811 * @inheritable
7812 * @property {boolean}
7813 */
7814 OO.ui.ToolGroup.static.autoDisable = true;
7815
7816 /* Methods */
7817
7818 /**
7819 * @inheritdoc
7820 */
7821 OO.ui.ToolGroup.prototype.isDisabled = function () {
7822 return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments );
7823 };
7824
7825 /**
7826 * @inheritdoc
7827 */
7828 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7829 var i, item, allDisabled = true;
7830
7831 if ( this.constructor.static.autoDisable ) {
7832 for ( i = this.items.length - 1; i >= 0; i-- ) {
7833 item = this.items[ i ];
7834 if ( !item.isDisabled() ) {
7835 allDisabled = false;
7836 break;
7837 }
7838 }
7839 this.autoDisabled = allDisabled;
7840 }
7841 OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments );
7842 };
7843
7844 /**
7845 * Handle mouse down and key down events.
7846 *
7847 * @protected
7848 * @param {jQuery.Event} e Mouse down or key down event
7849 */
7850 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7851 if (
7852 !this.isDisabled() &&
7853 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7854 ) {
7855 this.pressed = this.getTargetTool( e );
7856 if ( this.pressed ) {
7857 this.pressed.setActive( true );
7858 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7859 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7860 }
7861 return false;
7862 }
7863 };
7864
7865 /**
7866 * Handle captured mouse up and key up events.
7867 *
7868 * @protected
7869 * @param {Event} e Mouse up or key up event
7870 */
7871 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7872 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler );
7873 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler );
7874 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7875 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7876 this.onMouseKeyUp( e );
7877 };
7878
7879 /**
7880 * Handle mouse up and key up events.
7881 *
7882 * @protected
7883 * @param {jQuery.Event} e Mouse up or key up event
7884 */
7885 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7886 var tool = this.getTargetTool( e );
7887
7888 if (
7889 !this.isDisabled() && this.pressed && this.pressed === tool &&
7890 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7891 ) {
7892 this.pressed.onSelect();
7893 this.pressed = null;
7894 return false;
7895 }
7896
7897 this.pressed = null;
7898 };
7899
7900 /**
7901 * Handle mouse over and focus events.
7902 *
7903 * @protected
7904 * @param {jQuery.Event} e Mouse over or focus event
7905 */
7906 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7907 var tool = this.getTargetTool( e );
7908
7909 if ( this.pressed && this.pressed === tool ) {
7910 this.pressed.setActive( true );
7911 }
7912 };
7913
7914 /**
7915 * Handle mouse out and blur events.
7916 *
7917 * @protected
7918 * @param {jQuery.Event} e Mouse out or blur event
7919 */
7920 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7921 var tool = this.getTargetTool( e );
7922
7923 if ( this.pressed && this.pressed === tool ) {
7924 this.pressed.setActive( false );
7925 }
7926 };
7927
7928 /**
7929 * Get the closest tool to a jQuery.Event.
7930 *
7931 * Only tool links are considered, which prevents other elements in the tool such as popups from
7932 * triggering tool group interactions.
7933 *
7934 * @private
7935 * @param {jQuery.Event} e
7936 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7937 */
7938 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7939 var tool,
7940 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7941
7942 if ( $item.length ) {
7943 tool = $item.parent().data( 'oo-ui-tool' );
7944 }
7945
7946 return tool && !tool.isDisabled() ? tool : null;
7947 };
7948
7949 /**
7950 * Handle tool registry register events.
7951 *
7952 * If a tool is registered after the group is created, we must repopulate the list to account for:
7953 *
7954 * - a tool being added that may be included
7955 * - a tool already included being overridden
7956 *
7957 * @protected
7958 * @param {string} name Symbolic name of tool
7959 */
7960 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7961 this.populate();
7962 };
7963
7964 /**
7965 * Get the toolbar that contains the toolgroup.
7966 *
7967 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7968 */
7969 OO.ui.ToolGroup.prototype.getToolbar = function () {
7970 return this.toolbar;
7971 };
7972
7973 /**
7974 * Add and remove tools based on configuration.
7975 */
7976 OO.ui.ToolGroup.prototype.populate = function () {
7977 var i, len, name, tool,
7978 toolFactory = this.toolbar.getToolFactory(),
7979 names = {},
7980 add = [],
7981 remove = [],
7982 list = this.toolbar.getToolFactory().getTools(
7983 this.include, this.exclude, this.promote, this.demote
7984 );
7985
7986 // Build a list of needed tools
7987 for ( i = 0, len = list.length; i < len; i++ ) {
7988 name = list[ i ];
7989 if (
7990 // Tool exists
7991 toolFactory.lookup( name ) &&
7992 // Tool is available or is already in this group
7993 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7994 ) {
7995 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7996 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7997 this.toolbar.tools[ name ] = true;
7998 tool = this.tools[ name ];
7999 if ( !tool ) {
8000 // Auto-initialize tools on first use
8001 this.tools[ name ] = tool = toolFactory.create( name, this );
8002 tool.updateTitle();
8003 }
8004 this.toolbar.reserveTool( tool );
8005 add.push( tool );
8006 names[ name ] = true;
8007 }
8008 }
8009 // Remove tools that are no longer needed
8010 for ( name in this.tools ) {
8011 if ( !names[ name ] ) {
8012 this.tools[ name ].destroy();
8013 this.toolbar.releaseTool( this.tools[ name ] );
8014 remove.push( this.tools[ name ] );
8015 delete this.tools[ name ];
8016 }
8017 }
8018 if ( remove.length ) {
8019 this.removeItems( remove );
8020 }
8021 // Update emptiness state
8022 if ( add.length ) {
8023 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
8024 } else {
8025 this.$element.addClass( 'oo-ui-toolGroup-empty' );
8026 }
8027 // Re-add tools (moving existing ones to new locations)
8028 this.addItems( add );
8029 // Disabled state may depend on items
8030 this.updateDisabled();
8031 };
8032
8033 /**
8034 * Destroy toolgroup.
8035 */
8036 OO.ui.ToolGroup.prototype.destroy = function () {
8037 var name;
8038
8039 this.clearItems();
8040 this.toolbar.getToolFactory().disconnect( this );
8041 for ( name in this.tools ) {
8042 this.toolbar.releaseTool( this.tools[ name ] );
8043 this.tools[ name ].disconnect( this ).destroy();
8044 delete this.tools[ name ];
8045 }
8046 this.$element.remove();
8047 };
8048
8049 /**
8050 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8051 * consists of a header that contains the dialog title, a body with the message, and a footer that
8052 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8053 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8054 *
8055 * There are two basic types of message dialogs, confirmation and alert:
8056 *
8057 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8058 * more details about the consequences.
8059 * - **alert**: the dialog title describes which event occurred and the message provides more information
8060 * about why the event occurred.
8061 *
8062 * The MessageDialog class specifies two actions: ‘accept’, the primary
8063 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8064 * passing along the selected action.
8065 *
8066 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8067 *
8068 * @example
8069 * // Example: Creating and opening a message dialog window.
8070 * var messageDialog = new OO.ui.MessageDialog();
8071 *
8072 * // Create and append a window manager.
8073 * var windowManager = new OO.ui.WindowManager();
8074 * $( 'body' ).append( windowManager.$element );
8075 * windowManager.addWindows( [ messageDialog ] );
8076 * // Open the window.
8077 * windowManager.openWindow( messageDialog, {
8078 * title: 'Basic message dialog',
8079 * message: 'This is the message'
8080 * } );
8081 *
8082 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8083 *
8084 * @class
8085 * @extends OO.ui.Dialog
8086 *
8087 * @constructor
8088 * @param {Object} [config] Configuration options
8089 */
8090 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
8091 // Parent constructor
8092 OO.ui.MessageDialog.parent.call( this, config );
8093
8094 // Properties
8095 this.verticalActionLayout = null;
8096
8097 // Initialization
8098 this.$element.addClass( 'oo-ui-messageDialog' );
8099 };
8100
8101 /* Setup */
8102
8103 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
8104
8105 /* Static Properties */
8106
8107 OO.ui.MessageDialog.static.name = 'message';
8108
8109 OO.ui.MessageDialog.static.size = 'small';
8110
8111 OO.ui.MessageDialog.static.verbose = false;
8112
8113 /**
8114 * Dialog title.
8115 *
8116 * The title of a confirmation dialog describes what a progressive action will do. The
8117 * title of an alert dialog describes which event occurred.
8118 *
8119 * @static
8120 * @inheritable
8121 * @property {jQuery|string|Function|null}
8122 */
8123 OO.ui.MessageDialog.static.title = null;
8124
8125 /**
8126 * The message displayed in the dialog body.
8127 *
8128 * A confirmation message describes the consequences of a progressive action. An alert
8129 * message describes why an event occurred.
8130 *
8131 * @static
8132 * @inheritable
8133 * @property {jQuery|string|Function|null}
8134 */
8135 OO.ui.MessageDialog.static.message = null;
8136
8137 OO.ui.MessageDialog.static.actions = [
8138 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
8139 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
8140 ];
8141
8142 /* Methods */
8143
8144 /**
8145 * @inheritdoc
8146 */
8147 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
8148 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
8149
8150 // Events
8151 this.manager.connect( this, {
8152 resize: 'onResize'
8153 } );
8154
8155 return this;
8156 };
8157
8158 /**
8159 * @inheritdoc
8160 */
8161 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
8162 this.fitActions();
8163 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
8164 };
8165
8166 /**
8167 * Handle window resized events.
8168 *
8169 * @private
8170 */
8171 OO.ui.MessageDialog.prototype.onResize = function () {
8172 var dialog = this;
8173 dialog.fitActions();
8174 // Wait for CSS transition to finish and do it again :(
8175 setTimeout( function () {
8176 dialog.fitActions();
8177 }, 300 );
8178 };
8179
8180 /**
8181 * Toggle action layout between vertical and horizontal.
8182 *
8183 *
8184 * @private
8185 * @param {boolean} [value] Layout actions vertically, omit to toggle
8186 * @chainable
8187 */
8188 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
8189 value = value === undefined ? !this.verticalActionLayout : !!value;
8190
8191 if ( value !== this.verticalActionLayout ) {
8192 this.verticalActionLayout = value;
8193 this.$actions
8194 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
8195 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
8196 }
8197
8198 return this;
8199 };
8200
8201 /**
8202 * @inheritdoc
8203 */
8204 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
8205 if ( action ) {
8206 return new OO.ui.Process( function () {
8207 this.close( { action: action } );
8208 }, this );
8209 }
8210 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
8211 };
8212
8213 /**
8214 * @inheritdoc
8215 *
8216 * @param {Object} [data] Dialog opening data
8217 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8218 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8219 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8220 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8221 * action item
8222 */
8223 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
8224 data = data || {};
8225
8226 // Parent method
8227 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
8228 .next( function () {
8229 this.title.setLabel(
8230 data.title !== undefined ? data.title : this.constructor.static.title
8231 );
8232 this.message.setLabel(
8233 data.message !== undefined ? data.message : this.constructor.static.message
8234 );
8235 this.message.$element.toggleClass(
8236 'oo-ui-messageDialog-message-verbose',
8237 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
8238 );
8239 }, this );
8240 };
8241
8242 /**
8243 * @inheritdoc
8244 */
8245 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
8246 data = data || {};
8247
8248 // Parent method
8249 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
8250 .next( function () {
8251 // Focus the primary action button
8252 var actions = this.actions.get();
8253 actions = actions.filter( function ( action ) {
8254 return action.getFlags().indexOf( 'primary' ) > -1;
8255 } );
8256 if ( actions.length > 0 ) {
8257 actions[ 0 ].$button.focus();
8258 }
8259 }, this );
8260 };
8261
8262 /**
8263 * @inheritdoc
8264 */
8265 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
8266 var bodyHeight, oldOverflow,
8267 $scrollable = this.container.$element;
8268
8269 oldOverflow = $scrollable[ 0 ].style.overflow;
8270 $scrollable[ 0 ].style.overflow = 'hidden';
8271
8272 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8273
8274 bodyHeight = this.text.$element.outerHeight( true );
8275 $scrollable[ 0 ].style.overflow = oldOverflow;
8276
8277 return bodyHeight;
8278 };
8279
8280 /**
8281 * @inheritdoc
8282 */
8283 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
8284 var $scrollable = this.container.$element;
8285 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
8286
8287 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8288 // Need to do it after transition completes (250ms), add 50ms just in case.
8289 setTimeout( function () {
8290 var oldOverflow = $scrollable[ 0 ].style.overflow;
8291 $scrollable[ 0 ].style.overflow = 'hidden';
8292
8293 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
8294
8295 $scrollable[ 0 ].style.overflow = oldOverflow;
8296 }, 300 );
8297
8298 return this;
8299 };
8300
8301 /**
8302 * @inheritdoc
8303 */
8304 OO.ui.MessageDialog.prototype.initialize = function () {
8305 // Parent method
8306 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
8307
8308 // Properties
8309 this.$actions = $( '<div>' );
8310 this.container = new OO.ui.PanelLayout( {
8311 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
8312 } );
8313 this.text = new OO.ui.PanelLayout( {
8314 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
8315 } );
8316 this.message = new OO.ui.LabelWidget( {
8317 classes: [ 'oo-ui-messageDialog-message' ]
8318 } );
8319
8320 // Initialization
8321 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
8322 this.$content.addClass( 'oo-ui-messageDialog-content' );
8323 this.container.$element.append( this.text.$element );
8324 this.text.$element.append( this.title.$element, this.message.$element );
8325 this.$body.append( this.container.$element );
8326 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
8327 this.$foot.append( this.$actions );
8328 };
8329
8330 /**
8331 * @inheritdoc
8332 */
8333 OO.ui.MessageDialog.prototype.attachActions = function () {
8334 var i, len, other, special, others;
8335
8336 // Parent method
8337 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
8338
8339 special = this.actions.getSpecial();
8340 others = this.actions.getOthers();
8341
8342 if ( special.safe ) {
8343 this.$actions.append( special.safe.$element );
8344 special.safe.toggleFramed( false );
8345 }
8346 if ( others.length ) {
8347 for ( i = 0, len = others.length; i < len; i++ ) {
8348 other = others[ i ];
8349 this.$actions.append( other.$element );
8350 other.toggleFramed( false );
8351 }
8352 }
8353 if ( special.primary ) {
8354 this.$actions.append( special.primary.$element );
8355 special.primary.toggleFramed( false );
8356 }
8357
8358 if ( !this.isOpening() ) {
8359 // If the dialog is currently opening, this will be called automatically soon.
8360 // This also calls #fitActions.
8361 this.updateSize();
8362 }
8363 };
8364
8365 /**
8366 * Fit action actions into columns or rows.
8367 *
8368 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8369 *
8370 * @private
8371 */
8372 OO.ui.MessageDialog.prototype.fitActions = function () {
8373 var i, len, action,
8374 previous = this.verticalActionLayout,
8375 actions = this.actions.get();
8376
8377 // Detect clipping
8378 this.toggleVerticalActionLayout( false );
8379 for ( i = 0, len = actions.length; i < len; i++ ) {
8380 action = actions[ i ];
8381 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
8382 this.toggleVerticalActionLayout( true );
8383 break;
8384 }
8385 }
8386
8387 // Move the body out of the way of the foot
8388 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8389
8390 if ( this.verticalActionLayout !== previous ) {
8391 // We changed the layout, window height might need to be updated.
8392 this.updateSize();
8393 }
8394 };
8395
8396 /**
8397 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8398 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8399 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8400 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8401 * required for each process.
8402 *
8403 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8404 * processes with an animation. The header contains the dialog title as well as
8405 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8406 * a ‘primary’ action on the right (e.g., ‘Done’).
8407 *
8408 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8409 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8410 *
8411 * @example
8412 * // Example: Creating and opening a process dialog window.
8413 * function MyProcessDialog( config ) {
8414 * MyProcessDialog.parent.call( this, config );
8415 * }
8416 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8417 *
8418 * MyProcessDialog.static.title = 'Process dialog';
8419 * MyProcessDialog.static.actions = [
8420 * { action: 'save', label: 'Done', flags: 'primary' },
8421 * { label: 'Cancel', flags: 'safe' }
8422 * ];
8423 *
8424 * MyProcessDialog.prototype.initialize = function () {
8425 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8426 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8427 * 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>' );
8428 * this.$body.append( this.content.$element );
8429 * };
8430 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8431 * var dialog = this;
8432 * if ( action ) {
8433 * return new OO.ui.Process( function () {
8434 * dialog.close( { action: action } );
8435 * } );
8436 * }
8437 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8438 * };
8439 *
8440 * var windowManager = new OO.ui.WindowManager();
8441 * $( 'body' ).append( windowManager.$element );
8442 *
8443 * var dialog = new MyProcessDialog();
8444 * windowManager.addWindows( [ dialog ] );
8445 * windowManager.openWindow( dialog );
8446 *
8447 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8448 *
8449 * @abstract
8450 * @class
8451 * @extends OO.ui.Dialog
8452 *
8453 * @constructor
8454 * @param {Object} [config] Configuration options
8455 */
8456 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
8457 // Parent constructor
8458 OO.ui.ProcessDialog.parent.call( this, config );
8459
8460 // Properties
8461 this.fitOnOpen = false;
8462
8463 // Initialization
8464 this.$element.addClass( 'oo-ui-processDialog' );
8465 };
8466
8467 /* Setup */
8468
8469 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
8470
8471 /* Methods */
8472
8473 /**
8474 * Handle dismiss button click events.
8475 *
8476 * Hides errors.
8477 *
8478 * @private
8479 */
8480 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
8481 this.hideErrors();
8482 };
8483
8484 /**
8485 * Handle retry button click events.
8486 *
8487 * Hides errors and then tries again.
8488 *
8489 * @private
8490 */
8491 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
8492 this.hideErrors();
8493 this.executeAction( this.currentAction );
8494 };
8495
8496 /**
8497 * @inheritdoc
8498 */
8499 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
8500 if ( this.actions.isSpecial( action ) ) {
8501 this.fitLabel();
8502 }
8503 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
8504 };
8505
8506 /**
8507 * @inheritdoc
8508 */
8509 OO.ui.ProcessDialog.prototype.initialize = function () {
8510 // Parent method
8511 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
8512
8513 // Properties
8514 this.$navigation = $( '<div>' );
8515 this.$location = $( '<div>' );
8516 this.$safeActions = $( '<div>' );
8517 this.$primaryActions = $( '<div>' );
8518 this.$otherActions = $( '<div>' );
8519 this.dismissButton = new OO.ui.ButtonWidget( {
8520 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
8521 } );
8522 this.retryButton = new OO.ui.ButtonWidget();
8523 this.$errors = $( '<div>' );
8524 this.$errorsTitle = $( '<div>' );
8525
8526 // Events
8527 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
8528 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
8529
8530 // Initialization
8531 this.title.$element.addClass( 'oo-ui-processDialog-title' );
8532 this.$location
8533 .append( this.title.$element )
8534 .addClass( 'oo-ui-processDialog-location' );
8535 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
8536 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
8537 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
8538 this.$errorsTitle
8539 .addClass( 'oo-ui-processDialog-errors-title' )
8540 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
8541 this.$errors
8542 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8543 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
8544 this.$content
8545 .addClass( 'oo-ui-processDialog-content' )
8546 .append( this.$errors );
8547 this.$navigation
8548 .addClass( 'oo-ui-processDialog-navigation' )
8549 .append( this.$safeActions, this.$location, this.$primaryActions );
8550 this.$head.append( this.$navigation );
8551 this.$foot.append( this.$otherActions );
8552 };
8553
8554 /**
8555 * @inheritdoc
8556 */
8557 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8558 var i, len, widgets = [];
8559 for ( i = 0, len = actions.length; i < len; i++ ) {
8560 widgets.push(
8561 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8562 );
8563 }
8564 return widgets;
8565 };
8566
8567 /**
8568 * @inheritdoc
8569 */
8570 OO.ui.ProcessDialog.prototype.attachActions = function () {
8571 var i, len, other, special, others;
8572
8573 // Parent method
8574 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
8575
8576 special = this.actions.getSpecial();
8577 others = this.actions.getOthers();
8578 if ( special.primary ) {
8579 this.$primaryActions.append( special.primary.$element );
8580 }
8581 for ( i = 0, len = others.length; i < len; i++ ) {
8582 other = others[ i ];
8583 this.$otherActions.append( other.$element );
8584 }
8585 if ( special.safe ) {
8586 this.$safeActions.append( special.safe.$element );
8587 }
8588
8589 this.fitLabel();
8590 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8591 };
8592
8593 /**
8594 * @inheritdoc
8595 */
8596 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8597 var process = this;
8598 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
8599 .fail( function ( errors ) {
8600 process.showErrors( errors || [] );
8601 } );
8602 };
8603
8604 /**
8605 * @inheritdoc
8606 */
8607 OO.ui.ProcessDialog.prototype.setDimensions = function () {
8608 // Parent method
8609 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
8610
8611 this.fitLabel();
8612 };
8613
8614 /**
8615 * Fit label between actions.
8616 *
8617 * @private
8618 * @chainable
8619 */
8620 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8621 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
8622 size = this.getSizeProperties();
8623
8624 if ( typeof size.width !== 'number' ) {
8625 if ( this.isOpened() ) {
8626 navigationWidth = this.$head.width() - 20;
8627 } else if ( this.isOpening() ) {
8628 if ( !this.fitOnOpen ) {
8629 // Size is relative and the dialog isn't open yet, so wait.
8630 this.manager.opening.done( this.fitLabel.bind( this ) );
8631 this.fitOnOpen = true;
8632 }
8633 return;
8634 } else {
8635 return;
8636 }
8637 } else {
8638 navigationWidth = size.width - 20;
8639 }
8640
8641 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
8642 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
8643 biggerWidth = Math.max( safeWidth, primaryWidth );
8644
8645 labelWidth = this.title.$element.width();
8646
8647 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
8648 // We have enough space to center the label
8649 leftWidth = rightWidth = biggerWidth;
8650 } else {
8651 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8652 if ( this.getDir() === 'ltr' ) {
8653 leftWidth = safeWidth;
8654 rightWidth = primaryWidth;
8655 } else {
8656 leftWidth = primaryWidth;
8657 rightWidth = safeWidth;
8658 }
8659 }
8660
8661 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
8662
8663 return this;
8664 };
8665
8666 /**
8667 * Handle errors that occurred during accept or reject processes.
8668 *
8669 * @private
8670 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8671 */
8672 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8673 var i, len, $item, actions,
8674 items = [],
8675 abilities = {},
8676 recoverable = true,
8677 warning = false;
8678
8679 if ( errors instanceof OO.ui.Error ) {
8680 errors = [ errors ];
8681 }
8682
8683 for ( i = 0, len = errors.length; i < len; i++ ) {
8684 if ( !errors[ i ].isRecoverable() ) {
8685 recoverable = false;
8686 }
8687 if ( errors[ i ].isWarning() ) {
8688 warning = true;
8689 }
8690 $item = $( '<div>' )
8691 .addClass( 'oo-ui-processDialog-error' )
8692 .append( errors[ i ].getMessage() );
8693 items.push( $item[ 0 ] );
8694 }
8695 this.$errorItems = $( items );
8696 if ( recoverable ) {
8697 abilities[ this.currentAction ] = true;
8698 // Copy the flags from the first matching action
8699 actions = this.actions.get( { actions: this.currentAction } );
8700 if ( actions.length ) {
8701 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
8702 }
8703 } else {
8704 abilities[ this.currentAction ] = false;
8705 this.actions.setAbilities( abilities );
8706 }
8707 if ( warning ) {
8708 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8709 } else {
8710 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8711 }
8712 this.retryButton.toggle( recoverable );
8713 this.$errorsTitle.after( this.$errorItems );
8714 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8715 };
8716
8717 /**
8718 * Hide errors.
8719 *
8720 * @private
8721 */
8722 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8723 this.$errors.addClass( 'oo-ui-element-hidden' );
8724 if ( this.$errorItems ) {
8725 this.$errorItems.remove();
8726 this.$errorItems = null;
8727 }
8728 };
8729
8730 /**
8731 * @inheritdoc
8732 */
8733 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8734 // Parent method
8735 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
8736 .first( function () {
8737 // Make sure to hide errors
8738 this.hideErrors();
8739 this.fitOnOpen = false;
8740 }, this );
8741 };
8742
8743 /**
8744 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8745 * which is a widget that is specified by reference before any optional configuration settings.
8746 *
8747 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8748 *
8749 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8750 * A left-alignment is used for forms with many fields.
8751 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8752 * A right-alignment is used for long but familiar forms which users tab through,
8753 * verifying the current field with a quick glance at the label.
8754 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8755 * that users fill out from top to bottom.
8756 * - **inline**: The label is placed after the field-widget and aligned to the left.
8757 * An inline-alignment is best used with checkboxes or radio buttons.
8758 *
8759 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8760 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8761 *
8762 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8763 * @class
8764 * @extends OO.ui.Layout
8765 * @mixins OO.ui.mixin.LabelElement
8766 * @mixins OO.ui.mixin.TitledElement
8767 *
8768 * @constructor
8769 * @param {OO.ui.Widget} fieldWidget Field widget
8770 * @param {Object} [config] Configuration options
8771 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8772 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8773 * The array may contain strings or OO.ui.HtmlSnippet instances.
8774 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8775 * The array may contain strings or OO.ui.HtmlSnippet instances.
8776 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8777 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8778 * For important messages, you are advised to use `notices`, as they are always shown.
8779 *
8780 * @throws {Error} An error is thrown if no widget is specified
8781 */
8782 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8783 var hasInputWidget, div, i;
8784
8785 // Allow passing positional parameters inside the config object
8786 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8787 config = fieldWidget;
8788 fieldWidget = config.fieldWidget;
8789 }
8790
8791 // Make sure we have required constructor arguments
8792 if ( fieldWidget === undefined ) {
8793 throw new Error( 'Widget not found' );
8794 }
8795
8796 hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel;
8797
8798 // Configuration initialization
8799 config = $.extend( { align: 'left' }, config );
8800
8801 // Parent constructor
8802 OO.ui.FieldLayout.parent.call( this, config );
8803
8804 // Mixin constructors
8805 OO.ui.mixin.LabelElement.call( this, config );
8806 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8807
8808 // Properties
8809 this.fieldWidget = fieldWidget;
8810 this.errors = config.errors || [];
8811 this.notices = config.notices || [];
8812 this.$field = $( '<div>' );
8813 this.$messages = $( '<ul>' );
8814 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8815 this.align = null;
8816 if ( config.help ) {
8817 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8818 classes: [ 'oo-ui-fieldLayout-help' ],
8819 framed: false,
8820 icon: 'info'
8821 } );
8822
8823 div = $( '<div>' );
8824 if ( config.help instanceof OO.ui.HtmlSnippet ) {
8825 div.html( config.help.toString() );
8826 } else {
8827 div.text( config.help );
8828 }
8829 this.popupButtonWidget.getPopup().$body.append(
8830 div.addClass( 'oo-ui-fieldLayout-help-content' )
8831 );
8832 this.$help = this.popupButtonWidget.$element;
8833 } else {
8834 this.$help = $( [] );
8835 }
8836
8837 // Events
8838 if ( hasInputWidget ) {
8839 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8840 }
8841 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8842
8843 // Initialization
8844 this.$element
8845 .addClass( 'oo-ui-fieldLayout' )
8846 .append( this.$help, this.$body );
8847 if ( this.errors.length || this.notices.length ) {
8848 this.$element.append( this.$messages );
8849 }
8850 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8851 this.$messages.addClass( 'oo-ui-fieldLayout-messages' );
8852 this.$field
8853 .addClass( 'oo-ui-fieldLayout-field' )
8854 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8855 .append( this.fieldWidget.$element );
8856
8857 for ( i = 0; i < this.notices.length; i++ ) {
8858 this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) );
8859 }
8860 for ( i = 0; i < this.errors.length; i++ ) {
8861 this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) );
8862 }
8863
8864 this.setAlignment( config.align );
8865 };
8866
8867 /* Setup */
8868
8869 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8870 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement );
8871 OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement );
8872
8873 /* Methods */
8874
8875 /**
8876 * Handle field disable events.
8877 *
8878 * @private
8879 * @param {boolean} value Field is disabled
8880 */
8881 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8882 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8883 };
8884
8885 /**
8886 * Handle label mouse click events.
8887 *
8888 * @private
8889 * @param {jQuery.Event} e Mouse click event
8890 */
8891 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8892 this.fieldWidget.simulateLabelClick();
8893 return false;
8894 };
8895
8896 /**
8897 * Get the widget contained by the field.
8898 *
8899 * @return {OO.ui.Widget} Field widget
8900 */
8901 OO.ui.FieldLayout.prototype.getField = function () {
8902 return this.fieldWidget;
8903 };
8904
8905 /**
8906 * @param {string} kind 'error' or 'notice'
8907 * @param {string|OO.ui.HtmlSnippet} text
8908 * @return {jQuery}
8909 */
8910 OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) {
8911 var $listItem, $icon, message;
8912 $listItem = $( '<li>' );
8913 if ( kind === 'error' ) {
8914 $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element;
8915 } else if ( kind === 'notice' ) {
8916 $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element;
8917 } else {
8918 $icon = '';
8919 }
8920 message = new OO.ui.LabelWidget( { label: text } );
8921 $listItem
8922 .append( $icon, message.$element )
8923 .addClass( 'oo-ui-fieldLayout-messages-' + kind );
8924 return $listItem;
8925 };
8926
8927 /**
8928 * Set the field alignment mode.
8929 *
8930 * @private
8931 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8932 * @chainable
8933 */
8934 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8935 if ( value !== this.align ) {
8936 // Default to 'left'
8937 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8938 value = 'left';
8939 }
8940 // Reorder elements
8941 if ( value === 'inline' ) {
8942 this.$body.append( this.$field, this.$label );
8943 } else {
8944 this.$body.append( this.$label, this.$field );
8945 }
8946 // Set classes. The following classes can be used here:
8947 // * oo-ui-fieldLayout-align-left
8948 // * oo-ui-fieldLayout-align-right
8949 // * oo-ui-fieldLayout-align-top
8950 // * oo-ui-fieldLayout-align-inline
8951 if ( this.align ) {
8952 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8953 }
8954 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8955 this.align = value;
8956 }
8957
8958 return this;
8959 };
8960
8961 /**
8962 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8963 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8964 * is required and is specified before any optional configuration settings.
8965 *
8966 * Labels can be aligned in one of four ways:
8967 *
8968 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8969 * A left-alignment is used for forms with many fields.
8970 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8971 * A right-alignment is used for long but familiar forms which users tab through,
8972 * verifying the current field with a quick glance at the label.
8973 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8974 * that users fill out from top to bottom.
8975 * - **inline**: The label is placed after the field-widget and aligned to the left.
8976 * An inline-alignment is best used with checkboxes or radio buttons.
8977 *
8978 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8979 * text is specified.
8980 *
8981 * @example
8982 * // Example of an ActionFieldLayout
8983 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8984 * new OO.ui.TextInputWidget( {
8985 * placeholder: 'Field widget'
8986 * } ),
8987 * new OO.ui.ButtonWidget( {
8988 * label: 'Button'
8989 * } ),
8990 * {
8991 * label: 'An ActionFieldLayout. This label is aligned top',
8992 * align: 'top',
8993 * help: 'This is help text'
8994 * }
8995 * );
8996 *
8997 * $( 'body' ).append( actionFieldLayout.$element );
8998 *
8999 *
9000 * @class
9001 * @extends OO.ui.FieldLayout
9002 *
9003 * @constructor
9004 * @param {OO.ui.Widget} fieldWidget Field widget
9005 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9006 */
9007 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
9008 // Allow passing positional parameters inside the config object
9009 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
9010 config = fieldWidget;
9011 fieldWidget = config.fieldWidget;
9012 buttonWidget = config.buttonWidget;
9013 }
9014
9015 // Parent constructor
9016 OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config );
9017
9018 // Properties
9019 this.buttonWidget = buttonWidget;
9020 this.$button = $( '<div>' );
9021 this.$input = $( '<div>' );
9022
9023 // Initialization
9024 this.$element
9025 .addClass( 'oo-ui-actionFieldLayout' );
9026 this.$button
9027 .addClass( 'oo-ui-actionFieldLayout-button' )
9028 .append( this.buttonWidget.$element );
9029 this.$input
9030 .addClass( 'oo-ui-actionFieldLayout-input' )
9031 .append( this.fieldWidget.$element );
9032 this.$field
9033 .append( this.$input, this.$button );
9034 };
9035
9036 /* Setup */
9037
9038 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
9039
9040 /**
9041 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9042 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9043 * configured with a label as well. For more information and examples,
9044 * please see the [OOjs UI documentation on MediaWiki][1].
9045 *
9046 * @example
9047 * // Example of a fieldset layout
9048 * var input1 = new OO.ui.TextInputWidget( {
9049 * placeholder: 'A text input field'
9050 * } );
9051 *
9052 * var input2 = new OO.ui.TextInputWidget( {
9053 * placeholder: 'A text input field'
9054 * } );
9055 *
9056 * var fieldset = new OO.ui.FieldsetLayout( {
9057 * label: 'Example of a fieldset layout'
9058 * } );
9059 *
9060 * fieldset.addItems( [
9061 * new OO.ui.FieldLayout( input1, {
9062 * label: 'Field One'
9063 * } ),
9064 * new OO.ui.FieldLayout( input2, {
9065 * label: 'Field Two'
9066 * } )
9067 * ] );
9068 * $( 'body' ).append( fieldset.$element );
9069 *
9070 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9071 *
9072 * @class
9073 * @extends OO.ui.Layout
9074 * @mixins OO.ui.mixin.IconElement
9075 * @mixins OO.ui.mixin.LabelElement
9076 * @mixins OO.ui.mixin.GroupElement
9077 *
9078 * @constructor
9079 * @param {Object} [config] Configuration options
9080 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9081 */
9082 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
9083 // Configuration initialization
9084 config = config || {};
9085
9086 // Parent constructor
9087 OO.ui.FieldsetLayout.parent.call( this, config );
9088
9089 // Mixin constructors
9090 OO.ui.mixin.IconElement.call( this, config );
9091 OO.ui.mixin.LabelElement.call( this, config );
9092 OO.ui.mixin.GroupElement.call( this, config );
9093
9094 if ( config.help ) {
9095 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
9096 classes: [ 'oo-ui-fieldsetLayout-help' ],
9097 framed: false,
9098 icon: 'info'
9099 } );
9100
9101 this.popupButtonWidget.getPopup().$body.append(
9102 $( '<div>' )
9103 .text( config.help )
9104 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9105 );
9106 this.$help = this.popupButtonWidget.$element;
9107 } else {
9108 this.$help = $( [] );
9109 }
9110
9111 // Initialization
9112 this.$element
9113 .addClass( 'oo-ui-fieldsetLayout' )
9114 .prepend( this.$help, this.$icon, this.$label, this.$group );
9115 if ( Array.isArray( config.items ) ) {
9116 this.addItems( config.items );
9117 }
9118 };
9119
9120 /* Setup */
9121
9122 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
9123 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement );
9124 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement );
9125 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement );
9126
9127 /**
9128 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9129 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9130 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9131 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9132 *
9133 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9134 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9135 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9136 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9137 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9138 * often have simplified APIs to match the capabilities of HTML forms.
9139 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9140 *
9141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9142 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9143 *
9144 * @example
9145 * // Example of a form layout that wraps a fieldset layout
9146 * var input1 = new OO.ui.TextInputWidget( {
9147 * placeholder: 'Username'
9148 * } );
9149 * var input2 = new OO.ui.TextInputWidget( {
9150 * placeholder: 'Password',
9151 * type: 'password'
9152 * } );
9153 * var submit = new OO.ui.ButtonInputWidget( {
9154 * label: 'Submit'
9155 * } );
9156 *
9157 * var fieldset = new OO.ui.FieldsetLayout( {
9158 * label: 'A form layout'
9159 * } );
9160 * fieldset.addItems( [
9161 * new OO.ui.FieldLayout( input1, {
9162 * label: 'Username',
9163 * align: 'top'
9164 * } ),
9165 * new OO.ui.FieldLayout( input2, {
9166 * label: 'Password',
9167 * align: 'top'
9168 * } ),
9169 * new OO.ui.FieldLayout( submit )
9170 * ] );
9171 * var form = new OO.ui.FormLayout( {
9172 * items: [ fieldset ],
9173 * action: '/api/formhandler',
9174 * method: 'get'
9175 * } )
9176 * $( 'body' ).append( form.$element );
9177 *
9178 * @class
9179 * @extends OO.ui.Layout
9180 * @mixins OO.ui.mixin.GroupElement
9181 *
9182 * @constructor
9183 * @param {Object} [config] Configuration options
9184 * @cfg {string} [method] HTML form `method` attribute
9185 * @cfg {string} [action] HTML form `action` attribute
9186 * @cfg {string} [enctype] HTML form `enctype` attribute
9187 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9188 */
9189 OO.ui.FormLayout = function OoUiFormLayout( config ) {
9190 // Configuration initialization
9191 config = config || {};
9192
9193 // Parent constructor
9194 OO.ui.FormLayout.parent.call( this, config );
9195
9196 // Mixin constructors
9197 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9198
9199 // Events
9200 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
9201
9202 // Make sure the action is safe
9203 if ( config.action !== undefined && !OO.ui.isSafeUrl( config.action ) ) {
9204 throw new Error( 'Potentially unsafe action provided: ' + config.action );
9205 }
9206
9207 // Initialization
9208 this.$element
9209 .addClass( 'oo-ui-formLayout' )
9210 .attr( {
9211 method: config.method,
9212 action: config.action,
9213 enctype: config.enctype
9214 } );
9215 if ( Array.isArray( config.items ) ) {
9216 this.addItems( config.items );
9217 }
9218 };
9219
9220 /* Setup */
9221
9222 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
9223 OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement );
9224
9225 /* Events */
9226
9227 /**
9228 * A 'submit' event is emitted when the form is submitted.
9229 *
9230 * @event submit
9231 */
9232
9233 /* Static Properties */
9234
9235 OO.ui.FormLayout.static.tagName = 'form';
9236
9237 /* Methods */
9238
9239 /**
9240 * Handle form submit events.
9241 *
9242 * @private
9243 * @param {jQuery.Event} e Submit event
9244 * @fires submit
9245 */
9246 OO.ui.FormLayout.prototype.onFormSubmit = function () {
9247 if ( this.emit( 'submit' ) ) {
9248 return false;
9249 }
9250 };
9251
9252 /**
9253 * 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)
9254 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9255 *
9256 * @example
9257 * var menuLayout = new OO.ui.MenuLayout( {
9258 * position: 'top'
9259 * } ),
9260 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9261 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9262 * select = new OO.ui.SelectWidget( {
9263 * items: [
9264 * new OO.ui.OptionWidget( {
9265 * data: 'before',
9266 * label: 'Before',
9267 * } ),
9268 * new OO.ui.OptionWidget( {
9269 * data: 'after',
9270 * label: 'After',
9271 * } ),
9272 * new OO.ui.OptionWidget( {
9273 * data: 'top',
9274 * label: 'Top',
9275 * } ),
9276 * new OO.ui.OptionWidget( {
9277 * data: 'bottom',
9278 * label: 'Bottom',
9279 * } )
9280 * ]
9281 * } ).on( 'select', function ( item ) {
9282 * menuLayout.setMenuPosition( item.getData() );
9283 * } );
9284 *
9285 * menuLayout.$menu.append(
9286 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9287 * );
9288 * menuLayout.$content.append(
9289 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9290 * );
9291 * $( 'body' ).append( menuLayout.$element );
9292 *
9293 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9294 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9295 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9296 * may be omitted.
9297 *
9298 * .oo-ui-menuLayout-menu {
9299 * height: 200px;
9300 * width: 200px;
9301 * }
9302 * .oo-ui-menuLayout-content {
9303 * top: 200px;
9304 * left: 200px;
9305 * right: 200px;
9306 * bottom: 200px;
9307 * }
9308 *
9309 * @class
9310 * @extends OO.ui.Layout
9311 *
9312 * @constructor
9313 * @param {Object} [config] Configuration options
9314 * @cfg {boolean} [showMenu=true] Show menu
9315 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9316 */
9317 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
9318 // Configuration initialization
9319 config = $.extend( {
9320 showMenu: true,
9321 menuPosition: 'before'
9322 }, config );
9323
9324 // Parent constructor
9325 OO.ui.MenuLayout.parent.call( this, config );
9326
9327 /**
9328 * Menu DOM node
9329 *
9330 * @property {jQuery}
9331 */
9332 this.$menu = $( '<div>' );
9333 /**
9334 * Content DOM node
9335 *
9336 * @property {jQuery}
9337 */
9338 this.$content = $( '<div>' );
9339
9340 // Initialization
9341 this.$menu
9342 .addClass( 'oo-ui-menuLayout-menu' );
9343 this.$content.addClass( 'oo-ui-menuLayout-content' );
9344 this.$element
9345 .addClass( 'oo-ui-menuLayout' )
9346 .append( this.$content, this.$menu );
9347 this.setMenuPosition( config.menuPosition );
9348 this.toggleMenu( config.showMenu );
9349 };
9350
9351 /* Setup */
9352
9353 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
9354
9355 /* Methods */
9356
9357 /**
9358 * Toggle menu.
9359 *
9360 * @param {boolean} showMenu Show menu, omit to toggle
9361 * @chainable
9362 */
9363 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
9364 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
9365
9366 if ( this.showMenu !== showMenu ) {
9367 this.showMenu = showMenu;
9368 this.$element
9369 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
9370 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
9371 }
9372
9373 return this;
9374 };
9375
9376 /**
9377 * Check if menu is visible
9378 *
9379 * @return {boolean} Menu is visible
9380 */
9381 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
9382 return this.showMenu;
9383 };
9384
9385 /**
9386 * Set menu position.
9387 *
9388 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9389 * @throws {Error} If position value is not supported
9390 * @chainable
9391 */
9392 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
9393 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
9394 this.menuPosition = position;
9395 this.$element.addClass( 'oo-ui-menuLayout-' + position );
9396
9397 return this;
9398 };
9399
9400 /**
9401 * Get menu position.
9402 *
9403 * @return {string} Menu position
9404 */
9405 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
9406 return this.menuPosition;
9407 };
9408
9409 /**
9410 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9411 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9412 * through the pages and select which one to display. By default, only one page is
9413 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9414 * the booklet layout automatically focuses on the first focusable element, unless the
9415 * default setting is changed. Optionally, booklets can be configured to show
9416 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9417 *
9418 * @example
9419 * // Example of a BookletLayout that contains two PageLayouts.
9420 *
9421 * function PageOneLayout( name, config ) {
9422 * PageOneLayout.parent.call( this, name, config );
9423 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9424 * }
9425 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9426 * PageOneLayout.prototype.setupOutlineItem = function () {
9427 * this.outlineItem.setLabel( 'Page One' );
9428 * };
9429 *
9430 * function PageTwoLayout( name, config ) {
9431 * PageTwoLayout.parent.call( this, name, config );
9432 * this.$element.append( '<p>Second page</p>' );
9433 * }
9434 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9435 * PageTwoLayout.prototype.setupOutlineItem = function () {
9436 * this.outlineItem.setLabel( 'Page Two' );
9437 * };
9438 *
9439 * var page1 = new PageOneLayout( 'one' ),
9440 * page2 = new PageTwoLayout( 'two' );
9441 *
9442 * var booklet = new OO.ui.BookletLayout( {
9443 * outlined: true
9444 * } );
9445 *
9446 * booklet.addPages ( [ page1, page2 ] );
9447 * $( 'body' ).append( booklet.$element );
9448 *
9449 * @class
9450 * @extends OO.ui.MenuLayout
9451 *
9452 * @constructor
9453 * @param {Object} [config] Configuration options
9454 * @cfg {boolean} [continuous=false] Show all pages, one after another
9455 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9456 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9457 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9458 */
9459 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
9460 // Configuration initialization
9461 config = config || {};
9462
9463 // Parent constructor
9464 OO.ui.BookletLayout.parent.call( this, config );
9465
9466 // Properties
9467 this.currentPageName = null;
9468 this.pages = {};
9469 this.ignoreFocus = false;
9470 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9471 this.$content.append( this.stackLayout.$element );
9472 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9473 this.outlineVisible = false;
9474 this.outlined = !!config.outlined;
9475 if ( this.outlined ) {
9476 this.editable = !!config.editable;
9477 this.outlineControlsWidget = null;
9478 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
9479 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
9480 this.$menu.append( this.outlinePanel.$element );
9481 this.outlineVisible = true;
9482 if ( this.editable ) {
9483 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
9484 this.outlineSelectWidget
9485 );
9486 }
9487 }
9488 this.toggleMenu( this.outlined );
9489
9490 // Events
9491 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9492 if ( this.outlined ) {
9493 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
9494 }
9495 if ( this.autoFocus ) {
9496 // Event 'focus' does not bubble, but 'focusin' does
9497 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9498 }
9499
9500 // Initialization
9501 this.$element.addClass( 'oo-ui-bookletLayout' );
9502 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
9503 if ( this.outlined ) {
9504 this.outlinePanel.$element
9505 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9506 .append( this.outlineSelectWidget.$element );
9507 if ( this.editable ) {
9508 this.outlinePanel.$element
9509 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9510 .append( this.outlineControlsWidget.$element );
9511 }
9512 }
9513 };
9514
9515 /* Setup */
9516
9517 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
9518
9519 /* Events */
9520
9521 /**
9522 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9523 * @event set
9524 * @param {OO.ui.PageLayout} page Current page
9525 */
9526
9527 /**
9528 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9529 *
9530 * @event add
9531 * @param {OO.ui.PageLayout[]} page Added pages
9532 * @param {number} index Index pages were added at
9533 */
9534
9535 /**
9536 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9537 * {@link #removePages removed} from the booklet.
9538 *
9539 * @event remove
9540 * @param {OO.ui.PageLayout[]} pages Removed pages
9541 */
9542
9543 /* Methods */
9544
9545 /**
9546 * Handle stack layout focus.
9547 *
9548 * @private
9549 * @param {jQuery.Event} e Focusin event
9550 */
9551 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
9552 var name, $target;
9553
9554 // Find the page that an element was focused within
9555 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
9556 for ( name in this.pages ) {
9557 // Check for page match, exclude current page to find only page changes
9558 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
9559 this.setPage( name );
9560 break;
9561 }
9562 }
9563 };
9564
9565 /**
9566 * Handle stack layout set events.
9567 *
9568 * @private
9569 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9570 */
9571 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
9572 var layout = this;
9573 if ( page ) {
9574 page.scrollElementIntoView( { complete: function () {
9575 if ( layout.autoFocus ) {
9576 layout.focus();
9577 }
9578 } } );
9579 }
9580 };
9581
9582 /**
9583 * Focus the first input in the current page.
9584 *
9585 * If no page is selected, the first selectable page will be selected.
9586 * If the focus is already in an element on the current page, nothing will happen.
9587 * @param {number} [itemIndex] A specific item to focus on
9588 */
9589 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
9590 var $input, page,
9591 items = this.stackLayout.getItems();
9592
9593 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9594 page = items[ itemIndex ];
9595 } else {
9596 page = this.stackLayout.getCurrentItem();
9597 }
9598
9599 if ( !page && this.outlined ) {
9600 this.selectFirstSelectablePage();
9601 page = this.stackLayout.getCurrentItem();
9602 }
9603 if ( !page ) {
9604 return;
9605 }
9606 // Only change the focus if is not already in the current page
9607 if ( !page.$element.find( ':focus' ).length ) {
9608 $input = page.$element.find( ':input:first' );
9609 if ( $input.length ) {
9610 $input[ 0 ].focus();
9611 }
9612 }
9613 };
9614
9615 /**
9616 * Find the first focusable input in the booklet layout and focus
9617 * on it.
9618 */
9619 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
9620 var i, len,
9621 found = false,
9622 items = this.stackLayout.getItems(),
9623 checkAndFocus = function () {
9624 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9625 $( this ).focus();
9626 found = true;
9627 return false;
9628 }
9629 };
9630
9631 for ( i = 0, len = items.length; i < len; i++ ) {
9632 if ( found ) {
9633 break;
9634 }
9635 // Find all potentially focusable elements in the item
9636 // and check if they are focusable
9637 items[ i ].$element
9638 .find( 'input, select, textarea, button, object' )
9639 /* jshint loopfunc:true */
9640 .each( checkAndFocus );
9641 }
9642 };
9643
9644 /**
9645 * Handle outline widget select events.
9646 *
9647 * @private
9648 * @param {OO.ui.OptionWidget|null} item Selected item
9649 */
9650 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9651 if ( item ) {
9652 this.setPage( item.getData() );
9653 }
9654 };
9655
9656 /**
9657 * Check if booklet has an outline.
9658 *
9659 * @return {boolean} Booklet has an outline
9660 */
9661 OO.ui.BookletLayout.prototype.isOutlined = function () {
9662 return this.outlined;
9663 };
9664
9665 /**
9666 * Check if booklet has editing controls.
9667 *
9668 * @return {boolean} Booklet is editable
9669 */
9670 OO.ui.BookletLayout.prototype.isEditable = function () {
9671 return this.editable;
9672 };
9673
9674 /**
9675 * Check if booklet has a visible outline.
9676 *
9677 * @return {boolean} Outline is visible
9678 */
9679 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9680 return this.outlined && this.outlineVisible;
9681 };
9682
9683 /**
9684 * Hide or show the outline.
9685 *
9686 * @param {boolean} [show] Show outline, omit to invert current state
9687 * @chainable
9688 */
9689 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9690 if ( this.outlined ) {
9691 show = show === undefined ? !this.outlineVisible : !!show;
9692 this.outlineVisible = show;
9693 this.toggleMenu( show );
9694 }
9695
9696 return this;
9697 };
9698
9699 /**
9700 * Get the page closest to the specified page.
9701 *
9702 * @param {OO.ui.PageLayout} page Page to use as a reference point
9703 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9704 */
9705 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9706 var next, prev, level,
9707 pages = this.stackLayout.getItems(),
9708 index = pages.indexOf( page );
9709
9710 if ( index !== -1 ) {
9711 next = pages[ index + 1 ];
9712 prev = pages[ index - 1 ];
9713 // Prefer adjacent pages at the same level
9714 if ( this.outlined ) {
9715 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9716 if (
9717 prev &&
9718 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9719 ) {
9720 return prev;
9721 }
9722 if (
9723 next &&
9724 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9725 ) {
9726 return next;
9727 }
9728 }
9729 }
9730 return prev || next || null;
9731 };
9732
9733 /**
9734 * Get the outline widget.
9735 *
9736 * If the booklet is not outlined, the method will return `null`.
9737 *
9738 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9739 */
9740 OO.ui.BookletLayout.prototype.getOutline = function () {
9741 return this.outlineSelectWidget;
9742 };
9743
9744 /**
9745 * Get the outline controls widget.
9746 *
9747 * If the outline is not editable, the method will return `null`.
9748 *
9749 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9750 */
9751 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9752 return this.outlineControlsWidget;
9753 };
9754
9755 /**
9756 * Get a page by its symbolic name.
9757 *
9758 * @param {string} name Symbolic name of page
9759 * @return {OO.ui.PageLayout|undefined} Page, if found
9760 */
9761 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9762 return this.pages[ name ];
9763 };
9764
9765 /**
9766 * Get the current page.
9767 *
9768 * @return {OO.ui.PageLayout|undefined} Current page, if found
9769 */
9770 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9771 var name = this.getCurrentPageName();
9772 return name ? this.getPage( name ) : undefined;
9773 };
9774
9775 /**
9776 * Get the symbolic name of the current page.
9777 *
9778 * @return {string|null} Symbolic name of the current page
9779 */
9780 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9781 return this.currentPageName;
9782 };
9783
9784 /**
9785 * Add pages to the booklet layout
9786 *
9787 * When pages are added with the same names as existing pages, the existing pages will be
9788 * automatically removed before the new pages are added.
9789 *
9790 * @param {OO.ui.PageLayout[]} pages Pages to add
9791 * @param {number} index Index of the insertion point
9792 * @fires add
9793 * @chainable
9794 */
9795 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9796 var i, len, name, page, item, currentIndex,
9797 stackLayoutPages = this.stackLayout.getItems(),
9798 remove = [],
9799 items = [];
9800
9801 // Remove pages with same names
9802 for ( i = 0, len = pages.length; i < len; i++ ) {
9803 page = pages[ i ];
9804 name = page.getName();
9805
9806 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9807 // Correct the insertion index
9808 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
9809 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9810 index--;
9811 }
9812 remove.push( this.pages[ name ] );
9813 }
9814 }
9815 if ( remove.length ) {
9816 this.removePages( remove );
9817 }
9818
9819 // Add new pages
9820 for ( i = 0, len = pages.length; i < len; i++ ) {
9821 page = pages[ i ];
9822 name = page.getName();
9823 this.pages[ page.getName() ] = page;
9824 if ( this.outlined ) {
9825 item = new OO.ui.OutlineOptionWidget( { data: name } );
9826 page.setOutlineItem( item );
9827 items.push( item );
9828 }
9829 }
9830
9831 if ( this.outlined && items.length ) {
9832 this.outlineSelectWidget.addItems( items, index );
9833 this.selectFirstSelectablePage();
9834 }
9835 this.stackLayout.addItems( pages, index );
9836 this.emit( 'add', pages, index );
9837
9838 return this;
9839 };
9840
9841 /**
9842 * Remove the specified pages from the booklet layout.
9843 *
9844 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9845 *
9846 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9847 * @fires remove
9848 * @chainable
9849 */
9850 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9851 var i, len, name, page,
9852 items = [];
9853
9854 for ( i = 0, len = pages.length; i < len; i++ ) {
9855 page = pages[ i ];
9856 name = page.getName();
9857 delete this.pages[ name ];
9858 if ( this.outlined ) {
9859 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9860 page.setOutlineItem( null );
9861 }
9862 }
9863 if ( this.outlined && items.length ) {
9864 this.outlineSelectWidget.removeItems( items );
9865 this.selectFirstSelectablePage();
9866 }
9867 this.stackLayout.removeItems( pages );
9868 this.emit( 'remove', pages );
9869
9870 return this;
9871 };
9872
9873 /**
9874 * Clear all pages from the booklet layout.
9875 *
9876 * To remove only a subset of pages from the booklet, use the #removePages method.
9877 *
9878 * @fires remove
9879 * @chainable
9880 */
9881 OO.ui.BookletLayout.prototype.clearPages = function () {
9882 var i, len,
9883 pages = this.stackLayout.getItems();
9884
9885 this.pages = {};
9886 this.currentPageName = null;
9887 if ( this.outlined ) {
9888 this.outlineSelectWidget.clearItems();
9889 for ( i = 0, len = pages.length; i < len; i++ ) {
9890 pages[ i ].setOutlineItem( null );
9891 }
9892 }
9893 this.stackLayout.clearItems();
9894
9895 this.emit( 'remove', pages );
9896
9897 return this;
9898 };
9899
9900 /**
9901 * Set the current page by symbolic name.
9902 *
9903 * @fires set
9904 * @param {string} name Symbolic name of page
9905 */
9906 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9907 var selectedItem,
9908 $focused,
9909 page = this.pages[ name ];
9910
9911 if ( name !== this.currentPageName ) {
9912 if ( this.outlined ) {
9913 selectedItem = this.outlineSelectWidget.getSelectedItem();
9914 if ( selectedItem && selectedItem.getData() !== name ) {
9915 this.outlineSelectWidget.selectItemByData( name );
9916 }
9917 }
9918 if ( page ) {
9919 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9920 this.pages[ this.currentPageName ].setActive( false );
9921 // Blur anything focused if the next page doesn't have anything focusable - this
9922 // is not needed if the next page has something focusable because once it is focused
9923 // this blur happens automatically
9924 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9925 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9926 if ( $focused.length ) {
9927 $focused[ 0 ].blur();
9928 }
9929 }
9930 }
9931 this.currentPageName = name;
9932 this.stackLayout.setItem( page );
9933 page.setActive( true );
9934 this.emit( 'set', page );
9935 }
9936 }
9937 };
9938
9939 /**
9940 * Select the first selectable page.
9941 *
9942 * @chainable
9943 */
9944 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9945 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9946 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9947 }
9948
9949 return this;
9950 };
9951
9952 /**
9953 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9954 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9955 * select which one to display. By default, only one card is displayed at a time. When a user
9956 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9957 * unless the default setting is changed.
9958 *
9959 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9960 *
9961 * @example
9962 * // Example of a IndexLayout that contains two CardLayouts.
9963 *
9964 * function CardOneLayout( name, config ) {
9965 * CardOneLayout.parent.call( this, name, config );
9966 * this.$element.append( '<p>First card</p>' );
9967 * }
9968 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9969 * CardOneLayout.prototype.setupTabItem = function () {
9970 * this.tabItem.setLabel( 'Card One' );
9971 * };
9972 *
9973 * function CardTwoLayout( name, config ) {
9974 * CardTwoLayout.parent.call( this, name, config );
9975 * this.$element.append( '<p>Second card</p>' );
9976 * }
9977 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9978 * CardTwoLayout.prototype.setupTabItem = function () {
9979 * this.tabItem.setLabel( 'Card Two' );
9980 * };
9981 *
9982 * var card1 = new CardOneLayout( 'one' ),
9983 * card2 = new CardTwoLayout( 'two' );
9984 *
9985 * var index = new OO.ui.IndexLayout();
9986 *
9987 * index.addCards ( [ card1, card2 ] );
9988 * $( 'body' ).append( index.$element );
9989 *
9990 * @class
9991 * @extends OO.ui.MenuLayout
9992 *
9993 * @constructor
9994 * @param {Object} [config] Configuration options
9995 * @cfg {boolean} [continuous=false] Show all cards, one after another
9996 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9997 */
9998 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
9999 // Configuration initialization
10000 config = $.extend( {}, config, { menuPosition: 'top' } );
10001
10002 // Parent constructor
10003 OO.ui.IndexLayout.parent.call( this, config );
10004
10005 // Properties
10006 this.currentCardName = null;
10007 this.cards = {};
10008 this.ignoreFocus = false;
10009 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
10010 this.$content.append( this.stackLayout.$element );
10011 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
10012
10013 this.tabSelectWidget = new OO.ui.TabSelectWidget();
10014 this.tabPanel = new OO.ui.PanelLayout();
10015 this.$menu.append( this.tabPanel.$element );
10016
10017 this.toggleMenu( true );
10018
10019 // Events
10020 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
10021 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
10022 if ( this.autoFocus ) {
10023 // Event 'focus' does not bubble, but 'focusin' does
10024 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
10025 }
10026
10027 // Initialization
10028 this.$element.addClass( 'oo-ui-indexLayout' );
10029 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
10030 this.tabPanel.$element
10031 .addClass( 'oo-ui-indexLayout-tabPanel' )
10032 .append( this.tabSelectWidget.$element );
10033 };
10034
10035 /* Setup */
10036
10037 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
10038
10039 /* Events */
10040
10041 /**
10042 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10043 * @event set
10044 * @param {OO.ui.CardLayout} card Current card
10045 */
10046
10047 /**
10048 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10049 *
10050 * @event add
10051 * @param {OO.ui.CardLayout[]} card Added cards
10052 * @param {number} index Index cards were added at
10053 */
10054
10055 /**
10056 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10057 * {@link #removeCards removed} from the index.
10058 *
10059 * @event remove
10060 * @param {OO.ui.CardLayout[]} cards Removed cards
10061 */
10062
10063 /* Methods */
10064
10065 /**
10066 * Handle stack layout focus.
10067 *
10068 * @private
10069 * @param {jQuery.Event} e Focusin event
10070 */
10071 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
10072 var name, $target;
10073
10074 // Find the card that an element was focused within
10075 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
10076 for ( name in this.cards ) {
10077 // Check for card match, exclude current card to find only card changes
10078 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
10079 this.setCard( name );
10080 break;
10081 }
10082 }
10083 };
10084
10085 /**
10086 * Handle stack layout set events.
10087 *
10088 * @private
10089 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10090 */
10091 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
10092 var layout = this;
10093 if ( card ) {
10094 card.scrollElementIntoView( { complete: function () {
10095 if ( layout.autoFocus ) {
10096 layout.focus();
10097 }
10098 } } );
10099 }
10100 };
10101
10102 /**
10103 * Focus the first input in the current card.
10104 *
10105 * If no card is selected, the first selectable card will be selected.
10106 * If the focus is already in an element on the current card, nothing will happen.
10107 * @param {number} [itemIndex] A specific item to focus on
10108 */
10109 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
10110 var $input, card,
10111 items = this.stackLayout.getItems();
10112
10113 if ( itemIndex !== undefined && items[ itemIndex ] ) {
10114 card = items[ itemIndex ];
10115 } else {
10116 card = this.stackLayout.getCurrentItem();
10117 }
10118
10119 if ( !card ) {
10120 this.selectFirstSelectableCard();
10121 card = this.stackLayout.getCurrentItem();
10122 }
10123 if ( !card ) {
10124 return;
10125 }
10126 // Only change the focus if is not already in the current card
10127 if ( !card.$element.find( ':focus' ).length ) {
10128 $input = card.$element.find( ':input:first' );
10129 if ( $input.length ) {
10130 $input[ 0 ].focus();
10131 }
10132 }
10133 };
10134
10135 /**
10136 * Find the first focusable input in the index layout and focus
10137 * on it.
10138 */
10139 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
10140 var i, len,
10141 found = false,
10142 items = this.stackLayout.getItems(),
10143 checkAndFocus = function () {
10144 if ( OO.ui.isFocusableElement( $( this ) ) ) {
10145 $( this ).focus();
10146 found = true;
10147 return false;
10148 }
10149 };
10150
10151 for ( i = 0, len = items.length; i < len; i++ ) {
10152 if ( found ) {
10153 break;
10154 }
10155 // Find all potentially focusable elements in the item
10156 // and check if they are focusable
10157 items[ i ].$element
10158 .find( 'input, select, textarea, button, object' )
10159 .each( checkAndFocus );
10160 }
10161 };
10162
10163 /**
10164 * Handle tab widget select events.
10165 *
10166 * @private
10167 * @param {OO.ui.OptionWidget|null} item Selected item
10168 */
10169 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
10170 if ( item ) {
10171 this.setCard( item.getData() );
10172 }
10173 };
10174
10175 /**
10176 * Get the card closest to the specified card.
10177 *
10178 * @param {OO.ui.CardLayout} card Card to use as a reference point
10179 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10180 */
10181 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
10182 var next, prev, level,
10183 cards = this.stackLayout.getItems(),
10184 index = cards.indexOf( card );
10185
10186 if ( index !== -1 ) {
10187 next = cards[ index + 1 ];
10188 prev = cards[ index - 1 ];
10189 // Prefer adjacent cards at the same level
10190 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
10191 if (
10192 prev &&
10193 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
10194 ) {
10195 return prev;
10196 }
10197 if (
10198 next &&
10199 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
10200 ) {
10201 return next;
10202 }
10203 }
10204 return prev || next || null;
10205 };
10206
10207 /**
10208 * Get the tabs widget.
10209 *
10210 * @return {OO.ui.TabSelectWidget} Tabs widget
10211 */
10212 OO.ui.IndexLayout.prototype.getTabs = function () {
10213 return this.tabSelectWidget;
10214 };
10215
10216 /**
10217 * Get a card by its symbolic name.
10218 *
10219 * @param {string} name Symbolic name of card
10220 * @return {OO.ui.CardLayout|undefined} Card, if found
10221 */
10222 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
10223 return this.cards[ name ];
10224 };
10225
10226 /**
10227 * Get the current card.
10228 *
10229 * @return {OO.ui.CardLayout|undefined} Current card, if found
10230 */
10231 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
10232 var name = this.getCurrentCardName();
10233 return name ? this.getCard( name ) : undefined;
10234 };
10235
10236 /**
10237 * Get the symbolic name of the current card.
10238 *
10239 * @return {string|null} Symbolic name of the current card
10240 */
10241 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
10242 return this.currentCardName;
10243 };
10244
10245 /**
10246 * Add cards to the index layout
10247 *
10248 * When cards are added with the same names as existing cards, the existing cards will be
10249 * automatically removed before the new cards are added.
10250 *
10251 * @param {OO.ui.CardLayout[]} cards Cards to add
10252 * @param {number} index Index of the insertion point
10253 * @fires add
10254 * @chainable
10255 */
10256 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
10257 var i, len, name, card, item, currentIndex,
10258 stackLayoutCards = this.stackLayout.getItems(),
10259 remove = [],
10260 items = [];
10261
10262 // Remove cards with same names
10263 for ( i = 0, len = cards.length; i < len; i++ ) {
10264 card = cards[ i ];
10265 name = card.getName();
10266
10267 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
10268 // Correct the insertion index
10269 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
10270 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
10271 index--;
10272 }
10273 remove.push( this.cards[ name ] );
10274 }
10275 }
10276 if ( remove.length ) {
10277 this.removeCards( remove );
10278 }
10279
10280 // Add new cards
10281 for ( i = 0, len = cards.length; i < len; i++ ) {
10282 card = cards[ i ];
10283 name = card.getName();
10284 this.cards[ card.getName() ] = card;
10285 item = new OO.ui.TabOptionWidget( { data: name } );
10286 card.setTabItem( item );
10287 items.push( item );
10288 }
10289
10290 if ( items.length ) {
10291 this.tabSelectWidget.addItems( items, index );
10292 this.selectFirstSelectableCard();
10293 }
10294 this.stackLayout.addItems( cards, index );
10295 this.emit( 'add', cards, index );
10296
10297 return this;
10298 };
10299
10300 /**
10301 * Remove the specified cards from the index layout.
10302 *
10303 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10304 *
10305 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10306 * @fires remove
10307 * @chainable
10308 */
10309 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
10310 var i, len, name, card,
10311 items = [];
10312
10313 for ( i = 0, len = cards.length; i < len; i++ ) {
10314 card = cards[ i ];
10315 name = card.getName();
10316 delete this.cards[ name ];
10317 items.push( this.tabSelectWidget.getItemFromData( name ) );
10318 card.setTabItem( null );
10319 }
10320 if ( items.length ) {
10321 this.tabSelectWidget.removeItems( items );
10322 this.selectFirstSelectableCard();
10323 }
10324 this.stackLayout.removeItems( cards );
10325 this.emit( 'remove', cards );
10326
10327 return this;
10328 };
10329
10330 /**
10331 * Clear all cards from the index layout.
10332 *
10333 * To remove only a subset of cards from the index, use the #removeCards method.
10334 *
10335 * @fires remove
10336 * @chainable
10337 */
10338 OO.ui.IndexLayout.prototype.clearCards = function () {
10339 var i, len,
10340 cards = this.stackLayout.getItems();
10341
10342 this.cards = {};
10343 this.currentCardName = null;
10344 this.tabSelectWidget.clearItems();
10345 for ( i = 0, len = cards.length; i < len; i++ ) {
10346 cards[ i ].setTabItem( null );
10347 }
10348 this.stackLayout.clearItems();
10349
10350 this.emit( 'remove', cards );
10351
10352 return this;
10353 };
10354
10355 /**
10356 * Set the current card by symbolic name.
10357 *
10358 * @fires set
10359 * @param {string} name Symbolic name of card
10360 */
10361 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
10362 var selectedItem,
10363 $focused,
10364 card = this.cards[ name ];
10365
10366 if ( name !== this.currentCardName ) {
10367 selectedItem = this.tabSelectWidget.getSelectedItem();
10368 if ( selectedItem && selectedItem.getData() !== name ) {
10369 this.tabSelectWidget.selectItemByData( name );
10370 }
10371 if ( card ) {
10372 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
10373 this.cards[ this.currentCardName ].setActive( false );
10374 // Blur anything focused if the next card doesn't have anything focusable - this
10375 // is not needed if the next card has something focusable because once it is focused
10376 // this blur happens automatically
10377 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
10378 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
10379 if ( $focused.length ) {
10380 $focused[ 0 ].blur();
10381 }
10382 }
10383 }
10384 this.currentCardName = name;
10385 this.stackLayout.setItem( card );
10386 card.setActive( true );
10387 this.emit( 'set', card );
10388 }
10389 }
10390 };
10391
10392 /**
10393 * Select the first selectable card.
10394 *
10395 * @chainable
10396 */
10397 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
10398 if ( !this.tabSelectWidget.getSelectedItem() ) {
10399 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
10400 }
10401
10402 return this;
10403 };
10404
10405 /**
10406 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10407 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10408 *
10409 * @example
10410 * // Example of a panel layout
10411 * var panel = new OO.ui.PanelLayout( {
10412 * expanded: false,
10413 * framed: true,
10414 * padded: true,
10415 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10416 * } );
10417 * $( 'body' ).append( panel.$element );
10418 *
10419 * @class
10420 * @extends OO.ui.Layout
10421 *
10422 * @constructor
10423 * @param {Object} [config] Configuration options
10424 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10425 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10426 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10427 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10428 */
10429 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
10430 // Configuration initialization
10431 config = $.extend( {
10432 scrollable: false,
10433 padded: false,
10434 expanded: true,
10435 framed: false
10436 }, config );
10437
10438 // Parent constructor
10439 OO.ui.PanelLayout.parent.call( this, config );
10440
10441 // Initialization
10442 this.$element.addClass( 'oo-ui-panelLayout' );
10443 if ( config.scrollable ) {
10444 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
10445 }
10446 if ( config.padded ) {
10447 this.$element.addClass( 'oo-ui-panelLayout-padded' );
10448 }
10449 if ( config.expanded ) {
10450 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
10451 }
10452 if ( config.framed ) {
10453 this.$element.addClass( 'oo-ui-panelLayout-framed' );
10454 }
10455 };
10456
10457 /* Setup */
10458
10459 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
10460
10461 /**
10462 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10463 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10464 * rather extended to include the required content and functionality.
10465 *
10466 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10467 * item is customized (with a label) using the #setupTabItem method. See
10468 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10469 *
10470 * @class
10471 * @extends OO.ui.PanelLayout
10472 *
10473 * @constructor
10474 * @param {string} name Unique symbolic name of card
10475 * @param {Object} [config] Configuration options
10476 */
10477 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
10478 // Allow passing positional parameters inside the config object
10479 if ( OO.isPlainObject( name ) && config === undefined ) {
10480 config = name;
10481 name = config.name;
10482 }
10483
10484 // Configuration initialization
10485 config = $.extend( { scrollable: true }, config );
10486
10487 // Parent constructor
10488 OO.ui.CardLayout.parent.call( this, config );
10489
10490 // Properties
10491 this.name = name;
10492 this.tabItem = null;
10493 this.active = false;
10494
10495 // Initialization
10496 this.$element.addClass( 'oo-ui-cardLayout' );
10497 };
10498
10499 /* Setup */
10500
10501 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
10502
10503 /* Events */
10504
10505 /**
10506 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10507 * shown in a index layout that is configured to display only one card at a time.
10508 *
10509 * @event active
10510 * @param {boolean} active Card is active
10511 */
10512
10513 /* Methods */
10514
10515 /**
10516 * Get the symbolic name of the card.
10517 *
10518 * @return {string} Symbolic name of card
10519 */
10520 OO.ui.CardLayout.prototype.getName = function () {
10521 return this.name;
10522 };
10523
10524 /**
10525 * Check if card is active.
10526 *
10527 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10528 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10529 *
10530 * @return {boolean} Card is active
10531 */
10532 OO.ui.CardLayout.prototype.isActive = function () {
10533 return this.active;
10534 };
10535
10536 /**
10537 * Get tab item.
10538 *
10539 * The tab item allows users to access the card from the index's tab
10540 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10541 *
10542 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10543 */
10544 OO.ui.CardLayout.prototype.getTabItem = function () {
10545 return this.tabItem;
10546 };
10547
10548 /**
10549 * Set or unset the tab item.
10550 *
10551 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10552 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10553 * level), use #setupTabItem instead of this method.
10554 *
10555 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10556 * @chainable
10557 */
10558 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
10559 this.tabItem = tabItem || null;
10560 if ( tabItem ) {
10561 this.setupTabItem();
10562 }
10563 return this;
10564 };
10565
10566 /**
10567 * Set up the tab item.
10568 *
10569 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10570 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10571 * the #setTabItem method instead.
10572 *
10573 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10574 * @chainable
10575 */
10576 OO.ui.CardLayout.prototype.setupTabItem = function () {
10577 return this;
10578 };
10579
10580 /**
10581 * Set the card to its 'active' state.
10582 *
10583 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10584 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10585 * context, setting the active state on a card does nothing.
10586 *
10587 * @param {boolean} value Card is active
10588 * @fires active
10589 */
10590 OO.ui.CardLayout.prototype.setActive = function ( active ) {
10591 active = !!active;
10592
10593 if ( active !== this.active ) {
10594 this.active = active;
10595 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
10596 this.emit( 'active', this.active );
10597 }
10598 };
10599
10600 /**
10601 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10602 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10603 * rather extended to include the required content and functionality.
10604 *
10605 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10606 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10607 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10608 *
10609 * @class
10610 * @extends OO.ui.PanelLayout
10611 *
10612 * @constructor
10613 * @param {string} name Unique symbolic name of page
10614 * @param {Object} [config] Configuration options
10615 */
10616 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
10617 // Allow passing positional parameters inside the config object
10618 if ( OO.isPlainObject( name ) && config === undefined ) {
10619 config = name;
10620 name = config.name;
10621 }
10622
10623 // Configuration initialization
10624 config = $.extend( { scrollable: true }, config );
10625
10626 // Parent constructor
10627 OO.ui.PageLayout.parent.call( this, config );
10628
10629 // Properties
10630 this.name = name;
10631 this.outlineItem = null;
10632 this.active = false;
10633
10634 // Initialization
10635 this.$element.addClass( 'oo-ui-pageLayout' );
10636 };
10637
10638 /* Setup */
10639
10640 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
10641
10642 /* Events */
10643
10644 /**
10645 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10646 * shown in a booklet layout that is configured to display only one page at a time.
10647 *
10648 * @event active
10649 * @param {boolean} active Page is active
10650 */
10651
10652 /* Methods */
10653
10654 /**
10655 * Get the symbolic name of the page.
10656 *
10657 * @return {string} Symbolic name of page
10658 */
10659 OO.ui.PageLayout.prototype.getName = function () {
10660 return this.name;
10661 };
10662
10663 /**
10664 * Check if page is active.
10665 *
10666 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10667 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10668 *
10669 * @return {boolean} Page is active
10670 */
10671 OO.ui.PageLayout.prototype.isActive = function () {
10672 return this.active;
10673 };
10674
10675 /**
10676 * Get outline item.
10677 *
10678 * The outline item allows users to access the page from the booklet's outline
10679 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10680 *
10681 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10682 */
10683 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10684 return this.outlineItem;
10685 };
10686
10687 /**
10688 * Set or unset the outline item.
10689 *
10690 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10691 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10692 * level), use #setupOutlineItem instead of this method.
10693 *
10694 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10695 * @chainable
10696 */
10697 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10698 this.outlineItem = outlineItem || null;
10699 if ( outlineItem ) {
10700 this.setupOutlineItem();
10701 }
10702 return this;
10703 };
10704
10705 /**
10706 * Set up the outline item.
10707 *
10708 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10709 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10710 * the #setOutlineItem method instead.
10711 *
10712 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10713 * @chainable
10714 */
10715 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10716 return this;
10717 };
10718
10719 /**
10720 * Set the page to its 'active' state.
10721 *
10722 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10723 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10724 * context, setting the active state on a page does nothing.
10725 *
10726 * @param {boolean} value Page is active
10727 * @fires active
10728 */
10729 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10730 active = !!active;
10731
10732 if ( active !== this.active ) {
10733 this.active = active;
10734 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10735 this.emit( 'active', this.active );
10736 }
10737 };
10738
10739 /**
10740 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10741 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10742 * by setting the #continuous option to 'true'.
10743 *
10744 * @example
10745 * // A stack layout with two panels, configured to be displayed continously
10746 * var myStack = new OO.ui.StackLayout( {
10747 * items: [
10748 * new OO.ui.PanelLayout( {
10749 * $content: $( '<p>Panel One</p>' ),
10750 * padded: true,
10751 * framed: true
10752 * } ),
10753 * new OO.ui.PanelLayout( {
10754 * $content: $( '<p>Panel Two</p>' ),
10755 * padded: true,
10756 * framed: true
10757 * } )
10758 * ],
10759 * continuous: true
10760 * } );
10761 * $( 'body' ).append( myStack.$element );
10762 *
10763 * @class
10764 * @extends OO.ui.PanelLayout
10765 * @mixins OO.ui.mixin.GroupElement
10766 *
10767 * @constructor
10768 * @param {Object} [config] Configuration options
10769 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10770 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10771 */
10772 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10773 // Configuration initialization
10774 config = $.extend( { scrollable: true }, config );
10775
10776 // Parent constructor
10777 OO.ui.StackLayout.parent.call( this, config );
10778
10779 // Mixin constructors
10780 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10781
10782 // Properties
10783 this.currentItem = null;
10784 this.continuous = !!config.continuous;
10785
10786 // Initialization
10787 this.$element.addClass( 'oo-ui-stackLayout' );
10788 if ( this.continuous ) {
10789 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10790 }
10791 if ( Array.isArray( config.items ) ) {
10792 this.addItems( config.items );
10793 }
10794 };
10795
10796 /* Setup */
10797
10798 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10799 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
10800
10801 /* Events */
10802
10803 /**
10804 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10805 * {@link #clearItems cleared} or {@link #setItem displayed}.
10806 *
10807 * @event set
10808 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10809 */
10810
10811 /* Methods */
10812
10813 /**
10814 * Get the current panel.
10815 *
10816 * @return {OO.ui.Layout|null}
10817 */
10818 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10819 return this.currentItem;
10820 };
10821
10822 /**
10823 * Unset the current item.
10824 *
10825 * @private
10826 * @param {OO.ui.StackLayout} layout
10827 * @fires set
10828 */
10829 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10830 var prevItem = this.currentItem;
10831 if ( prevItem === null ) {
10832 return;
10833 }
10834
10835 this.currentItem = null;
10836 this.emit( 'set', null );
10837 };
10838
10839 /**
10840 * Add panel layouts to the stack layout.
10841 *
10842 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10843 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10844 * by the index.
10845 *
10846 * @param {OO.ui.Layout[]} items Panels to add
10847 * @param {number} [index] Index of the insertion point
10848 * @chainable
10849 */
10850 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10851 // Update the visibility
10852 this.updateHiddenState( items, this.currentItem );
10853
10854 // Mixin method
10855 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
10856
10857 if ( !this.currentItem && items.length ) {
10858 this.setItem( items[ 0 ] );
10859 }
10860
10861 return this;
10862 };
10863
10864 /**
10865 * Remove the specified panels from the stack layout.
10866 *
10867 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10868 * you may wish to use the #clearItems method instead.
10869 *
10870 * @param {OO.ui.Layout[]} items Panels to remove
10871 * @chainable
10872 * @fires set
10873 */
10874 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10875 // Mixin method
10876 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
10877
10878 if ( items.indexOf( this.currentItem ) !== -1 ) {
10879 if ( this.items.length ) {
10880 this.setItem( this.items[ 0 ] );
10881 } else {
10882 this.unsetCurrentItem();
10883 }
10884 }
10885
10886 return this;
10887 };
10888
10889 /**
10890 * Clear all panels from the stack layout.
10891 *
10892 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10893 * a subset of panels, use the #removeItems method.
10894 *
10895 * @chainable
10896 * @fires set
10897 */
10898 OO.ui.StackLayout.prototype.clearItems = function () {
10899 this.unsetCurrentItem();
10900 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
10901
10902 return this;
10903 };
10904
10905 /**
10906 * Show the specified panel.
10907 *
10908 * If another panel is currently displayed, it will be hidden.
10909 *
10910 * @param {OO.ui.Layout} item Panel to show
10911 * @chainable
10912 * @fires set
10913 */
10914 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10915 if ( item !== this.currentItem ) {
10916 this.updateHiddenState( this.items, item );
10917
10918 if ( this.items.indexOf( item ) !== -1 ) {
10919 this.currentItem = item;
10920 this.emit( 'set', item );
10921 } else {
10922 this.unsetCurrentItem();
10923 }
10924 }
10925
10926 return this;
10927 };
10928
10929 /**
10930 * Update the visibility of all items in case of non-continuous view.
10931 *
10932 * Ensure all items are hidden except for the selected one.
10933 * This method does nothing when the stack is continuous.
10934 *
10935 * @private
10936 * @param {OO.ui.Layout[]} items Item list iterate over
10937 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10938 */
10939 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10940 var i, len;
10941
10942 if ( !this.continuous ) {
10943 for ( i = 0, len = items.length; i < len; i++ ) {
10944 if ( !selectedItem || selectedItem !== items[ i ] ) {
10945 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10946 }
10947 }
10948 if ( selectedItem ) {
10949 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10950 }
10951 }
10952 };
10953
10954 /**
10955 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10956 * items), with small margins between them. Convenient when you need to put a number of block-level
10957 * widgets on a single line next to each other.
10958 *
10959 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10960 *
10961 * @example
10962 * // HorizontalLayout with a text input and a label
10963 * var layout = new OO.ui.HorizontalLayout( {
10964 * items: [
10965 * new OO.ui.LabelWidget( { label: 'Label' } ),
10966 * new OO.ui.TextInputWidget( { value: 'Text' } )
10967 * ]
10968 * } );
10969 * $( 'body' ).append( layout.$element );
10970 *
10971 * @class
10972 * @extends OO.ui.Layout
10973 * @mixins OO.ui.mixin.GroupElement
10974 *
10975 * @constructor
10976 * @param {Object} [config] Configuration options
10977 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10978 */
10979 OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) {
10980 // Configuration initialization
10981 config = config || {};
10982
10983 // Parent constructor
10984 OO.ui.HorizontalLayout.parent.call( this, config );
10985
10986 // Mixin constructors
10987 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10988
10989 // Initialization
10990 this.$element.addClass( 'oo-ui-horizontalLayout' );
10991 if ( Array.isArray( config.items ) ) {
10992 this.addItems( config.items );
10993 }
10994 };
10995
10996 /* Setup */
10997
10998 OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout );
10999 OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement );
11000
11001 /**
11002 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11003 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11004 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11005 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11006 * the tool.
11007 *
11008 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11009 * set up.
11010 *
11011 * @example
11012 * // Example of a BarToolGroup with two tools
11013 * var toolFactory = new OO.ui.ToolFactory();
11014 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11015 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11016 *
11017 * // We will be placing status text in this element when tools are used
11018 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11019 *
11020 * // Define the tools that we're going to place in our toolbar
11021 *
11022 * // Create a class inheriting from OO.ui.Tool
11023 * function PictureTool() {
11024 * PictureTool.parent.apply( this, arguments );
11025 * }
11026 * OO.inheritClass( PictureTool, OO.ui.Tool );
11027 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11028 * // of 'icon' and 'title' (displayed icon and text).
11029 * PictureTool.static.name = 'picture';
11030 * PictureTool.static.icon = 'picture';
11031 * PictureTool.static.title = 'Insert picture';
11032 * // Defines the action that will happen when this tool is selected (clicked).
11033 * PictureTool.prototype.onSelect = function () {
11034 * $area.text( 'Picture tool clicked!' );
11035 * // Never display this tool as "active" (selected).
11036 * this.setActive( false );
11037 * };
11038 * // Make this tool available in our toolFactory and thus our toolbar
11039 * toolFactory.register( PictureTool );
11040 *
11041 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11042 * // little popup window (a PopupWidget).
11043 * function HelpTool( toolGroup, config ) {
11044 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11045 * padded: true,
11046 * label: 'Help',
11047 * head: true
11048 * } }, config ) );
11049 * this.popup.$body.append( '<p>I am helpful!</p>' );
11050 * }
11051 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11052 * HelpTool.static.name = 'help';
11053 * HelpTool.static.icon = 'help';
11054 * HelpTool.static.title = 'Help';
11055 * toolFactory.register( HelpTool );
11056 *
11057 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11058 * // used once (but not all defined tools must be used).
11059 * toolbar.setup( [
11060 * {
11061 * // 'bar' tool groups display tools by icon only
11062 * type: 'bar',
11063 * include: [ 'picture', 'help' ]
11064 * }
11065 * ] );
11066 *
11067 * // Create some UI around the toolbar and place it in the document
11068 * var frame = new OO.ui.PanelLayout( {
11069 * expanded: false,
11070 * framed: true
11071 * } );
11072 * var contentFrame = new OO.ui.PanelLayout( {
11073 * expanded: false,
11074 * padded: true
11075 * } );
11076 * frame.$element.append(
11077 * toolbar.$element,
11078 * contentFrame.$element.append( $area )
11079 * );
11080 * $( 'body' ).append( frame.$element );
11081 *
11082 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11083 * // document.
11084 * toolbar.initialize();
11085 *
11086 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11087 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11088 *
11089 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11090 *
11091 * @class
11092 * @extends OO.ui.ToolGroup
11093 *
11094 * @constructor
11095 * @param {OO.ui.Toolbar} toolbar
11096 * @param {Object} [config] Configuration options
11097 */
11098 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
11099 // Allow passing positional parameters inside the config object
11100 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11101 config = toolbar;
11102 toolbar = config.toolbar;
11103 }
11104
11105 // Parent constructor
11106 OO.ui.BarToolGroup.parent.call( this, toolbar, config );
11107
11108 // Initialization
11109 this.$element.addClass( 'oo-ui-barToolGroup' );
11110 };
11111
11112 /* Setup */
11113
11114 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
11115
11116 /* Static Properties */
11117
11118 OO.ui.BarToolGroup.static.titleTooltips = true;
11119
11120 OO.ui.BarToolGroup.static.accelTooltips = true;
11121
11122 OO.ui.BarToolGroup.static.name = 'bar';
11123
11124 /**
11125 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11126 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11127 * optional icon and label. This class can be used for other base classes that also use this functionality.
11128 *
11129 * @abstract
11130 * @class
11131 * @extends OO.ui.ToolGroup
11132 * @mixins OO.ui.mixin.IconElement
11133 * @mixins OO.ui.mixin.IndicatorElement
11134 * @mixins OO.ui.mixin.LabelElement
11135 * @mixins OO.ui.mixin.TitledElement
11136 * @mixins OO.ui.mixin.ClippableElement
11137 * @mixins OO.ui.mixin.TabIndexedElement
11138 *
11139 * @constructor
11140 * @param {OO.ui.Toolbar} toolbar
11141 * @param {Object} [config] Configuration options
11142 * @cfg {string} [header] Text to display at the top of the popup
11143 */
11144 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
11145 // Allow passing positional parameters inside the config object
11146 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11147 config = toolbar;
11148 toolbar = config.toolbar;
11149 }
11150
11151 // Configuration initialization
11152 config = config || {};
11153
11154 // Parent constructor
11155 OO.ui.PopupToolGroup.parent.call( this, toolbar, config );
11156
11157 // Properties
11158 this.active = false;
11159 this.dragging = false;
11160 this.onBlurHandler = this.onBlur.bind( this );
11161 this.$handle = $( '<span>' );
11162
11163 // Mixin constructors
11164 OO.ui.mixin.IconElement.call( this, config );
11165 OO.ui.mixin.IndicatorElement.call( this, config );
11166 OO.ui.mixin.LabelElement.call( this, config );
11167 OO.ui.mixin.TitledElement.call( this, config );
11168 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11169 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11170
11171 // Events
11172 this.$handle.on( {
11173 keydown: this.onHandleMouseKeyDown.bind( this ),
11174 keyup: this.onHandleMouseKeyUp.bind( this ),
11175 mousedown: this.onHandleMouseKeyDown.bind( this ),
11176 mouseup: this.onHandleMouseKeyUp.bind( this )
11177 } );
11178
11179 // Initialization
11180 this.$handle
11181 .addClass( 'oo-ui-popupToolGroup-handle' )
11182 .append( this.$icon, this.$label, this.$indicator );
11183 // If the pop-up should have a header, add it to the top of the toolGroup.
11184 // Note: If this feature is useful for other widgets, we could abstract it into an
11185 // OO.ui.HeaderedElement mixin constructor.
11186 if ( config.header !== undefined ) {
11187 this.$group
11188 .prepend( $( '<span>' )
11189 .addClass( 'oo-ui-popupToolGroup-header' )
11190 .text( config.header )
11191 );
11192 }
11193 this.$element
11194 .addClass( 'oo-ui-popupToolGroup' )
11195 .prepend( this.$handle );
11196 };
11197
11198 /* Setup */
11199
11200 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
11201 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
11202 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
11203 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
11204 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
11205 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
11206 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
11207
11208 /* Methods */
11209
11210 /**
11211 * @inheritdoc
11212 */
11213 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
11214 // Parent method
11215 OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments );
11216
11217 if ( this.isDisabled() && this.isElementAttached() ) {
11218 this.setActive( false );
11219 }
11220 };
11221
11222 /**
11223 * Handle focus being lost.
11224 *
11225 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11226 *
11227 * @protected
11228 * @param {jQuery.Event} e Mouse up or key up event
11229 */
11230 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
11231 // Only deactivate when clicking outside the dropdown element
11232 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
11233 this.setActive( false );
11234 }
11235 };
11236
11237 /**
11238 * @inheritdoc
11239 */
11240 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
11241 // Only close toolgroup when a tool was actually selected
11242 if (
11243 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
11244 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11245 ) {
11246 this.setActive( false );
11247 }
11248 return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11249 };
11250
11251 /**
11252 * Handle mouse up and key up events.
11253 *
11254 * @protected
11255 * @param {jQuery.Event} e Mouse up or key up event
11256 */
11257 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
11258 if (
11259 !this.isDisabled() &&
11260 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11261 ) {
11262 return false;
11263 }
11264 };
11265
11266 /**
11267 * Handle mouse down and key down events.
11268 *
11269 * @protected
11270 * @param {jQuery.Event} e Mouse down or key down event
11271 */
11272 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
11273 if (
11274 !this.isDisabled() &&
11275 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11276 ) {
11277 this.setActive( !this.active );
11278 return false;
11279 }
11280 };
11281
11282 /**
11283 * Switch into 'active' mode.
11284 *
11285 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11286 * deactivation.
11287 */
11288 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
11289 var containerWidth, containerLeft;
11290 value = !!value;
11291 if ( this.active !== value ) {
11292 this.active = value;
11293 if ( value ) {
11294 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11295 OO.ui.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11296
11297 this.$clippable.css( 'left', '' );
11298 // Try anchoring the popup to the left first
11299 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11300 this.toggleClipping( true );
11301 if ( this.isClippedHorizontally() ) {
11302 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11303 this.toggleClipping( false );
11304 this.$element
11305 .removeClass( 'oo-ui-popupToolGroup-left' )
11306 .addClass( 'oo-ui-popupToolGroup-right' );
11307 this.toggleClipping( true );
11308 }
11309 if ( this.isClippedHorizontally() ) {
11310 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11311 containerWidth = this.$clippableContainer.width();
11312 containerLeft = this.$clippableContainer.offset().left;
11313
11314 this.toggleClipping( false );
11315 this.$element.removeClass( 'oo-ui-popupToolGroup-right' );
11316
11317 this.$clippable.css( {
11318 left: -( this.$element.offset().left - containerLeft ),
11319 width: containerWidth
11320 } );
11321 }
11322 } else {
11323 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler );
11324 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler );
11325 this.$element.removeClass(
11326 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11327 );
11328 this.toggleClipping( false );
11329 }
11330 }
11331 };
11332
11333 /**
11334 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11335 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11336 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11337 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11338 * with a label, icon, indicator, header, and title.
11339 *
11340 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11341 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11342 * users to collapse the list again.
11343 *
11344 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11345 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11346 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11347 *
11348 * @example
11349 * // Example of a ListToolGroup
11350 * var toolFactory = new OO.ui.ToolFactory();
11351 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11352 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11353 *
11354 * // Configure and register two tools
11355 * function SettingsTool() {
11356 * SettingsTool.parent.apply( this, arguments );
11357 * }
11358 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11359 * SettingsTool.static.name = 'settings';
11360 * SettingsTool.static.icon = 'settings';
11361 * SettingsTool.static.title = 'Change settings';
11362 * SettingsTool.prototype.onSelect = function () {
11363 * this.setActive( false );
11364 * };
11365 * toolFactory.register( SettingsTool );
11366 * // Register two more tools, nothing interesting here
11367 * function StuffTool() {
11368 * StuffTool.parent.apply( this, arguments );
11369 * }
11370 * OO.inheritClass( StuffTool, OO.ui.Tool );
11371 * StuffTool.static.name = 'stuff';
11372 * StuffTool.static.icon = 'ellipsis';
11373 * StuffTool.static.title = 'Change the world';
11374 * StuffTool.prototype.onSelect = function () {
11375 * this.setActive( false );
11376 * };
11377 * toolFactory.register( StuffTool );
11378 * toolbar.setup( [
11379 * {
11380 * // Configurations for list toolgroup.
11381 * type: 'list',
11382 * label: 'ListToolGroup',
11383 * indicator: 'down',
11384 * icon: 'picture',
11385 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11386 * header: 'This is the header',
11387 * include: [ 'settings', 'stuff' ],
11388 * allowCollapse: ['stuff']
11389 * }
11390 * ] );
11391 *
11392 * // Create some UI around the toolbar and place it in the document
11393 * var frame = new OO.ui.PanelLayout( {
11394 * expanded: false,
11395 * framed: true
11396 * } );
11397 * frame.$element.append(
11398 * toolbar.$element
11399 * );
11400 * $( 'body' ).append( frame.$element );
11401 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11402 * toolbar.initialize();
11403 *
11404 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11405 *
11406 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11407 *
11408 * @class
11409 * @extends OO.ui.PopupToolGroup
11410 *
11411 * @constructor
11412 * @param {OO.ui.Toolbar} toolbar
11413 * @param {Object} [config] Configuration options
11414 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11415 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11416 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11417 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11418 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11419 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11420 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11421 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11422 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11423 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11424 */
11425 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
11426 // Allow passing positional parameters inside the config object
11427 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11428 config = toolbar;
11429 toolbar = config.toolbar;
11430 }
11431
11432 // Configuration initialization
11433 config = config || {};
11434
11435 // Properties (must be set before parent constructor, which calls #populate)
11436 this.allowCollapse = config.allowCollapse;
11437 this.forceExpand = config.forceExpand;
11438 this.expanded = config.expanded !== undefined ? config.expanded : false;
11439 this.collapsibleTools = [];
11440
11441 // Parent constructor
11442 OO.ui.ListToolGroup.parent.call( this, toolbar, config );
11443
11444 // Initialization
11445 this.$element.addClass( 'oo-ui-listToolGroup' );
11446 };
11447
11448 /* Setup */
11449
11450 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
11451
11452 /* Static Properties */
11453
11454 OO.ui.ListToolGroup.static.name = 'list';
11455
11456 /* Methods */
11457
11458 /**
11459 * @inheritdoc
11460 */
11461 OO.ui.ListToolGroup.prototype.populate = function () {
11462 var i, len, allowCollapse = [];
11463
11464 OO.ui.ListToolGroup.parent.prototype.populate.call( this );
11465
11466 // Update the list of collapsible tools
11467 if ( this.allowCollapse !== undefined ) {
11468 allowCollapse = this.allowCollapse;
11469 } else if ( this.forceExpand !== undefined ) {
11470 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
11471 }
11472
11473 this.collapsibleTools = [];
11474 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
11475 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
11476 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
11477 }
11478 }
11479
11480 // Keep at the end, even when tools are added
11481 this.$group.append( this.getExpandCollapseTool().$element );
11482
11483 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
11484 this.updateCollapsibleState();
11485 };
11486
11487 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
11488 var ExpandCollapseTool;
11489 if ( this.expandCollapseTool === undefined ) {
11490 ExpandCollapseTool = function () {
11491 ExpandCollapseTool.parent.apply( this, arguments );
11492 };
11493
11494 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
11495
11496 ExpandCollapseTool.prototype.onSelect = function () {
11497 this.toolGroup.expanded = !this.toolGroup.expanded;
11498 this.toolGroup.updateCollapsibleState();
11499 this.setActive( false );
11500 };
11501 ExpandCollapseTool.prototype.onUpdateState = function () {
11502 // Do nothing. Tool interface requires an implementation of this function.
11503 };
11504
11505 ExpandCollapseTool.static.name = 'more-fewer';
11506
11507 this.expandCollapseTool = new ExpandCollapseTool( this );
11508 }
11509 return this.expandCollapseTool;
11510 };
11511
11512 /**
11513 * @inheritdoc
11514 */
11515 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
11516 // Do not close the popup when the user wants to show more/fewer tools
11517 if (
11518 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
11519 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
11520 ) {
11521 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11522 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11523 return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e );
11524 } else {
11525 return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e );
11526 }
11527 };
11528
11529 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
11530 var i, len;
11531
11532 this.getExpandCollapseTool()
11533 .setIcon( this.expanded ? 'collapse' : 'expand' )
11534 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11535
11536 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
11537 this.collapsibleTools[ i ].toggle( this.expanded );
11538 }
11539 };
11540
11541 /**
11542 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11543 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11544 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11545 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11546 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11547 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11548 *
11549 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11550 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11551 * a MenuToolGroup is used.
11552 *
11553 * @example
11554 * // Example of a MenuToolGroup
11555 * var toolFactory = new OO.ui.ToolFactory();
11556 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11557 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11558 *
11559 * // We will be placing status text in this element when tools are used
11560 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11561 *
11562 * // Define the tools that we're going to place in our toolbar
11563 *
11564 * function SettingsTool() {
11565 * SettingsTool.parent.apply( this, arguments );
11566 * this.reallyActive = false;
11567 * }
11568 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11569 * SettingsTool.static.name = 'settings';
11570 * SettingsTool.static.icon = 'settings';
11571 * SettingsTool.static.title = 'Change settings';
11572 * SettingsTool.prototype.onSelect = function () {
11573 * $area.text( 'Settings tool clicked!' );
11574 * // Toggle the active state on each click
11575 * this.reallyActive = !this.reallyActive;
11576 * this.setActive( this.reallyActive );
11577 * // To update the menu label
11578 * this.toolbar.emit( 'updateState' );
11579 * };
11580 * SettingsTool.prototype.onUpdateState = function () {
11581 * };
11582 * toolFactory.register( SettingsTool );
11583 *
11584 * function StuffTool() {
11585 * StuffTool.parent.apply( this, arguments );
11586 * this.reallyActive = false;
11587 * }
11588 * OO.inheritClass( StuffTool, OO.ui.Tool );
11589 * StuffTool.static.name = 'stuff';
11590 * StuffTool.static.icon = 'ellipsis';
11591 * StuffTool.static.title = 'More stuff';
11592 * StuffTool.prototype.onSelect = function () {
11593 * $area.text( 'More stuff tool clicked!' );
11594 * // Toggle the active state on each click
11595 * this.reallyActive = !this.reallyActive;
11596 * this.setActive( this.reallyActive );
11597 * // To update the menu label
11598 * this.toolbar.emit( 'updateState' );
11599 * };
11600 * StuffTool.prototype.onUpdateState = function () {
11601 * };
11602 * toolFactory.register( StuffTool );
11603 *
11604 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11605 * // used once (but not all defined tools must be used).
11606 * toolbar.setup( [
11607 * {
11608 * type: 'menu',
11609 * header: 'This is the (optional) header',
11610 * title: 'This is the (optional) title',
11611 * indicator: 'down',
11612 * include: [ 'settings', 'stuff' ]
11613 * }
11614 * ] );
11615 *
11616 * // Create some UI around the toolbar and place it in the document
11617 * var frame = new OO.ui.PanelLayout( {
11618 * expanded: false,
11619 * framed: true
11620 * } );
11621 * var contentFrame = new OO.ui.PanelLayout( {
11622 * expanded: false,
11623 * padded: true
11624 * } );
11625 * frame.$element.append(
11626 * toolbar.$element,
11627 * contentFrame.$element.append( $area )
11628 * );
11629 * $( 'body' ).append( frame.$element );
11630 *
11631 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11632 * // document.
11633 * toolbar.initialize();
11634 * toolbar.emit( 'updateState' );
11635 *
11636 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11637 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11638 *
11639 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11640 *
11641 * @class
11642 * @extends OO.ui.PopupToolGroup
11643 *
11644 * @constructor
11645 * @param {OO.ui.Toolbar} toolbar
11646 * @param {Object} [config] Configuration options
11647 */
11648 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
11649 // Allow passing positional parameters inside the config object
11650 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
11651 config = toolbar;
11652 toolbar = config.toolbar;
11653 }
11654
11655 // Configuration initialization
11656 config = config || {};
11657
11658 // Parent constructor
11659 OO.ui.MenuToolGroup.parent.call( this, toolbar, config );
11660
11661 // Events
11662 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
11663
11664 // Initialization
11665 this.$element.addClass( 'oo-ui-menuToolGroup' );
11666 };
11667
11668 /* Setup */
11669
11670 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
11671
11672 /* Static Properties */
11673
11674 OO.ui.MenuToolGroup.static.name = 'menu';
11675
11676 /* Methods */
11677
11678 /**
11679 * Handle the toolbar state being updated.
11680 *
11681 * When the state changes, the title of each active item in the menu will be joined together and
11682 * used as a label for the group. The label will be empty if none of the items are active.
11683 *
11684 * @private
11685 */
11686 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
11687 var name,
11688 labelTexts = [];
11689
11690 for ( name in this.tools ) {
11691 if ( this.tools[ name ].isActive() ) {
11692 labelTexts.push( this.tools[ name ].getTitle() );
11693 }
11694 }
11695
11696 this.setLabel( labelTexts.join( ', ' ) || ' ' );
11697 };
11698
11699 /**
11700 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11701 * 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
11702 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11703 *
11704 * // Example of a popup tool. When selected, a popup tool displays
11705 * // a popup window.
11706 * function HelpTool( toolGroup, config ) {
11707 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11708 * padded: true,
11709 * label: 'Help',
11710 * head: true
11711 * } }, config ) );
11712 * this.popup.$body.append( '<p>I am helpful!</p>' );
11713 * };
11714 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11715 * HelpTool.static.name = 'help';
11716 * HelpTool.static.icon = 'help';
11717 * HelpTool.static.title = 'Help';
11718 * toolFactory.register( HelpTool );
11719 *
11720 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11721 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11722 *
11723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11724 *
11725 * @abstract
11726 * @class
11727 * @extends OO.ui.Tool
11728 * @mixins OO.ui.mixin.PopupElement
11729 *
11730 * @constructor
11731 * @param {OO.ui.ToolGroup} toolGroup
11732 * @param {Object} [config] Configuration options
11733 */
11734 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
11735 // Allow passing positional parameters inside the config object
11736 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11737 config = toolGroup;
11738 toolGroup = config.toolGroup;
11739 }
11740
11741 // Parent constructor
11742 OO.ui.PopupTool.parent.call( this, toolGroup, config );
11743
11744 // Mixin constructors
11745 OO.ui.mixin.PopupElement.call( this, config );
11746
11747 // Initialization
11748 this.$element
11749 .addClass( 'oo-ui-popupTool' )
11750 .append( this.popup.$element );
11751 };
11752
11753 /* Setup */
11754
11755 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
11756 OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
11757
11758 /* Methods */
11759
11760 /**
11761 * Handle the tool being selected.
11762 *
11763 * @inheritdoc
11764 */
11765 OO.ui.PopupTool.prototype.onSelect = function () {
11766 if ( !this.isDisabled() ) {
11767 this.popup.toggle();
11768 }
11769 this.setActive( false );
11770 return false;
11771 };
11772
11773 /**
11774 * Handle the toolbar state being updated.
11775 *
11776 * @inheritdoc
11777 */
11778 OO.ui.PopupTool.prototype.onUpdateState = function () {
11779 this.setActive( false );
11780 };
11781
11782 /**
11783 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11784 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11785 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11786 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11787 * when the ToolGroupTool is selected.
11788 *
11789 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11790 *
11791 * function SettingsTool() {
11792 * SettingsTool.parent.apply( this, arguments );
11793 * };
11794 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11795 * SettingsTool.static.name = 'settings';
11796 * SettingsTool.static.title = 'Change settings';
11797 * SettingsTool.static.groupConfig = {
11798 * icon: 'settings',
11799 * label: 'ToolGroupTool',
11800 * include: [ 'setting1', 'setting2' ]
11801 * };
11802 * toolFactory.register( SettingsTool );
11803 *
11804 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11805 *
11806 * Please note that this implementation is subject to change per [T74159] [2].
11807 *
11808 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11809 * [2]: https://phabricator.wikimedia.org/T74159
11810 *
11811 * @abstract
11812 * @class
11813 * @extends OO.ui.Tool
11814 *
11815 * @constructor
11816 * @param {OO.ui.ToolGroup} toolGroup
11817 * @param {Object} [config] Configuration options
11818 */
11819 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
11820 // Allow passing positional parameters inside the config object
11821 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
11822 config = toolGroup;
11823 toolGroup = config.toolGroup;
11824 }
11825
11826 // Parent constructor
11827 OO.ui.ToolGroupTool.parent.call( this, toolGroup, config );
11828
11829 // Properties
11830 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
11831
11832 // Events
11833 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
11834
11835 // Initialization
11836 this.$link.remove();
11837 this.$element
11838 .addClass( 'oo-ui-toolGroupTool' )
11839 .append( this.innerToolGroup.$element );
11840 };
11841
11842 /* Setup */
11843
11844 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
11845
11846 /* Static Properties */
11847
11848 /**
11849 * Toolgroup configuration.
11850 *
11851 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11852 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11853 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11854 *
11855 * @property {Object.<string,Array>}
11856 */
11857 OO.ui.ToolGroupTool.static.groupConfig = {};
11858
11859 /* Methods */
11860
11861 /**
11862 * Handle the tool being selected.
11863 *
11864 * @inheritdoc
11865 */
11866 OO.ui.ToolGroupTool.prototype.onSelect = function () {
11867 this.innerToolGroup.setActive( !this.innerToolGroup.active );
11868 return false;
11869 };
11870
11871 /**
11872 * Synchronize disabledness state of the tool with the inner toolgroup.
11873 *
11874 * @private
11875 * @param {boolean} disabled Element is disabled
11876 */
11877 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
11878 this.setDisabled( disabled );
11879 };
11880
11881 /**
11882 * Handle the toolbar state being updated.
11883 *
11884 * @inheritdoc
11885 */
11886 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
11887 this.setActive( false );
11888 };
11889
11890 /**
11891 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11892 *
11893 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11894 * more information.
11895 * @return {OO.ui.ListToolGroup}
11896 */
11897 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
11898 if ( group.include === '*' ) {
11899 // Apply defaults to catch-all groups
11900 if ( group.label === undefined ) {
11901 group.label = OO.ui.msg( 'ooui-toolbar-more' );
11902 }
11903 }
11904
11905 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
11906 };
11907
11908 /**
11909 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11910 *
11911 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11912 *
11913 * @private
11914 * @abstract
11915 * @class
11916 * @extends OO.ui.mixin.GroupElement
11917 *
11918 * @constructor
11919 * @param {Object} [config] Configuration options
11920 */
11921 OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) {
11922 // Parent constructor
11923 OO.ui.mixin.GroupWidget.parent.call( this, config );
11924 };
11925
11926 /* Setup */
11927
11928 OO.inheritClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement );
11929
11930 /* Methods */
11931
11932 /**
11933 * Set the disabled state of the widget.
11934 *
11935 * This will also update the disabled state of child widgets.
11936 *
11937 * @param {boolean} disabled Disable widget
11938 * @chainable
11939 */
11940 OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) {
11941 var i, len;
11942
11943 // Parent method
11944 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11945 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
11946
11947 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11948 if ( this.items ) {
11949 for ( i = 0, len = this.items.length; i < len; i++ ) {
11950 this.items[ i ].updateDisabled();
11951 }
11952 }
11953
11954 return this;
11955 };
11956
11957 /**
11958 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11959 *
11960 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11961 * allows bidirectional communication.
11962 *
11963 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11964 *
11965 * @private
11966 * @abstract
11967 * @class
11968 *
11969 * @constructor
11970 */
11971 OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() {
11972 //
11973 };
11974
11975 /* Methods */
11976
11977 /**
11978 * Check if widget is disabled.
11979 *
11980 * Checks parent if present, making disabled state inheritable.
11981 *
11982 * @return {boolean} Widget is disabled
11983 */
11984 OO.ui.mixin.ItemWidget.prototype.isDisabled = function () {
11985 return this.disabled ||
11986 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
11987 };
11988
11989 /**
11990 * Set group element is in.
11991 *
11992 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11993 * @chainable
11994 */
11995 OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) {
11996 // Parent method
11997 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
11998 OO.ui.Element.prototype.setElementGroup.call( this, group );
11999
12000 // Initialize item disabled states
12001 this.updateDisabled();
12002
12003 return this;
12004 };
12005
12006 /**
12007 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12008 * Controls include moving items up and down, removing items, and adding different kinds of items.
12009 *
12010 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12011 *
12012 * @class
12013 * @extends OO.ui.Widget
12014 * @mixins OO.ui.mixin.GroupElement
12015 * @mixins OO.ui.mixin.IconElement
12016 *
12017 * @constructor
12018 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12019 * @param {Object} [config] Configuration options
12020 * @cfg {Object} [abilities] List of abilties
12021 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12022 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12023 */
12024 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
12025 // Allow passing positional parameters inside the config object
12026 if ( OO.isPlainObject( outline ) && config === undefined ) {
12027 config = outline;
12028 outline = config.outline;
12029 }
12030
12031 // Configuration initialization
12032 config = $.extend( { icon: 'add' }, config );
12033
12034 // Parent constructor
12035 OO.ui.OutlineControlsWidget.parent.call( this, config );
12036
12037 // Mixin constructors
12038 OO.ui.mixin.GroupElement.call( this, config );
12039 OO.ui.mixin.IconElement.call( this, config );
12040
12041 // Properties
12042 this.outline = outline;
12043 this.$movers = $( '<div>' );
12044 this.upButton = new OO.ui.ButtonWidget( {
12045 framed: false,
12046 icon: 'collapse',
12047 title: OO.ui.msg( 'ooui-outline-control-move-up' )
12048 } );
12049 this.downButton = new OO.ui.ButtonWidget( {
12050 framed: false,
12051 icon: 'expand',
12052 title: OO.ui.msg( 'ooui-outline-control-move-down' )
12053 } );
12054 this.removeButton = new OO.ui.ButtonWidget( {
12055 framed: false,
12056 icon: 'remove',
12057 title: OO.ui.msg( 'ooui-outline-control-remove' )
12058 } );
12059 this.abilities = { move: true, remove: true };
12060
12061 // Events
12062 outline.connect( this, {
12063 select: 'onOutlineChange',
12064 add: 'onOutlineChange',
12065 remove: 'onOutlineChange'
12066 } );
12067 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
12068 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
12069 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
12070
12071 // Initialization
12072 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
12073 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
12074 this.$movers
12075 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12076 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
12077 this.$element.append( this.$icon, this.$group, this.$movers );
12078 this.setAbilities( config.abilities || {} );
12079 };
12080
12081 /* Setup */
12082
12083 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
12084 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
12085 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
12086
12087 /* Events */
12088
12089 /**
12090 * @event move
12091 * @param {number} places Number of places to move
12092 */
12093
12094 /**
12095 * @event remove
12096 */
12097
12098 /* Methods */
12099
12100 /**
12101 * Set abilities.
12102 *
12103 * @param {Object} abilities List of abilties
12104 * @param {boolean} [abilities.move] Allow moving movable items
12105 * @param {boolean} [abilities.remove] Allow removing removable items
12106 */
12107 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
12108 var ability;
12109
12110 for ( ability in this.abilities ) {
12111 if ( abilities[ ability ] !== undefined ) {
12112 this.abilities[ ability ] = !!abilities[ ability ];
12113 }
12114 }
12115
12116 this.onOutlineChange();
12117 };
12118
12119 /**
12120 *
12121 * @private
12122 * Handle outline change events.
12123 */
12124 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
12125 var i, len, firstMovable, lastMovable,
12126 items = this.outline.getItems(),
12127 selectedItem = this.outline.getSelectedItem(),
12128 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
12129 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
12130
12131 if ( movable ) {
12132 i = -1;
12133 len = items.length;
12134 while ( ++i < len ) {
12135 if ( items[ i ].isMovable() ) {
12136 firstMovable = items[ i ];
12137 break;
12138 }
12139 }
12140 i = len;
12141 while ( i-- ) {
12142 if ( items[ i ].isMovable() ) {
12143 lastMovable = items[ i ];
12144 break;
12145 }
12146 }
12147 }
12148 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
12149 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
12150 this.removeButton.setDisabled( !removable );
12151 };
12152
12153 /**
12154 * ToggleWidget implements basic behavior of widgets with an on/off state.
12155 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12156 *
12157 * @abstract
12158 * @class
12159 * @extends OO.ui.Widget
12160 *
12161 * @constructor
12162 * @param {Object} [config] Configuration options
12163 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12164 * By default, the toggle is in the 'off' state.
12165 */
12166 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
12167 // Configuration initialization
12168 config = config || {};
12169
12170 // Parent constructor
12171 OO.ui.ToggleWidget.parent.call( this, config );
12172
12173 // Properties
12174 this.value = null;
12175
12176 // Initialization
12177 this.$element.addClass( 'oo-ui-toggleWidget' );
12178 this.setValue( !!config.value );
12179 };
12180
12181 /* Setup */
12182
12183 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
12184
12185 /* Events */
12186
12187 /**
12188 * @event change
12189 *
12190 * A change event is emitted when the on/off state of the toggle changes.
12191 *
12192 * @param {boolean} value Value representing the new state of the toggle
12193 */
12194
12195 /* Methods */
12196
12197 /**
12198 * Get the value representing the toggle’s state.
12199 *
12200 * @return {boolean} The on/off state of the toggle
12201 */
12202 OO.ui.ToggleWidget.prototype.getValue = function () {
12203 return this.value;
12204 };
12205
12206 /**
12207 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12208 *
12209 * @param {boolean} value The state of the toggle
12210 * @fires change
12211 * @chainable
12212 */
12213 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
12214 value = !!value;
12215 if ( this.value !== value ) {
12216 this.value = value;
12217 this.emit( 'change', value );
12218 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
12219 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
12220 this.$element.attr( 'aria-checked', value.toString() );
12221 }
12222 return this;
12223 };
12224
12225 /**
12226 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12227 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12228 * removed, and cleared from the group.
12229 *
12230 * @example
12231 * // Example: A ButtonGroupWidget with two buttons
12232 * var button1 = new OO.ui.PopupButtonWidget( {
12233 * label: 'Select a category',
12234 * icon: 'menu',
12235 * popup: {
12236 * $content: $( '<p>List of categories...</p>' ),
12237 * padded: true,
12238 * align: 'left'
12239 * }
12240 * } );
12241 * var button2 = new OO.ui.ButtonWidget( {
12242 * label: 'Add item'
12243 * });
12244 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12245 * items: [button1, button2]
12246 * } );
12247 * $( 'body' ).append( buttonGroup.$element );
12248 *
12249 * @class
12250 * @extends OO.ui.Widget
12251 * @mixins OO.ui.mixin.GroupElement
12252 *
12253 * @constructor
12254 * @param {Object} [config] Configuration options
12255 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12256 */
12257 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
12258 // Configuration initialization
12259 config = config || {};
12260
12261 // Parent constructor
12262 OO.ui.ButtonGroupWidget.parent.call( this, config );
12263
12264 // Mixin constructors
12265 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
12266
12267 // Initialization
12268 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
12269 if ( Array.isArray( config.items ) ) {
12270 this.addItems( config.items );
12271 }
12272 };
12273
12274 /* Setup */
12275
12276 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
12277 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement );
12278
12279 /**
12280 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12281 * feels, and functionality can be customized via the class’s configuration options
12282 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12283 * and examples.
12284 *
12285 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12286 *
12287 * @example
12288 * // A button widget
12289 * var button = new OO.ui.ButtonWidget( {
12290 * label: 'Button with Icon',
12291 * icon: 'remove',
12292 * iconTitle: 'Remove'
12293 * } );
12294 * $( 'body' ).append( button.$element );
12295 *
12296 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12297 *
12298 * @class
12299 * @extends OO.ui.Widget
12300 * @mixins OO.ui.mixin.ButtonElement
12301 * @mixins OO.ui.mixin.IconElement
12302 * @mixins OO.ui.mixin.IndicatorElement
12303 * @mixins OO.ui.mixin.LabelElement
12304 * @mixins OO.ui.mixin.TitledElement
12305 * @mixins OO.ui.mixin.FlaggedElement
12306 * @mixins OO.ui.mixin.TabIndexedElement
12307 * @mixins OO.ui.mixin.AccessKeyedElement
12308 *
12309 * @constructor
12310 * @param {Object} [config] Configuration options
12311 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12312 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12313 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12314 */
12315 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
12316 // Configuration initialization
12317 config = config || {};
12318
12319 // Parent constructor
12320 OO.ui.ButtonWidget.parent.call( this, config );
12321
12322 // Mixin constructors
12323 OO.ui.mixin.ButtonElement.call( this, config );
12324 OO.ui.mixin.IconElement.call( this, config );
12325 OO.ui.mixin.IndicatorElement.call( this, config );
12326 OO.ui.mixin.LabelElement.call( this, config );
12327 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12328 OO.ui.mixin.FlaggedElement.call( this, config );
12329 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12330 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) );
12331
12332 // Properties
12333 this.href = null;
12334 this.target = null;
12335 this.noFollow = false;
12336
12337 // Events
12338 this.connect( this, { disable: 'onDisable' } );
12339
12340 // Initialization
12341 this.$button.append( this.$icon, this.$label, this.$indicator );
12342 this.$element
12343 .addClass( 'oo-ui-buttonWidget' )
12344 .append( this.$button );
12345 this.setHref( config.href );
12346 this.setTarget( config.target );
12347 this.setNoFollow( config.noFollow );
12348 };
12349
12350 /* Setup */
12351
12352 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
12353 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement );
12354 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement );
12355 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement );
12356 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement );
12357 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement );
12358 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement );
12359 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement );
12360 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement );
12361
12362 /* Methods */
12363
12364 /**
12365 * @inheritdoc
12366 */
12367 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
12368 if ( !this.isDisabled() ) {
12369 // Remove the tab-index while the button is down to prevent the button from stealing focus
12370 this.$button.removeAttr( 'tabindex' );
12371 }
12372
12373 return OO.ui.mixin.ButtonElement.prototype.onMouseDown.call( this, e );
12374 };
12375
12376 /**
12377 * @inheritdoc
12378 */
12379 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
12380 if ( !this.isDisabled() ) {
12381 // Restore the tab-index after the button is up to restore the button's accessibility
12382 this.$button.attr( 'tabindex', this.tabIndex );
12383 }
12384
12385 return OO.ui.mixin.ButtonElement.prototype.onMouseUp.call( this, e );
12386 };
12387
12388 /**
12389 * Get hyperlink location.
12390 *
12391 * @return {string} Hyperlink location
12392 */
12393 OO.ui.ButtonWidget.prototype.getHref = function () {
12394 return this.href;
12395 };
12396
12397 /**
12398 * Get hyperlink target.
12399 *
12400 * @return {string} Hyperlink target
12401 */
12402 OO.ui.ButtonWidget.prototype.getTarget = function () {
12403 return this.target;
12404 };
12405
12406 /**
12407 * Get search engine traversal hint.
12408 *
12409 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12410 */
12411 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
12412 return this.noFollow;
12413 };
12414
12415 /**
12416 * Set hyperlink location.
12417 *
12418 * @param {string|null} href Hyperlink location, null to remove
12419 */
12420 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
12421 href = typeof href === 'string' ? href : null;
12422 if ( href !== null ) {
12423 if ( !OO.ui.isSafeUrl( href ) ) {
12424 throw new Error( 'Potentially unsafe href provided: ' + href );
12425 }
12426
12427 }
12428
12429 if ( href !== this.href ) {
12430 this.href = href;
12431 this.updateHref();
12432 }
12433
12434 return this;
12435 };
12436
12437 /**
12438 * Update the `href` attribute, in case of changes to href or
12439 * disabled state.
12440 *
12441 * @private
12442 * @chainable
12443 */
12444 OO.ui.ButtonWidget.prototype.updateHref = function () {
12445 if ( this.href !== null && !this.isDisabled() ) {
12446 this.$button.attr( 'href', this.href );
12447 } else {
12448 this.$button.removeAttr( 'href' );
12449 }
12450
12451 return this;
12452 };
12453
12454 /**
12455 * Handle disable events.
12456 *
12457 * @private
12458 * @param {boolean} disabled Element is disabled
12459 */
12460 OO.ui.ButtonWidget.prototype.onDisable = function () {
12461 this.updateHref();
12462 };
12463
12464 /**
12465 * Set hyperlink target.
12466 *
12467 * @param {string|null} target Hyperlink target, null to remove
12468 */
12469 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
12470 target = typeof target === 'string' ? target : null;
12471
12472 if ( target !== this.target ) {
12473 this.target = target;
12474 if ( target !== null ) {
12475 this.$button.attr( 'target', target );
12476 } else {
12477 this.$button.removeAttr( 'target' );
12478 }
12479 }
12480
12481 return this;
12482 };
12483
12484 /**
12485 * Set search engine traversal hint.
12486 *
12487 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12488 */
12489 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
12490 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
12491
12492 if ( noFollow !== this.noFollow ) {
12493 this.noFollow = noFollow;
12494 if ( noFollow ) {
12495 this.$button.attr( 'rel', 'nofollow' );
12496 } else {
12497 this.$button.removeAttr( 'rel' );
12498 }
12499 }
12500
12501 return this;
12502 };
12503
12504 /**
12505 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12506 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12507 * of the actions.
12508 *
12509 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12510 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12511 * and examples.
12512 *
12513 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12514 *
12515 * @class
12516 * @extends OO.ui.ButtonWidget
12517 * @mixins OO.ui.mixin.PendingElement
12518 *
12519 * @constructor
12520 * @param {Object} [config] Configuration options
12521 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12522 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12523 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12524 * for more information about setting modes.
12525 * @cfg {boolean} [framed=false] Render the action button with a frame
12526 */
12527 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
12528 // Configuration initialization
12529 config = $.extend( { framed: false }, config );
12530
12531 // Parent constructor
12532 OO.ui.ActionWidget.parent.call( this, config );
12533
12534 // Mixin constructors
12535 OO.ui.mixin.PendingElement.call( this, config );
12536
12537 // Properties
12538 this.action = config.action || '';
12539 this.modes = config.modes || [];
12540 this.width = 0;
12541 this.height = 0;
12542
12543 // Initialization
12544 this.$element.addClass( 'oo-ui-actionWidget' );
12545 };
12546
12547 /* Setup */
12548
12549 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
12550 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
12551
12552 /* Events */
12553
12554 /**
12555 * A resize event is emitted when the size of the widget changes.
12556 *
12557 * @event resize
12558 */
12559
12560 /* Methods */
12561
12562 /**
12563 * Check if the action is configured to be available in the specified `mode`.
12564 *
12565 * @param {string} mode Name of mode
12566 * @return {boolean} The action is configured with the mode
12567 */
12568 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
12569 return this.modes.indexOf( mode ) !== -1;
12570 };
12571
12572 /**
12573 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12574 *
12575 * @return {string}
12576 */
12577 OO.ui.ActionWidget.prototype.getAction = function () {
12578 return this.action;
12579 };
12580
12581 /**
12582 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12583 *
12584 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12585 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12586 * are hidden.
12587 *
12588 * @return {string[]}
12589 */
12590 OO.ui.ActionWidget.prototype.getModes = function () {
12591 return this.modes.slice();
12592 };
12593
12594 /**
12595 * Emit a resize event if the size has changed.
12596 *
12597 * @private
12598 * @chainable
12599 */
12600 OO.ui.ActionWidget.prototype.propagateResize = function () {
12601 var width, height;
12602
12603 if ( this.isElementAttached() ) {
12604 width = this.$element.width();
12605 height = this.$element.height();
12606
12607 if ( width !== this.width || height !== this.height ) {
12608 this.width = width;
12609 this.height = height;
12610 this.emit( 'resize' );
12611 }
12612 }
12613
12614 return this;
12615 };
12616
12617 /**
12618 * @inheritdoc
12619 */
12620 OO.ui.ActionWidget.prototype.setIcon = function () {
12621 // Mixin method
12622 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
12623 this.propagateResize();
12624
12625 return this;
12626 };
12627
12628 /**
12629 * @inheritdoc
12630 */
12631 OO.ui.ActionWidget.prototype.setLabel = function () {
12632 // Mixin method
12633 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
12634 this.propagateResize();
12635
12636 return this;
12637 };
12638
12639 /**
12640 * @inheritdoc
12641 */
12642 OO.ui.ActionWidget.prototype.setFlags = function () {
12643 // Mixin method
12644 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
12645 this.propagateResize();
12646
12647 return this;
12648 };
12649
12650 /**
12651 * @inheritdoc
12652 */
12653 OO.ui.ActionWidget.prototype.clearFlags = function () {
12654 // Mixin method
12655 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
12656 this.propagateResize();
12657
12658 return this;
12659 };
12660
12661 /**
12662 * Toggle the visibility of the action button.
12663 *
12664 * @param {boolean} [show] Show button, omit to toggle visibility
12665 * @chainable
12666 */
12667 OO.ui.ActionWidget.prototype.toggle = function () {
12668 // Parent method
12669 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
12670 this.propagateResize();
12671
12672 return this;
12673 };
12674
12675 /**
12676 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12677 * which is used to display additional information or options.
12678 *
12679 * @example
12680 * // Example of a popup button.
12681 * var popupButton = new OO.ui.PopupButtonWidget( {
12682 * label: 'Popup button with options',
12683 * icon: 'menu',
12684 * popup: {
12685 * $content: $( '<p>Additional options here.</p>' ),
12686 * padded: true,
12687 * align: 'force-left'
12688 * }
12689 * } );
12690 * // Append the button to the DOM.
12691 * $( 'body' ).append( popupButton.$element );
12692 *
12693 * @class
12694 * @extends OO.ui.ButtonWidget
12695 * @mixins OO.ui.mixin.PopupElement
12696 *
12697 * @constructor
12698 * @param {Object} [config] Configuration options
12699 */
12700 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
12701 // Parent constructor
12702 OO.ui.PopupButtonWidget.parent.call( this, config );
12703
12704 // Mixin constructors
12705 OO.ui.mixin.PopupElement.call( this, config );
12706
12707 // Events
12708 this.connect( this, { click: 'onAction' } );
12709
12710 // Initialization
12711 this.$element
12712 .addClass( 'oo-ui-popupButtonWidget' )
12713 .attr( 'aria-haspopup', 'true' )
12714 .append( this.popup.$element );
12715 };
12716
12717 /* Setup */
12718
12719 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
12720 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement );
12721
12722 /* Methods */
12723
12724 /**
12725 * Handle the button action being triggered.
12726 *
12727 * @private
12728 */
12729 OO.ui.PopupButtonWidget.prototype.onAction = function () {
12730 this.popup.toggle();
12731 };
12732
12733 /**
12734 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12735 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12736 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12737 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12738 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12739 * the [OOjs UI documentation][1] on MediaWiki for more information.
12740 *
12741 * @example
12742 * // Toggle buttons in the 'off' and 'on' state.
12743 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12744 * label: 'Toggle Button off'
12745 * } );
12746 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12747 * label: 'Toggle Button on',
12748 * value: true
12749 * } );
12750 * // Append the buttons to the DOM.
12751 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12752 *
12753 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12754 *
12755 * @class
12756 * @extends OO.ui.ToggleWidget
12757 * @mixins OO.ui.mixin.ButtonElement
12758 * @mixins OO.ui.mixin.IconElement
12759 * @mixins OO.ui.mixin.IndicatorElement
12760 * @mixins OO.ui.mixin.LabelElement
12761 * @mixins OO.ui.mixin.TitledElement
12762 * @mixins OO.ui.mixin.FlaggedElement
12763 * @mixins OO.ui.mixin.TabIndexedElement
12764 *
12765 * @constructor
12766 * @param {Object} [config] Configuration options
12767 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12768 * state. By default, the button is in the 'off' state.
12769 */
12770 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
12771 // Configuration initialization
12772 config = config || {};
12773
12774 // Parent constructor
12775 OO.ui.ToggleButtonWidget.parent.call( this, config );
12776
12777 // Mixin constructors
12778 OO.ui.mixin.ButtonElement.call( this, config );
12779 OO.ui.mixin.IconElement.call( this, config );
12780 OO.ui.mixin.IndicatorElement.call( this, config );
12781 OO.ui.mixin.LabelElement.call( this, config );
12782 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
12783 OO.ui.mixin.FlaggedElement.call( this, config );
12784 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12785
12786 // Events
12787 this.connect( this, { click: 'onAction' } );
12788
12789 // Initialization
12790 this.$button.append( this.$icon, this.$label, this.$indicator );
12791 this.$element
12792 .addClass( 'oo-ui-toggleButtonWidget' )
12793 .append( this.$button );
12794 };
12795
12796 /* Setup */
12797
12798 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
12799 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
12800 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
12801 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
12802 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
12803 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
12804 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
12805 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
12806
12807 /* Methods */
12808
12809 /**
12810 * Handle the button action being triggered.
12811 *
12812 * @private
12813 */
12814 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
12815 this.setValue( !this.value );
12816 };
12817
12818 /**
12819 * @inheritdoc
12820 */
12821 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
12822 value = !!value;
12823 if ( value !== this.value ) {
12824 // Might be called from parent constructor before ButtonElement constructor
12825 if ( this.$button ) {
12826 this.$button.attr( 'aria-pressed', value.toString() );
12827 }
12828 this.setActive( value );
12829 }
12830
12831 // Parent method
12832 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
12833
12834 return this;
12835 };
12836
12837 /**
12838 * @inheritdoc
12839 */
12840 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
12841 if ( this.$button ) {
12842 this.$button.removeAttr( 'aria-pressed' );
12843 }
12844 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
12845 this.$button.attr( 'aria-pressed', this.value.toString() );
12846 };
12847
12848 /**
12849 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12850 * that allows for selecting multiple values.
12851 *
12852 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12853 *
12854 * @example
12855 * // Example: A CapsuleMultiSelectWidget.
12856 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12857 * label: 'CapsuleMultiSelectWidget',
12858 * selected: [ 'Option 1', 'Option 3' ],
12859 * menu: {
12860 * items: [
12861 * new OO.ui.MenuOptionWidget( {
12862 * data: 'Option 1',
12863 * label: 'Option One'
12864 * } ),
12865 * new OO.ui.MenuOptionWidget( {
12866 * data: 'Option 2',
12867 * label: 'Option Two'
12868 * } ),
12869 * new OO.ui.MenuOptionWidget( {
12870 * data: 'Option 3',
12871 * label: 'Option Three'
12872 * } ),
12873 * new OO.ui.MenuOptionWidget( {
12874 * data: 'Option 4',
12875 * label: 'Option Four'
12876 * } ),
12877 * new OO.ui.MenuOptionWidget( {
12878 * data: 'Option 5',
12879 * label: 'Option Five'
12880 * } )
12881 * ]
12882 * }
12883 * } );
12884 * $( 'body' ).append( capsule.$element );
12885 *
12886 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12887 *
12888 * @class
12889 * @extends OO.ui.Widget
12890 * @mixins OO.ui.mixin.TabIndexedElement
12891 * @mixins OO.ui.mixin.GroupElement
12892 *
12893 * @constructor
12894 * @param {Object} [config] Configuration options
12895 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12896 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12897 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12898 * If specified, this popup will be shown instead of the menu (but the menu
12899 * will still be used for item labels and allowArbitrary=false). The widgets
12900 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12901 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12902 * This configuration is useful in cases where the expanded menu is larger than
12903 * its containing `<div>`. The specified overlay layer is usually on top of
12904 * the containing `<div>` and has a larger area. By default, the menu uses
12905 * relative positioning.
12906 */
12907 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
12908 var $tabFocus;
12909
12910 // Configuration initialization
12911 config = config || {};
12912
12913 // Parent constructor
12914 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
12915
12916 // Properties (must be set before mixin constructor calls)
12917 this.$input = config.popup ? null : $( '<input>' );
12918 this.$handle = $( '<div>' );
12919
12920 // Mixin constructors
12921 OO.ui.mixin.GroupElement.call( this, config );
12922 if ( config.popup ) {
12923 config.popup = $.extend( {}, config.popup, {
12924 align: 'forwards',
12925 anchor: false
12926 } );
12927 OO.ui.mixin.PopupElement.call( this, config );
12928 $tabFocus = $( '<span>' );
12929 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
12930 } else {
12931 this.popup = null;
12932 $tabFocus = null;
12933 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
12934 }
12935 OO.ui.mixin.IndicatorElement.call( this, config );
12936 OO.ui.mixin.IconElement.call( this, config );
12937
12938 // Properties
12939 this.allowArbitrary = !!config.allowArbitrary;
12940 this.$overlay = config.$overlay || this.$element;
12941 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
12942 {
12943 widget: this,
12944 $input: this.$input,
12945 $container: this.$element,
12946 filterFromInput: true,
12947 disabled: this.isDisabled()
12948 },
12949 config.menu
12950 ) );
12951
12952 // Events
12953 if ( this.popup ) {
12954 $tabFocus.on( {
12955 focus: this.onFocusForPopup.bind( this )
12956 } );
12957 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12958 if ( this.popup.$autoCloseIgnore ) {
12959 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
12960 }
12961 this.popup.connect( this, {
12962 toggle: function ( visible ) {
12963 $tabFocus.toggle( !visible );
12964 }
12965 } );
12966 } else {
12967 this.$input.on( {
12968 focus: this.onInputFocus.bind( this ),
12969 blur: this.onInputBlur.bind( this ),
12970 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange.bind( this ),
12971 keydown: this.onKeyDown.bind( this ),
12972 keypress: this.onKeyPress.bind( this )
12973 } );
12974 }
12975 this.menu.connect( this, {
12976 choose: 'onMenuChoose',
12977 add: 'onMenuItemsChange',
12978 remove: 'onMenuItemsChange'
12979 } );
12980 this.$handle.on( {
12981 click: this.onClick.bind( this )
12982 } );
12983
12984 // Initialization
12985 if ( this.$input ) {
12986 this.$input.prop( 'disabled', this.isDisabled() );
12987 this.$input.attr( {
12988 role: 'combobox',
12989 'aria-autocomplete': 'list'
12990 } );
12991 this.$input.width( '1em' );
12992 }
12993 if ( config.data ) {
12994 this.setItemsFromData( config.data );
12995 }
12996 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12997 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
12998 .append( this.$indicator, this.$icon, this.$group );
12999 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13000 .append( this.$handle );
13001 if ( this.popup ) {
13002 this.$handle.append( $tabFocus );
13003 this.$overlay.append( this.popup.$element );
13004 } else {
13005 this.$handle.append( this.$input );
13006 this.$overlay.append( this.menu.$element );
13007 }
13008 this.onMenuItemsChange();
13009 };
13010
13011 /* Setup */
13012
13013 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
13014 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
13015 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
13016 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
13017 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
13018 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
13019
13020 /* Events */
13021
13022 /**
13023 * @event change
13024 *
13025 * A change event is emitted when the set of selected items changes.
13026 *
13027 * @param {Mixed[]} datas Data of the now-selected items
13028 */
13029
13030 /* Methods */
13031
13032 /**
13033 * Get the data of the items in the capsule
13034 * @return {Mixed[]}
13035 */
13036 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
13037 return $.map( this.getItems(), function ( e ) { return e.data; } );
13038 };
13039
13040 /**
13041 * Set the items in the capsule by providing data
13042 * @chainable
13043 * @param {Mixed[]} datas
13044 * @return {OO.ui.CapsuleMultiSelectWidget}
13045 */
13046 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
13047 var widget = this,
13048 menu = this.menu,
13049 items = this.getItems();
13050
13051 $.each( datas, function ( i, data ) {
13052 var j, label,
13053 item = menu.getItemFromData( data );
13054
13055 if ( item ) {
13056 label = item.label;
13057 } else if ( widget.allowArbitrary ) {
13058 label = String( data );
13059 } else {
13060 return;
13061 }
13062
13063 item = null;
13064 for ( j = 0; j < items.length; j++ ) {
13065 if ( items[ j ].data === data && items[ j ].label === label ) {
13066 item = items[ j ];
13067 items.splice( j, 1 );
13068 break;
13069 }
13070 }
13071 if ( !item ) {
13072 item = new OO.ui.CapsuleItemWidget( { data: data, label: label } );
13073 }
13074 widget.addItems( [ item ], i );
13075 } );
13076
13077 if ( items.length ) {
13078 widget.removeItems( items );
13079 }
13080
13081 return this;
13082 };
13083
13084 /**
13085 * Add items to the capsule by providing their data
13086 * @chainable
13087 * @param {Mixed[]} datas
13088 * @return {OO.ui.CapsuleMultiSelectWidget}
13089 */
13090 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
13091 var widget = this,
13092 menu = this.menu,
13093 items = [];
13094
13095 $.each( datas, function ( i, data ) {
13096 var item;
13097
13098 if ( !widget.getItemFromData( data ) ) {
13099 item = menu.getItemFromData( data );
13100 if ( item ) {
13101 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: item.label } ) );
13102 } else if ( widget.allowArbitrary ) {
13103 items.push( new OO.ui.CapsuleItemWidget( { data: data, label: String( data ) } ) );
13104 }
13105 }
13106 } );
13107
13108 if ( items.length ) {
13109 this.addItems( items );
13110 }
13111
13112 return this;
13113 };
13114
13115 /**
13116 * Remove items by data
13117 * @chainable
13118 * @param {Mixed[]} datas
13119 * @return {OO.ui.CapsuleMultiSelectWidget}
13120 */
13121 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
13122 var widget = this,
13123 items = [];
13124
13125 $.each( datas, function ( i, data ) {
13126 var item = widget.getItemFromData( data );
13127 if ( item ) {
13128 items.push( item );
13129 }
13130 } );
13131
13132 if ( items.length ) {
13133 this.removeItems( items );
13134 }
13135
13136 return this;
13137 };
13138
13139 /**
13140 * @inheritdoc
13141 */
13142 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
13143 var same, i, l,
13144 oldItems = this.items.slice();
13145
13146 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
13147
13148 if ( this.items.length !== oldItems.length ) {
13149 same = false;
13150 } else {
13151 same = true;
13152 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13153 same = same && this.items[ i ] === oldItems[ i ];
13154 }
13155 }
13156 if ( !same ) {
13157 this.emit( 'change', this.getItemsData() );
13158 }
13159
13160 return this;
13161 };
13162
13163 /**
13164 * @inheritdoc
13165 */
13166 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
13167 var same, i, l,
13168 oldItems = this.items.slice();
13169
13170 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
13171
13172 if ( this.items.length !== oldItems.length ) {
13173 same = false;
13174 } else {
13175 same = true;
13176 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
13177 same = same && this.items[ i ] === oldItems[ i ];
13178 }
13179 }
13180 if ( !same ) {
13181 this.emit( 'change', this.getItemsData() );
13182 }
13183
13184 return this;
13185 };
13186
13187 /**
13188 * @inheritdoc
13189 */
13190 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
13191 if ( this.items.length ) {
13192 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
13193 this.emit( 'change', this.getItemsData() );
13194 }
13195 return this;
13196 };
13197
13198 /**
13199 * Get the capsule widget's menu.
13200 * @return {OO.ui.MenuSelectWidget} Menu widget
13201 */
13202 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
13203 return this.menu;
13204 };
13205
13206 /**
13207 * Handle focus events
13208 *
13209 * @private
13210 * @param {jQuery.Event} event
13211 */
13212 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
13213 if ( !this.isDisabled() ) {
13214 this.menu.toggle( true );
13215 }
13216 };
13217
13218 /**
13219 * Handle blur events
13220 *
13221 * @private
13222 * @param {jQuery.Event} event
13223 */
13224 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
13225 this.clearInput();
13226 };
13227
13228 /**
13229 * Handle focus events
13230 *
13231 * @private
13232 * @param {jQuery.Event} event
13233 */
13234 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
13235 if ( !this.isDisabled() ) {
13236 this.popup.setSize( this.$handle.width() );
13237 this.popup.toggle( true );
13238 this.popup.$element.find( '*' )
13239 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13240 .first()
13241 .focus();
13242 }
13243 };
13244
13245 /**
13246 * Handles popup focus out events.
13247 *
13248 * @private
13249 * @param {Event} e Focus out event
13250 */
13251 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
13252 var widget = this.popup;
13253
13254 setTimeout( function () {
13255 if (
13256 widget.isVisible() &&
13257 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
13258 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
13259 ) {
13260 widget.toggle( false );
13261 }
13262 } );
13263 };
13264
13265 /**
13266 * Handle mouse click events.
13267 *
13268 * @private
13269 * @param {jQuery.Event} e Mouse click event
13270 */
13271 OO.ui.CapsuleMultiSelectWidget.prototype.onClick = function ( e ) {
13272 if ( e.which === 1 ) {
13273 this.focus();
13274 return false;
13275 }
13276 };
13277
13278 /**
13279 * Handle key press events.
13280 *
13281 * @private
13282 * @param {jQuery.Event} e Key press event
13283 */
13284 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
13285 var item;
13286
13287 if ( !this.isDisabled() ) {
13288 if ( e.which === OO.ui.Keys.ESCAPE ) {
13289 this.clearInput();
13290 return false;
13291 }
13292
13293 if ( !this.popup ) {
13294 this.menu.toggle( true );
13295 if ( e.which === OO.ui.Keys.ENTER ) {
13296 item = this.menu.getItemFromLabel( this.$input.val(), true );
13297 if ( item ) {
13298 this.addItemsFromData( [ item.data ] );
13299 this.clearInput();
13300 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
13301 this.addItemsFromData( [ this.$input.val() ] );
13302 this.clearInput();
13303 }
13304 return false;
13305 }
13306
13307 // Make sure the input gets resized.
13308 setTimeout( this.onInputChange.bind( this ), 0 );
13309 }
13310 }
13311 };
13312
13313 /**
13314 * Handle key down events.
13315 *
13316 * @private
13317 * @param {jQuery.Event} e Key down event
13318 */
13319 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
13320 if ( !this.isDisabled() ) {
13321 // 'keypress' event is not triggered for Backspace
13322 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.$input.val() === '' ) {
13323 if ( this.items.length ) {
13324 this.removeItems( this.items.slice( -1 ) );
13325 }
13326 return false;
13327 }
13328 }
13329 };
13330
13331 /**
13332 * Handle input change events.
13333 *
13334 * @private
13335 * @param {jQuery.Event} e Event of some sort
13336 */
13337 OO.ui.CapsuleMultiSelectWidget.prototype.onInputChange = function () {
13338 if ( !this.isDisabled() ) {
13339 this.$input.width( this.$input.val().length + 'em' );
13340 }
13341 };
13342
13343 /**
13344 * Handle menu choose events.
13345 *
13346 * @private
13347 * @param {OO.ui.OptionWidget} item Chosen item
13348 */
13349 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
13350 if ( item && item.isVisible() ) {
13351 this.addItemsFromData( [ item.getData() ] );
13352 this.clearInput();
13353 }
13354 };
13355
13356 /**
13357 * Handle menu item change events.
13358 *
13359 * @private
13360 */
13361 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
13362 this.setItemsFromData( this.getItemsData() );
13363 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
13364 };
13365
13366 /**
13367 * Clear the input field
13368 * @private
13369 */
13370 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
13371 if ( this.$input ) {
13372 this.$input.val( '' );
13373 this.$input.width( '1em' );
13374 }
13375 if ( this.popup ) {
13376 this.popup.toggle( false );
13377 }
13378 this.menu.toggle( false );
13379 this.menu.selectItem();
13380 this.menu.highlightItem();
13381 };
13382
13383 /**
13384 * @inheritdoc
13385 */
13386 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
13387 var i, len;
13388
13389 // Parent method
13390 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
13391
13392 if ( this.$input ) {
13393 this.$input.prop( 'disabled', this.isDisabled() );
13394 }
13395 if ( this.menu ) {
13396 this.menu.setDisabled( this.isDisabled() );
13397 }
13398 if ( this.popup ) {
13399 this.popup.setDisabled( this.isDisabled() );
13400 }
13401
13402 if ( this.items ) {
13403 for ( i = 0, len = this.items.length; i < len; i++ ) {
13404 this.items[ i ].updateDisabled();
13405 }
13406 }
13407
13408 return this;
13409 };
13410
13411 /**
13412 * Focus the widget
13413 * @chainable
13414 * @return {OO.ui.CapsuleMultiSelectWidget}
13415 */
13416 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
13417 if ( !this.isDisabled() ) {
13418 if ( this.popup ) {
13419 this.popup.setSize( this.$handle.width() );
13420 this.popup.toggle( true );
13421 this.popup.$element.find( '*' )
13422 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
13423 .first()
13424 .focus();
13425 } else {
13426 this.menu.toggle( true );
13427 this.$input.focus();
13428 }
13429 }
13430 return this;
13431 };
13432
13433 /**
13434 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13435 * CapsuleMultiSelectWidget} to display the selected items.
13436 *
13437 * @class
13438 * @extends OO.ui.Widget
13439 * @mixins OO.ui.mixin.ItemWidget
13440 * @mixins OO.ui.mixin.IndicatorElement
13441 * @mixins OO.ui.mixin.LabelElement
13442 * @mixins OO.ui.mixin.FlaggedElement
13443 * @mixins OO.ui.mixin.TabIndexedElement
13444 *
13445 * @constructor
13446 * @param {Object} [config] Configuration options
13447 */
13448 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
13449 // Configuration initialization
13450 config = config || {};
13451
13452 // Parent constructor
13453 OO.ui.CapsuleItemWidget.parent.call( this, config );
13454
13455 // Properties (must be set before mixin constructor calls)
13456 this.$indicator = $( '<span>' );
13457
13458 // Mixin constructors
13459 OO.ui.mixin.ItemWidget.call( this );
13460 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$indicator, indicator: 'clear' } ) );
13461 OO.ui.mixin.LabelElement.call( this, config );
13462 OO.ui.mixin.FlaggedElement.call( this, config );
13463 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13464
13465 // Events
13466 this.$indicator.on( {
13467 keydown: this.onCloseKeyDown.bind( this ),
13468 click: this.onCloseClick.bind( this )
13469 } );
13470 this.$element.on( 'click', false );
13471
13472 // Initialization
13473 this.$element
13474 .addClass( 'oo-ui-capsuleItemWidget' )
13475 .append( this.$indicator, this.$label );
13476 };
13477
13478 /* Setup */
13479
13480 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
13481 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
13482 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.IndicatorElement );
13483 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
13484 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
13485 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
13486
13487 /* Methods */
13488
13489 /**
13490 * Handle close icon clicks
13491 * @param {jQuery.Event} event
13492 */
13493 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
13494 var element = this.getElementGroup();
13495
13496 if ( !this.isDisabled() && element && $.isFunction( element.removeItems ) ) {
13497 element.removeItems( [ this ] );
13498 element.focus();
13499 }
13500 };
13501
13502 /**
13503 * Handle close keyboard events
13504 * @param {jQuery.Event} event Key down event
13505 */
13506 OO.ui.CapsuleItemWidget.prototype.onCloseKeyDown = function ( e ) {
13507 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems ) ) {
13508 switch ( e.which ) {
13509 case OO.ui.Keys.ENTER:
13510 case OO.ui.Keys.BACKSPACE:
13511 case OO.ui.Keys.SPACE:
13512 this.getElementGroup().removeItems( [ this ] );
13513 return false;
13514 }
13515 }
13516 };
13517
13518 /**
13519 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13520 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13521 * users can interact with it.
13522 *
13523 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13524 * OO.ui.DropdownInputWidget instead.
13525 *
13526 * @example
13527 * // Example: A DropdownWidget with a menu that contains three options
13528 * var dropDown = new OO.ui.DropdownWidget( {
13529 * label: 'Dropdown menu: Select a menu option',
13530 * menu: {
13531 * items: [
13532 * new OO.ui.MenuOptionWidget( {
13533 * data: 'a',
13534 * label: 'First'
13535 * } ),
13536 * new OO.ui.MenuOptionWidget( {
13537 * data: 'b',
13538 * label: 'Second'
13539 * } ),
13540 * new OO.ui.MenuOptionWidget( {
13541 * data: 'c',
13542 * label: 'Third'
13543 * } )
13544 * ]
13545 * }
13546 * } );
13547 *
13548 * $( 'body' ).append( dropDown.$element );
13549 *
13550 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13551 *
13552 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13553 *
13554 * @class
13555 * @extends OO.ui.Widget
13556 * @mixins OO.ui.mixin.IconElement
13557 * @mixins OO.ui.mixin.IndicatorElement
13558 * @mixins OO.ui.mixin.LabelElement
13559 * @mixins OO.ui.mixin.TitledElement
13560 * @mixins OO.ui.mixin.TabIndexedElement
13561 *
13562 * @constructor
13563 * @param {Object} [config] Configuration options
13564 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13565 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13566 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13567 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13568 */
13569 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
13570 // Configuration initialization
13571 config = $.extend( { indicator: 'down' }, config );
13572
13573 // Parent constructor
13574 OO.ui.DropdownWidget.parent.call( this, config );
13575
13576 // Properties (must be set before TabIndexedElement constructor call)
13577 this.$handle = this.$( '<span>' );
13578 this.$overlay = config.$overlay || this.$element;
13579
13580 // Mixin constructors
13581 OO.ui.mixin.IconElement.call( this, config );
13582 OO.ui.mixin.IndicatorElement.call( this, config );
13583 OO.ui.mixin.LabelElement.call( this, config );
13584 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
13585 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
13586
13587 // Properties
13588 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( {
13589 widget: this,
13590 $container: this.$element
13591 }, config.menu ) );
13592
13593 // Events
13594 this.$handle.on( {
13595 click: this.onClick.bind( this ),
13596 keypress: this.onKeyPress.bind( this )
13597 } );
13598 this.menu.connect( this, { select: 'onMenuSelect' } );
13599
13600 // Initialization
13601 this.$handle
13602 .addClass( 'oo-ui-dropdownWidget-handle' )
13603 .append( this.$icon, this.$label, this.$indicator );
13604 this.$element
13605 .addClass( 'oo-ui-dropdownWidget' )
13606 .append( this.$handle );
13607 this.$overlay.append( this.menu.$element );
13608 };
13609
13610 /* Setup */
13611
13612 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
13613 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement );
13614 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement );
13615 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement );
13616 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement );
13617 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement );
13618
13619 /* Methods */
13620
13621 /**
13622 * Get the menu.
13623 *
13624 * @return {OO.ui.MenuSelectWidget} Menu of widget
13625 */
13626 OO.ui.DropdownWidget.prototype.getMenu = function () {
13627 return this.menu;
13628 };
13629
13630 /**
13631 * Handles menu select events.
13632 *
13633 * @private
13634 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13635 */
13636 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
13637 var selectedLabel;
13638
13639 if ( !item ) {
13640 this.setLabel( null );
13641 return;
13642 }
13643
13644 selectedLabel = item.getLabel();
13645
13646 // If the label is a DOM element, clone it, because setLabel will append() it
13647 if ( selectedLabel instanceof jQuery ) {
13648 selectedLabel = selectedLabel.clone();
13649 }
13650
13651 this.setLabel( selectedLabel );
13652 };
13653
13654 /**
13655 * Handle mouse click events.
13656 *
13657 * @private
13658 * @param {jQuery.Event} e Mouse click event
13659 */
13660 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
13661 if ( !this.isDisabled() && e.which === 1 ) {
13662 this.menu.toggle();
13663 }
13664 return false;
13665 };
13666
13667 /**
13668 * Handle key press events.
13669 *
13670 * @private
13671 * @param {jQuery.Event} e Key press event
13672 */
13673 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
13674 if ( !this.isDisabled() &&
13675 ( ( e.which === OO.ui.Keys.SPACE && !this.menu.isVisible() ) || e.which === OO.ui.Keys.ENTER )
13676 ) {
13677 this.menu.toggle();
13678 return false;
13679 }
13680 };
13681
13682 /**
13683 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13684 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13685 * OO.ui.mixin.IndicatorElement indicators}.
13686 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13687 *
13688 * @example
13689 * // Example of a file select widget
13690 * var selectFile = new OO.ui.SelectFileWidget();
13691 * $( 'body' ).append( selectFile.$element );
13692 *
13693 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13694 *
13695 * @class
13696 * @extends OO.ui.Widget
13697 * @mixins OO.ui.mixin.IconElement
13698 * @mixins OO.ui.mixin.IndicatorElement
13699 * @mixins OO.ui.mixin.PendingElement
13700 * @mixins OO.ui.mixin.LabelElement
13701 *
13702 * @constructor
13703 * @param {Object} [config] Configuration options
13704 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13705 * @cfg {string} [placeholder] Text to display when no file is selected.
13706 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13707 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13708 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13709 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13710 */
13711 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
13712 var dragHandler;
13713
13714 // TODO: Remove in next release
13715 if ( config && config.dragDropUI ) {
13716 config.showDropTarget = true;
13717 }
13718
13719 // Configuration initialization
13720 config = $.extend( {
13721 accept: null,
13722 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
13723 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
13724 droppable: true,
13725 showDropTarget: false
13726 }, config );
13727
13728 // Parent constructor
13729 OO.ui.SelectFileWidget.parent.call( this, config );
13730
13731 // Mixin constructors
13732 OO.ui.mixin.IconElement.call( this, config );
13733 OO.ui.mixin.IndicatorElement.call( this, config );
13734 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
13735 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { autoFitLabel: true } ) );
13736
13737 // Properties
13738 this.$info = $( '<span>' );
13739
13740 // Properties
13741 this.showDropTarget = config.showDropTarget;
13742 this.isSupported = this.constructor.static.isSupported();
13743 this.currentFile = null;
13744 if ( Array.isArray( config.accept ) ) {
13745 this.accept = config.accept;
13746 } else {
13747 this.accept = null;
13748 }
13749 this.placeholder = config.placeholder;
13750 this.notsupported = config.notsupported;
13751 this.onFileSelectedHandler = this.onFileSelected.bind( this );
13752
13753 this.selectButton = new OO.ui.ButtonWidget( {
13754 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
13755 label: 'Select a file',
13756 disabled: this.disabled || !this.isSupported
13757 } );
13758
13759 this.clearButton = new OO.ui.ButtonWidget( {
13760 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
13761 framed: false,
13762 icon: 'remove',
13763 disabled: this.disabled
13764 } );
13765
13766 // Events
13767 this.selectButton.$button.on( {
13768 keypress: this.onKeyPress.bind( this )
13769 } );
13770 this.clearButton.connect( this, {
13771 click: 'onClearClick'
13772 } );
13773 if ( config.droppable ) {
13774 dragHandler = this.onDragEnterOrOver.bind( this );
13775 this.$element.on( {
13776 dragenter: dragHandler,
13777 dragover: dragHandler,
13778 dragleave: this.onDragLeave.bind( this ),
13779 drop: this.onDrop.bind( this )
13780 } );
13781 }
13782
13783 // Initialization
13784 this.addInput();
13785 this.updateUI();
13786 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
13787 this.$info
13788 .addClass( 'oo-ui-selectFileWidget-info' )
13789 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
13790 this.$element
13791 .addClass( 'oo-ui-selectFileWidget' )
13792 .append( this.$info, this.selectButton.$element );
13793 if ( config.droppable && config.showDropTarget ) {
13794 this.$dropTarget = $( '<div>' )
13795 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
13796 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
13797 .on( {
13798 click: this.onDropTargetClick.bind( this )
13799 } );
13800 this.$element.prepend( this.$dropTarget );
13801 }
13802 };
13803
13804 /* Setup */
13805
13806 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
13807 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
13808 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
13809 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
13810 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
13811
13812 /* Static Properties */
13813
13814 /**
13815 * Check if this widget is supported
13816 *
13817 * @static
13818 * @return {boolean}
13819 */
13820 OO.ui.SelectFileWidget.static.isSupported = function () {
13821 var $input;
13822 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
13823 $input = $( '<input type="file">' );
13824 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
13825 }
13826 return OO.ui.SelectFileWidget.static.isSupportedCache;
13827 };
13828
13829 OO.ui.SelectFileWidget.static.isSupportedCache = null;
13830
13831 /* Events */
13832
13833 /**
13834 * @event change
13835 *
13836 * A change event is emitted when the on/off state of the toggle changes.
13837 *
13838 * @param {File|null} value New value
13839 */
13840
13841 /* Methods */
13842
13843 /**
13844 * Get the current value of the field
13845 *
13846 * @return {File|null}
13847 */
13848 OO.ui.SelectFileWidget.prototype.getValue = function () {
13849 return this.currentFile;
13850 };
13851
13852 /**
13853 * Set the current value of the field
13854 *
13855 * @param {File|null} file File to select
13856 */
13857 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
13858 if ( this.currentFile !== file ) {
13859 this.currentFile = file;
13860 this.updateUI();
13861 this.emit( 'change', this.currentFile );
13862 }
13863 };
13864
13865 /**
13866 * Update the user interface when a file is selected or unselected
13867 *
13868 * @protected
13869 */
13870 OO.ui.SelectFileWidget.prototype.updateUI = function () {
13871 if ( !this.isSupported ) {
13872 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
13873 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13874 this.setLabel( this.notsupported );
13875 } else {
13876 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
13877 if ( this.currentFile ) {
13878 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
13879 this.setLabel( this.currentFile.name +
13880 ( this.currentFile.type !== '' ? OO.ui.msg( 'ooui-semicolon-separator' ) + this.currentFile.type : '' )
13881 );
13882 } else {
13883 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
13884 this.setLabel( this.placeholder );
13885 }
13886 }
13887
13888 if ( this.$input ) {
13889 this.$input.attr( 'title', this.getLabel() );
13890 }
13891 };
13892
13893 /**
13894 * Add the input to the widget
13895 *
13896 * @private
13897 */
13898 OO.ui.SelectFileWidget.prototype.addInput = function () {
13899 if ( this.$input ) {
13900 this.$input.remove();
13901 }
13902
13903 if ( !this.isSupported ) {
13904 this.$input = null;
13905 return;
13906 }
13907
13908 this.$input = $( '<input type="file">' );
13909 this.$input.on( 'change', this.onFileSelectedHandler );
13910 this.$input.attr( {
13911 tabindex: -1,
13912 title: this.getLabel()
13913 } );
13914 if ( this.accept ) {
13915 this.$input.attr( 'accept', this.accept.join( ', ' ) );
13916 }
13917 this.selectButton.$button.append( this.$input );
13918 };
13919
13920 /**
13921 * Determine if we should accept this file
13922 *
13923 * @private
13924 * @param {string} File MIME type
13925 * @return {boolean}
13926 */
13927 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
13928 var i, mimeTest;
13929
13930 if ( !this.accept || !mimeType ) {
13931 return true;
13932 }
13933
13934 for ( i = 0; i < this.accept.length; i++ ) {
13935 mimeTest = this.accept[ i ];
13936 if ( mimeTest === mimeType ) {
13937 return true;
13938 } else if ( mimeTest.substr( -2 ) === '/*' ) {
13939 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
13940 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
13941 return true;
13942 }
13943 }
13944 }
13945
13946 return false;
13947 };
13948
13949 /**
13950 * Handle file selection from the input
13951 *
13952 * @private
13953 * @param {jQuery.Event} e
13954 */
13955 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
13956 var file = OO.getProp( e.target, 'files', 0 ) || null;
13957
13958 if ( file && !this.isAllowedType( file.type ) ) {
13959 file = null;
13960 }
13961
13962 this.setValue( file );
13963 this.addInput();
13964 };
13965
13966 /**
13967 * Handle clear button click events.
13968 *
13969 * @private
13970 */
13971 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
13972 this.setValue( null );
13973 return false;
13974 };
13975
13976 /**
13977 * Handle key press events.
13978 *
13979 * @private
13980 * @param {jQuery.Event} e Key press event
13981 */
13982 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
13983 if ( this.isSupported && !this.isDisabled() && this.$input &&
13984 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
13985 ) {
13986 this.$input.click();
13987 return false;
13988 }
13989 };
13990
13991 /**
13992 * Handle drop target click events.
13993 *
13994 * @private
13995 * @param {jQuery.Event} e Key press event
13996 */
13997 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
13998 if ( this.isSupported && !this.isDisabled() && this.$input ) {
13999 this.$input.click();
14000 return false;
14001 }
14002 };
14003
14004 /**
14005 * Handle drag enter and over events
14006 *
14007 * @private
14008 * @param {jQuery.Event} e Drag event
14009 */
14010 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
14011 var itemOrFile,
14012 droppableFile = false,
14013 dt = e.originalEvent.dataTransfer;
14014
14015 e.preventDefault();
14016 e.stopPropagation();
14017
14018 if ( this.isDisabled() || !this.isSupported ) {
14019 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14020 dt.dropEffect = 'none';
14021 return false;
14022 }
14023
14024 // DataTransferItem and File both have a type property, but in Chrome files
14025 // have no information at this point.
14026 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
14027 if ( itemOrFile ) {
14028 if ( this.isAllowedType( itemOrFile.type ) ) {
14029 droppableFile = true;
14030 }
14031 // dt.types is Array-like, but not an Array
14032 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
14033 // File information is not available at this point for security so just assume
14034 // it is acceptable for now.
14035 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14036 droppableFile = true;
14037 }
14038
14039 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
14040 if ( !droppableFile ) {
14041 dt.dropEffect = 'none';
14042 }
14043
14044 return false;
14045 };
14046
14047 /**
14048 * Handle drag leave events
14049 *
14050 * @private
14051 * @param {jQuery.Event} e Drag event
14052 */
14053 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
14054 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14055 };
14056
14057 /**
14058 * Handle drop events
14059 *
14060 * @private
14061 * @param {jQuery.Event} e Drop event
14062 */
14063 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
14064 var file = null,
14065 dt = e.originalEvent.dataTransfer;
14066
14067 e.preventDefault();
14068 e.stopPropagation();
14069 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14070
14071 if ( this.isDisabled() || !this.isSupported ) {
14072 return false;
14073 }
14074
14075 file = OO.getProp( dt, 'files', 0 );
14076 if ( file && !this.isAllowedType( file.type ) ) {
14077 file = null;
14078 }
14079 if ( file ) {
14080 this.setValue( file );
14081 }
14082
14083 return false;
14084 };
14085
14086 /**
14087 * @inheritdoc
14088 */
14089 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
14090 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
14091 if ( this.selectButton ) {
14092 this.selectButton.setDisabled( disabled );
14093 }
14094 if ( this.clearButton ) {
14095 this.clearButton.setDisabled( disabled );
14096 }
14097 return this;
14098 };
14099
14100 /**
14101 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14102 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14103 * for a list of icons included in the library.
14104 *
14105 * @example
14106 * // An icon widget with a label
14107 * var myIcon = new OO.ui.IconWidget( {
14108 * icon: 'help',
14109 * iconTitle: 'Help'
14110 * } );
14111 * // Create a label.
14112 * var iconLabel = new OO.ui.LabelWidget( {
14113 * label: 'Help'
14114 * } );
14115 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14116 *
14117 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14118 *
14119 * @class
14120 * @extends OO.ui.Widget
14121 * @mixins OO.ui.mixin.IconElement
14122 * @mixins OO.ui.mixin.TitledElement
14123 * @mixins OO.ui.mixin.FlaggedElement
14124 *
14125 * @constructor
14126 * @param {Object} [config] Configuration options
14127 */
14128 OO.ui.IconWidget = function OoUiIconWidget( config ) {
14129 // Configuration initialization
14130 config = config || {};
14131
14132 // Parent constructor
14133 OO.ui.IconWidget.parent.call( this, config );
14134
14135 // Mixin constructors
14136 OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
14137 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14138 OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
14139
14140 // Initialization
14141 this.$element.addClass( 'oo-ui-iconWidget' );
14142 };
14143
14144 /* Setup */
14145
14146 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
14147 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement );
14148 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement );
14149 OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement );
14150
14151 /* Static Properties */
14152
14153 OO.ui.IconWidget.static.tagName = 'span';
14154
14155 /**
14156 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14157 * attention to the status of an item or to clarify the function of a control. For a list of
14158 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14159 *
14160 * @example
14161 * // Example of an indicator widget
14162 * var indicator1 = new OO.ui.IndicatorWidget( {
14163 * indicator: 'alert'
14164 * } );
14165 *
14166 * // Create a fieldset layout to add a label
14167 * var fieldset = new OO.ui.FieldsetLayout();
14168 * fieldset.addItems( [
14169 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14170 * ] );
14171 * $( 'body' ).append( fieldset.$element );
14172 *
14173 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14174 *
14175 * @class
14176 * @extends OO.ui.Widget
14177 * @mixins OO.ui.mixin.IndicatorElement
14178 * @mixins OO.ui.mixin.TitledElement
14179 *
14180 * @constructor
14181 * @param {Object} [config] Configuration options
14182 */
14183 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
14184 // Configuration initialization
14185 config = config || {};
14186
14187 // Parent constructor
14188 OO.ui.IndicatorWidget.parent.call( this, config );
14189
14190 // Mixin constructors
14191 OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
14192 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
14193
14194 // Initialization
14195 this.$element.addClass( 'oo-ui-indicatorWidget' );
14196 };
14197
14198 /* Setup */
14199
14200 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
14201 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement );
14202 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement );
14203
14204 /* Static Properties */
14205
14206 OO.ui.IndicatorWidget.static.tagName = 'span';
14207
14208 /**
14209 * InputWidget is the base class for all input widgets, which
14210 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14211 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14212 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14213 *
14214 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14215 *
14216 * @abstract
14217 * @class
14218 * @extends OO.ui.Widget
14219 * @mixins OO.ui.mixin.FlaggedElement
14220 * @mixins OO.ui.mixin.TabIndexedElement
14221 * @mixins OO.ui.mixin.TitledElement
14222 * @mixins OO.ui.mixin.AccessKeyedElement
14223 *
14224 * @constructor
14225 * @param {Object} [config] Configuration options
14226 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14227 * @cfg {string} [value=''] The value of the input.
14228 * @cfg {string} [accessKey=''] The access key of the input.
14229 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14230 * before it is accepted.
14231 */
14232 OO.ui.InputWidget = function OoUiInputWidget( config ) {
14233 // Configuration initialization
14234 config = config || {};
14235
14236 // Parent constructor
14237 OO.ui.InputWidget.parent.call( this, config );
14238
14239 // Properties
14240 this.$input = this.getInputElement( config );
14241 this.value = '';
14242 this.inputFilter = config.inputFilter;
14243
14244 // Mixin constructors
14245 OO.ui.mixin.FlaggedElement.call( this, config );
14246 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
14247 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14248 OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) );
14249
14250 // Events
14251 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
14252
14253 // Initialization
14254 this.$input
14255 .addClass( 'oo-ui-inputWidget-input' )
14256 .attr( 'name', config.name )
14257 .prop( 'disabled', this.isDisabled() );
14258 this.$element
14259 .addClass( 'oo-ui-inputWidget' )
14260 .append( this.$input );
14261 this.setValue( config.value );
14262 this.setAccessKey( config.accessKey );
14263 };
14264
14265 /* Setup */
14266
14267 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
14268 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement );
14269 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement );
14270 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement );
14271 OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement );
14272
14273 /* Static Properties */
14274
14275 OO.ui.InputWidget.static.supportsSimpleLabel = true;
14276
14277 /* Events */
14278
14279 /**
14280 * @event change
14281 *
14282 * A change event is emitted when the value of the input changes.
14283 *
14284 * @param {string} value
14285 */
14286
14287 /* Methods */
14288
14289 /**
14290 * Get input element.
14291 *
14292 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14293 * different circumstances. The element must have a `value` property (like form elements).
14294 *
14295 * @protected
14296 * @param {Object} config Configuration options
14297 * @return {jQuery} Input element
14298 */
14299 OO.ui.InputWidget.prototype.getInputElement = function () {
14300 return $( '<input>' );
14301 };
14302
14303 /**
14304 * Handle potentially value-changing events.
14305 *
14306 * @private
14307 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14308 */
14309 OO.ui.InputWidget.prototype.onEdit = function () {
14310 var widget = this;
14311 if ( !this.isDisabled() ) {
14312 // Allow the stack to clear so the value will be updated
14313 setTimeout( function () {
14314 widget.setValue( widget.$input.val() );
14315 } );
14316 }
14317 };
14318
14319 /**
14320 * Get the value of the input.
14321 *
14322 * @return {string} Input value
14323 */
14324 OO.ui.InputWidget.prototype.getValue = function () {
14325 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14326 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14327 var value = this.$input.val();
14328 if ( this.value !== value ) {
14329 this.setValue( value );
14330 }
14331 return this.value;
14332 };
14333
14334 /**
14335 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14336 *
14337 * @param {boolean} isRTL
14338 * Direction is right-to-left
14339 */
14340 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
14341 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
14342 };
14343
14344 /**
14345 * Set the value of the input.
14346 *
14347 * @param {string} value New value
14348 * @fires change
14349 * @chainable
14350 */
14351 OO.ui.InputWidget.prototype.setValue = function ( value ) {
14352 value = this.cleanUpValue( value );
14353 // Update the DOM if it has changed. Note that with cleanUpValue, it
14354 // is possible for the DOM value to change without this.value changing.
14355 if ( this.$input.val() !== value ) {
14356 this.$input.val( value );
14357 }
14358 if ( this.value !== value ) {
14359 this.value = value;
14360 this.emit( 'change', this.value );
14361 }
14362 return this;
14363 };
14364
14365 /**
14366 * Set the input's access key.
14367 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14368 *
14369 * @param {string} accessKey Input's access key, use empty string to remove
14370 * @chainable
14371 */
14372 OO.ui.InputWidget.prototype.setAccessKey = function ( accessKey ) {
14373 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
14374
14375 if ( this.accessKey !== accessKey ) {
14376 if ( this.$input ) {
14377 if ( accessKey !== null ) {
14378 this.$input.attr( 'accesskey', accessKey );
14379 } else {
14380 this.$input.removeAttr( 'accesskey' );
14381 }
14382 }
14383 this.accessKey = accessKey;
14384 }
14385
14386 return this;
14387 };
14388
14389 /**
14390 * Clean up incoming value.
14391 *
14392 * Ensures value is a string, and converts undefined and null to empty string.
14393 *
14394 * @private
14395 * @param {string} value Original value
14396 * @return {string} Cleaned up value
14397 */
14398 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
14399 if ( value === undefined || value === null ) {
14400 return '';
14401 } else if ( this.inputFilter ) {
14402 return this.inputFilter( String( value ) );
14403 } else {
14404 return String( value );
14405 }
14406 };
14407
14408 /**
14409 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14410 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14411 * called directly.
14412 */
14413 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
14414 if ( !this.isDisabled() ) {
14415 if ( this.$input.is( ':checkbox, :radio' ) ) {
14416 this.$input.click();
14417 }
14418 if ( this.$input.is( ':input' ) ) {
14419 this.$input[ 0 ].focus();
14420 }
14421 }
14422 };
14423
14424 /**
14425 * @inheritdoc
14426 */
14427 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
14428 OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state );
14429 if ( this.$input ) {
14430 this.$input.prop( 'disabled', this.isDisabled() );
14431 }
14432 return this;
14433 };
14434
14435 /**
14436 * Focus the input.
14437 *
14438 * @chainable
14439 */
14440 OO.ui.InputWidget.prototype.focus = function () {
14441 this.$input[ 0 ].focus();
14442 return this;
14443 };
14444
14445 /**
14446 * Blur the input.
14447 *
14448 * @chainable
14449 */
14450 OO.ui.InputWidget.prototype.blur = function () {
14451 this.$input[ 0 ].blur();
14452 return this;
14453 };
14454
14455 /**
14456 * @inheritdoc
14457 */
14458 OO.ui.InputWidget.prototype.gatherPreInfuseState = function ( node ) {
14459 var
14460 state = OO.ui.InputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14461 $input = state.$input || $( node ).find( '.oo-ui-inputWidget-input' );
14462 state.value = $input.val();
14463 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14464 state.focus = $input.is( ':focus' );
14465 return state;
14466 };
14467
14468 /**
14469 * @inheritdoc
14470 */
14471 OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) {
14472 OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14473 if ( state.value !== undefined && state.value !== this.getValue() ) {
14474 this.setValue( state.value );
14475 }
14476 if ( state.focus ) {
14477 this.focus();
14478 }
14479 };
14480
14481 /**
14482 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14483 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14484 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14485 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14486 * [OOjs UI documentation on MediaWiki] [1] for more information.
14487 *
14488 * @example
14489 * // A ButtonInputWidget rendered as an HTML button, the default.
14490 * var button = new OO.ui.ButtonInputWidget( {
14491 * label: 'Input button',
14492 * icon: 'check',
14493 * value: 'check'
14494 * } );
14495 * $( 'body' ).append( button.$element );
14496 *
14497 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14498 *
14499 * @class
14500 * @extends OO.ui.InputWidget
14501 * @mixins OO.ui.mixin.ButtonElement
14502 * @mixins OO.ui.mixin.IconElement
14503 * @mixins OO.ui.mixin.IndicatorElement
14504 * @mixins OO.ui.mixin.LabelElement
14505 * @mixins OO.ui.mixin.TitledElement
14506 *
14507 * @constructor
14508 * @param {Object} [config] Configuration options
14509 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14510 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14511 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14512 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14513 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14514 */
14515 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
14516 // Configuration initialization
14517 config = $.extend( { type: 'button', useInputTag: false }, config );
14518
14519 // Properties (must be set before parent constructor, which calls #setValue)
14520 this.useInputTag = config.useInputTag;
14521
14522 // Parent constructor
14523 OO.ui.ButtonInputWidget.parent.call( this, config );
14524
14525 // Mixin constructors
14526 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
14527 OO.ui.mixin.IconElement.call( this, config );
14528 OO.ui.mixin.IndicatorElement.call( this, config );
14529 OO.ui.mixin.LabelElement.call( this, config );
14530 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
14531
14532 // Initialization
14533 if ( !config.useInputTag ) {
14534 this.$input.append( this.$icon, this.$label, this.$indicator );
14535 }
14536 this.$element.addClass( 'oo-ui-buttonInputWidget' );
14537 };
14538
14539 /* Setup */
14540
14541 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
14542 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement );
14543 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement );
14544 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement );
14545 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement );
14546 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement );
14547
14548 /* Static Properties */
14549
14550 /**
14551 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14552 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14553 */
14554 OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false;
14555
14556 /* Methods */
14557
14558 /**
14559 * @inheritdoc
14560 * @protected
14561 */
14562 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
14563 var type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ?
14564 config.type :
14565 'button';
14566 return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' );
14567 };
14568
14569 /**
14570 * Set label value.
14571 *
14572 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14573 *
14574 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14575 * text, or `null` for no label
14576 * @chainable
14577 */
14578 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
14579 OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label );
14580
14581 if ( this.useInputTag ) {
14582 if ( typeof label === 'function' ) {
14583 label = OO.ui.resolveMsg( label );
14584 }
14585 if ( label instanceof jQuery ) {
14586 label = label.text();
14587 }
14588 if ( !label ) {
14589 label = '';
14590 }
14591 this.$input.val( label );
14592 }
14593
14594 return this;
14595 };
14596
14597 /**
14598 * Set the value of the input.
14599 *
14600 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14601 * they do not support {@link #value values}.
14602 *
14603 * @param {string} value New value
14604 * @chainable
14605 */
14606 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
14607 if ( !this.useInputTag ) {
14608 OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value );
14609 }
14610 return this;
14611 };
14612
14613 /**
14614 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14615 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14616 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14617 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14618 *
14619 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14620 *
14621 * @example
14622 * // An example of selected, unselected, and disabled checkbox inputs
14623 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14624 * value: 'a',
14625 * selected: true
14626 * } );
14627 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14628 * value: 'b'
14629 * } );
14630 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14631 * value:'c',
14632 * disabled: true
14633 * } );
14634 * // Create a fieldset layout with fields for each checkbox.
14635 * var fieldset = new OO.ui.FieldsetLayout( {
14636 * label: 'Checkboxes'
14637 * } );
14638 * fieldset.addItems( [
14639 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14640 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14641 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14642 * ] );
14643 * $( 'body' ).append( fieldset.$element );
14644 *
14645 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14646 *
14647 * @class
14648 * @extends OO.ui.InputWidget
14649 *
14650 * @constructor
14651 * @param {Object} [config] Configuration options
14652 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14653 */
14654 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
14655 // Configuration initialization
14656 config = config || {};
14657
14658 // Parent constructor
14659 OO.ui.CheckboxInputWidget.parent.call( this, config );
14660
14661 // Initialization
14662 this.$element
14663 .addClass( 'oo-ui-checkboxInputWidget' )
14664 // Required for pretty styling in MediaWiki theme
14665 .append( $( '<span>' ) );
14666 this.setSelected( config.selected !== undefined ? config.selected : false );
14667 };
14668
14669 /* Setup */
14670
14671 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
14672
14673 /* Methods */
14674
14675 /**
14676 * @inheritdoc
14677 * @protected
14678 */
14679 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
14680 return $( '<input type="checkbox" />' );
14681 };
14682
14683 /**
14684 * @inheritdoc
14685 */
14686 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
14687 var widget = this;
14688 if ( !this.isDisabled() ) {
14689 // Allow the stack to clear so the value will be updated
14690 setTimeout( function () {
14691 widget.setSelected( widget.$input.prop( 'checked' ) );
14692 } );
14693 }
14694 };
14695
14696 /**
14697 * Set selection state of this checkbox.
14698 *
14699 * @param {boolean} state `true` for selected
14700 * @chainable
14701 */
14702 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
14703 state = !!state;
14704 if ( this.selected !== state ) {
14705 this.selected = state;
14706 this.$input.prop( 'checked', this.selected );
14707 this.emit( 'change', this.selected );
14708 }
14709 return this;
14710 };
14711
14712 /**
14713 * Check if this checkbox is selected.
14714 *
14715 * @return {boolean} Checkbox is selected
14716 */
14717 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
14718 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14719 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14720 var selected = this.$input.prop( 'checked' );
14721 if ( this.selected !== selected ) {
14722 this.setSelected( selected );
14723 }
14724 return this.selected;
14725 };
14726
14727 /**
14728 * @inheritdoc
14729 */
14730 OO.ui.CheckboxInputWidget.prototype.gatherPreInfuseState = function ( node ) {
14731 var
14732 state = OO.ui.CheckboxInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
14733 $input = $( node ).find( '.oo-ui-inputWidget-input' );
14734 state.$input = $input; // shortcut for performance, used in InputWidget
14735 state.checked = $input.prop( 'checked' );
14736 return state;
14737 };
14738
14739 /**
14740 * @inheritdoc
14741 */
14742 OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) {
14743 OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
14744 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
14745 this.setSelected( state.checked );
14746 }
14747 };
14748
14749 /**
14750 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14751 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14752 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14753 * more information about input widgets.
14754 *
14755 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14756 * are no options. If no `value` configuration option is provided, the first option is selected.
14757 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14758 *
14759 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14760 *
14761 * @example
14762 * // Example: A DropdownInputWidget with three options
14763 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14764 * options: [
14765 * { data: 'a', label: 'First' },
14766 * { data: 'b', label: 'Second'},
14767 * { data: 'c', label: 'Third' }
14768 * ]
14769 * } );
14770 * $( 'body' ).append( dropdownInput.$element );
14771 *
14772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14773 *
14774 * @class
14775 * @extends OO.ui.InputWidget
14776 * @mixins OO.ui.mixin.TitledElement
14777 *
14778 * @constructor
14779 * @param {Object} [config] Configuration options
14780 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14781 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
14782 */
14783 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
14784 // Configuration initialization
14785 config = config || {};
14786
14787 // Properties (must be done before parent constructor which calls #setDisabled)
14788 this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown );
14789
14790 // Parent constructor
14791 OO.ui.DropdownInputWidget.parent.call( this, config );
14792
14793 // Mixin constructors
14794 OO.ui.mixin.TitledElement.call( this, config );
14795
14796 // Events
14797 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
14798
14799 // Initialization
14800 this.setOptions( config.options || [] );
14801 this.$element
14802 .addClass( 'oo-ui-dropdownInputWidget' )
14803 .append( this.dropdownWidget.$element );
14804 };
14805
14806 /* Setup */
14807
14808 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
14809 OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement );
14810
14811 /* Methods */
14812
14813 /**
14814 * @inheritdoc
14815 * @protected
14816 */
14817 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
14818 return $( '<input type="hidden">' );
14819 };
14820
14821 /**
14822 * Handles menu select events.
14823 *
14824 * @private
14825 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14826 */
14827 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
14828 this.setValue( item.getData() );
14829 };
14830
14831 /**
14832 * @inheritdoc
14833 */
14834 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
14835 value = this.cleanUpValue( value );
14836 this.dropdownWidget.getMenu().selectItemByData( value );
14837 OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value );
14838 return this;
14839 };
14840
14841 /**
14842 * @inheritdoc
14843 */
14844 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
14845 this.dropdownWidget.setDisabled( state );
14846 OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state );
14847 return this;
14848 };
14849
14850 /**
14851 * Set the options available for this input.
14852 *
14853 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14854 * @chainable
14855 */
14856 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
14857 var
14858 value = this.getValue(),
14859 widget = this;
14860
14861 // Rebuild the dropdown menu
14862 this.dropdownWidget.getMenu()
14863 .clearItems()
14864 .addItems( options.map( function ( opt ) {
14865 var optValue = widget.cleanUpValue( opt.data );
14866 return new OO.ui.MenuOptionWidget( {
14867 data: optValue,
14868 label: opt.label !== undefined ? opt.label : optValue
14869 } );
14870 } ) );
14871
14872 // Restore the previous value, or reset to something sensible
14873 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
14874 // Previous value is still available, ensure consistency with the dropdown
14875 this.setValue( value );
14876 } else {
14877 // No longer valid, reset
14878 if ( options.length ) {
14879 this.setValue( options[ 0 ].data );
14880 }
14881 }
14882
14883 return this;
14884 };
14885
14886 /**
14887 * @inheritdoc
14888 */
14889 OO.ui.DropdownInputWidget.prototype.focus = function () {
14890 this.dropdownWidget.getMenu().toggle( true );
14891 return this;
14892 };
14893
14894 /**
14895 * @inheritdoc
14896 */
14897 OO.ui.DropdownInputWidget.prototype.blur = function () {
14898 this.dropdownWidget.getMenu().toggle( false );
14899 return this;
14900 };
14901
14902 /**
14903 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14904 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14905 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14906 * please see the [OOjs UI documentation on MediaWiki][1].
14907 *
14908 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14909 *
14910 * @example
14911 * // An example of selected, unselected, and disabled radio inputs
14912 * var radio1 = new OO.ui.RadioInputWidget( {
14913 * value: 'a',
14914 * selected: true
14915 * } );
14916 * var radio2 = new OO.ui.RadioInputWidget( {
14917 * value: 'b'
14918 * } );
14919 * var radio3 = new OO.ui.RadioInputWidget( {
14920 * value: 'c',
14921 * disabled: true
14922 * } );
14923 * // Create a fieldset layout with fields for each radio button.
14924 * var fieldset = new OO.ui.FieldsetLayout( {
14925 * label: 'Radio inputs'
14926 * } );
14927 * fieldset.addItems( [
14928 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14929 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14930 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14931 * ] );
14932 * $( 'body' ).append( fieldset.$element );
14933 *
14934 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14935 *
14936 * @class
14937 * @extends OO.ui.InputWidget
14938 *
14939 * @constructor
14940 * @param {Object} [config] Configuration options
14941 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14942 */
14943 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
14944 // Configuration initialization
14945 config = config || {};
14946
14947 // Parent constructor
14948 OO.ui.RadioInputWidget.parent.call( this, config );
14949
14950 // Initialization
14951 this.$element
14952 .addClass( 'oo-ui-radioInputWidget' )
14953 // Required for pretty styling in MediaWiki theme
14954 .append( $( '<span>' ) );
14955 this.setSelected( config.selected !== undefined ? config.selected : false );
14956 };
14957
14958 /* Setup */
14959
14960 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
14961
14962 /* Methods */
14963
14964 /**
14965 * @inheritdoc
14966 * @protected
14967 */
14968 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
14969 return $( '<input type="radio" />' );
14970 };
14971
14972 /**
14973 * @inheritdoc
14974 */
14975 OO.ui.RadioInputWidget.prototype.onEdit = function () {
14976 // RadioInputWidget doesn't track its state.
14977 };
14978
14979 /**
14980 * Set selection state of this radio button.
14981 *
14982 * @param {boolean} state `true` for selected
14983 * @chainable
14984 */
14985 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
14986 // RadioInputWidget doesn't track its state.
14987 this.$input.prop( 'checked', state );
14988 return this;
14989 };
14990
14991 /**
14992 * Check if this radio button is selected.
14993 *
14994 * @return {boolean} Radio is selected
14995 */
14996 OO.ui.RadioInputWidget.prototype.isSelected = function () {
14997 return this.$input.prop( 'checked' );
14998 };
14999
15000 /**
15001 * @inheritdoc
15002 */
15003 OO.ui.RadioInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15004 var
15005 state = OO.ui.RadioInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15006 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15007 state.$input = $input; // shortcut for performance, used in InputWidget
15008 state.checked = $input.prop( 'checked' );
15009 return state;
15010 };
15011
15012 /**
15013 * @inheritdoc
15014 */
15015 OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) {
15016 OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15017 if ( state.checked !== undefined && state.checked !== this.isSelected() ) {
15018 this.setSelected( state.checked );
15019 }
15020 };
15021
15022 /**
15023 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15024 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15025 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15026 * more information about input widgets.
15027 *
15028 * This and OO.ui.DropdownInputWidget support the same configuration options.
15029 *
15030 * @example
15031 * // Example: A RadioSelectInputWidget with three options
15032 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15033 * options: [
15034 * { data: 'a', label: 'First' },
15035 * { data: 'b', label: 'Second'},
15036 * { data: 'c', label: 'Third' }
15037 * ]
15038 * } );
15039 * $( 'body' ).append( radioSelectInput.$element );
15040 *
15041 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15042 *
15043 * @class
15044 * @extends OO.ui.InputWidget
15045 *
15046 * @constructor
15047 * @param {Object} [config] Configuration options
15048 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15049 */
15050 OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) {
15051 // Configuration initialization
15052 config = config || {};
15053
15054 // Properties (must be done before parent constructor which calls #setDisabled)
15055 this.radioSelectWidget = new OO.ui.RadioSelectWidget();
15056
15057 // Parent constructor
15058 OO.ui.RadioSelectInputWidget.parent.call( this, config );
15059
15060 // Events
15061 this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } );
15062
15063 // Initialization
15064 this.setOptions( config.options || [] );
15065 this.$element
15066 .addClass( 'oo-ui-radioSelectInputWidget' )
15067 .append( this.radioSelectWidget.$element );
15068 };
15069
15070 /* Setup */
15071
15072 OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget );
15073
15074 /* Static Properties */
15075
15076 OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false;
15077
15078 /* Methods */
15079
15080 /**
15081 * @inheritdoc
15082 * @protected
15083 */
15084 OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () {
15085 return $( '<input type="hidden">' );
15086 };
15087
15088 /**
15089 * Handles menu select events.
15090 *
15091 * @private
15092 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15093 */
15094 OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) {
15095 this.setValue( item.getData() );
15096 };
15097
15098 /**
15099 * @inheritdoc
15100 */
15101 OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) {
15102 value = this.cleanUpValue( value );
15103 this.radioSelectWidget.selectItemByData( value );
15104 OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value );
15105 return this;
15106 };
15107
15108 /**
15109 * @inheritdoc
15110 */
15111 OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) {
15112 this.radioSelectWidget.setDisabled( state );
15113 OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state );
15114 return this;
15115 };
15116
15117 /**
15118 * Set the options available for this input.
15119 *
15120 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15121 * @chainable
15122 */
15123 OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) {
15124 var
15125 value = this.getValue(),
15126 widget = this;
15127
15128 // Rebuild the radioSelect menu
15129 this.radioSelectWidget
15130 .clearItems()
15131 .addItems( options.map( function ( opt ) {
15132 var optValue = widget.cleanUpValue( opt.data );
15133 return new OO.ui.RadioOptionWidget( {
15134 data: optValue,
15135 label: opt.label !== undefined ? opt.label : optValue
15136 } );
15137 } ) );
15138
15139 // Restore the previous value, or reset to something sensible
15140 if ( this.radioSelectWidget.getItemFromData( value ) ) {
15141 // Previous value is still available, ensure consistency with the radioSelect
15142 this.setValue( value );
15143 } else {
15144 // No longer valid, reset
15145 if ( options.length ) {
15146 this.setValue( options[ 0 ].data );
15147 }
15148 }
15149
15150 return this;
15151 };
15152
15153 /**
15154 * @inheritdoc
15155 */
15156 OO.ui.RadioSelectInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15157 var state = OO.ui.RadioSelectInputWidget.parent.prototype.gatherPreInfuseState.call( this, node );
15158 state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15159 return state;
15160 };
15161
15162 /**
15163 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15164 * size of the field as well as its presentation. In addition, these widgets can be configured
15165 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15166 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15167 * which modifies incoming values rather than validating them.
15168 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15169 *
15170 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15171 *
15172 * @example
15173 * // Example of a text input widget
15174 * var textInput = new OO.ui.TextInputWidget( {
15175 * value: 'Text input'
15176 * } )
15177 * $( 'body' ).append( textInput.$element );
15178 *
15179 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15180 *
15181 * @class
15182 * @extends OO.ui.InputWidget
15183 * @mixins OO.ui.mixin.IconElement
15184 * @mixins OO.ui.mixin.IndicatorElement
15185 * @mixins OO.ui.mixin.PendingElement
15186 * @mixins OO.ui.mixin.LabelElement
15187 *
15188 * @constructor
15189 * @param {Object} [config] Configuration options
15190 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15191 * 'email' or 'url'. Ignored if `multiline` is true.
15192 *
15193 * Some values of `type` result in additional behaviors:
15194 *
15195 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15196 * empties the text field
15197 * @cfg {string} [placeholder] Placeholder text
15198 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15199 * instruct the browser to focus this widget.
15200 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15201 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15202 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15203 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15204 * specifies minimum number of rows to display.
15205 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15206 * Use the #maxRows config to specify a maximum number of displayed rows.
15207 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15208 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15209 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15210 * the value or placeholder text: `'before'` or `'after'`
15211 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15212 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15213 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15214 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15215 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15216 * value for it to be considered valid; when Function, a function receiving the value as parameter
15217 * that must return true, or promise resolving to true, for it to be considered valid.
15218 */
15219 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
15220 // Configuration initialization
15221 config = $.extend( {
15222 type: 'text',
15223 labelPosition: 'after'
15224 }, config );
15225 if ( config.type === 'search' ) {
15226 if ( config.icon === undefined ) {
15227 config.icon = 'search';
15228 }
15229 // indicator: 'clear' is set dynamically later, depending on value
15230 }
15231 if ( config.required ) {
15232 if ( config.indicator === undefined ) {
15233 config.indicator = 'required';
15234 }
15235 }
15236
15237 // Parent constructor
15238 OO.ui.TextInputWidget.parent.call( this, config );
15239
15240 // Mixin constructors
15241 OO.ui.mixin.IconElement.call( this, config );
15242 OO.ui.mixin.IndicatorElement.call( this, config );
15243 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) );
15244 OO.ui.mixin.LabelElement.call( this, config );
15245
15246 // Properties
15247 this.type = this.getSaneType( config );
15248 this.readOnly = false;
15249 this.multiline = !!config.multiline;
15250 this.autosize = !!config.autosize;
15251 this.minRows = config.rows !== undefined ? config.rows : '';
15252 this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 );
15253 this.validate = null;
15254
15255 // Clone for resizing
15256 if ( this.autosize ) {
15257 this.$clone = this.$input
15258 .clone()
15259 .insertAfter( this.$input )
15260 .attr( 'aria-hidden', 'true' )
15261 .addClass( 'oo-ui-element-hidden' );
15262 }
15263
15264 this.setValidation( config.validate );
15265 this.setLabelPosition( config.labelPosition );
15266
15267 // Events
15268 this.$input.on( {
15269 keypress: this.onKeyPress.bind( this ),
15270 blur: this.onBlur.bind( this )
15271 } );
15272 this.$input.one( {
15273 focus: this.onElementAttach.bind( this )
15274 } );
15275 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
15276 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
15277 this.on( 'labelChange', this.updatePosition.bind( this ) );
15278 this.connect( this, {
15279 change: 'onChange',
15280 disable: 'onDisable'
15281 } );
15282
15283 // Initialization
15284 this.$element
15285 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type )
15286 .append( this.$icon, this.$indicator );
15287 this.setReadOnly( !!config.readOnly );
15288 this.updateSearchIndicator();
15289 if ( config.placeholder ) {
15290 this.$input.attr( 'placeholder', config.placeholder );
15291 }
15292 if ( config.maxLength !== undefined ) {
15293 this.$input.attr( 'maxlength', config.maxLength );
15294 }
15295 if ( config.autofocus ) {
15296 this.$input.attr( 'autofocus', 'autofocus' );
15297 }
15298 if ( config.required ) {
15299 this.$input.attr( 'required', 'required' );
15300 this.$input.attr( 'aria-required', 'true' );
15301 }
15302 if ( config.autocomplete === false ) {
15303 this.$input.attr( 'autocomplete', 'off' );
15304 }
15305 if ( this.multiline && config.rows ) {
15306 this.$input.attr( 'rows', config.rows );
15307 }
15308 if ( this.label || config.autosize ) {
15309 this.installParentChangeDetector();
15310 }
15311 };
15312
15313 /* Setup */
15314
15315 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
15316 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement );
15317 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement );
15318 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement );
15319 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement );
15320
15321 /* Static Properties */
15322
15323 OO.ui.TextInputWidget.static.validationPatterns = {
15324 'non-empty': /.+/,
15325 integer: /^\d+$/
15326 };
15327
15328 /* Events */
15329
15330 /**
15331 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15332 *
15333 * Not emitted if the input is multiline.
15334 *
15335 * @event enter
15336 */
15337
15338 /* Methods */
15339
15340 /**
15341 * Handle icon mouse down events.
15342 *
15343 * @private
15344 * @param {jQuery.Event} e Mouse down event
15345 * @fires icon
15346 */
15347 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
15348 if ( e.which === 1 ) {
15349 this.$input[ 0 ].focus();
15350 return false;
15351 }
15352 };
15353
15354 /**
15355 * Handle indicator mouse down events.
15356 *
15357 * @private
15358 * @param {jQuery.Event} e Mouse down event
15359 * @fires indicator
15360 */
15361 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
15362 if ( e.which === 1 ) {
15363 if ( this.type === 'search' ) {
15364 // Clear the text field
15365 this.setValue( '' );
15366 }
15367 this.$input[ 0 ].focus();
15368 return false;
15369 }
15370 };
15371
15372 /**
15373 * Handle key press events.
15374 *
15375 * @private
15376 * @param {jQuery.Event} e Key press event
15377 * @fires enter If enter key is pressed and input is not multiline
15378 */
15379 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
15380 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
15381 this.emit( 'enter', e );
15382 }
15383 };
15384
15385 /**
15386 * Handle blur events.
15387 *
15388 * @private
15389 * @param {jQuery.Event} e Blur event
15390 */
15391 OO.ui.TextInputWidget.prototype.onBlur = function () {
15392 this.setValidityFlag();
15393 };
15394
15395 /**
15396 * Handle element attach events.
15397 *
15398 * @private
15399 * @param {jQuery.Event} e Element attach event
15400 */
15401 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
15402 // Any previously calculated size is now probably invalid if we reattached elsewhere
15403 this.valCache = null;
15404 this.adjustSize();
15405 this.positionLabel();
15406 };
15407
15408 /**
15409 * Handle change events.
15410 *
15411 * @param {string} value
15412 * @private
15413 */
15414 OO.ui.TextInputWidget.prototype.onChange = function () {
15415 this.updateSearchIndicator();
15416 this.setValidityFlag();
15417 this.adjustSize();
15418 };
15419
15420 /**
15421 * Handle disable events.
15422 *
15423 * @param {boolean} disabled Element is disabled
15424 * @private
15425 */
15426 OO.ui.TextInputWidget.prototype.onDisable = function () {
15427 this.updateSearchIndicator();
15428 };
15429
15430 /**
15431 * Check if the input is {@link #readOnly read-only}.
15432 *
15433 * @return {boolean}
15434 */
15435 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
15436 return this.readOnly;
15437 };
15438
15439 /**
15440 * Set the {@link #readOnly read-only} state of the input.
15441 *
15442 * @param {boolean} state Make input read-only
15443 * @chainable
15444 */
15445 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
15446 this.readOnly = !!state;
15447 this.$input.prop( 'readOnly', this.readOnly );
15448 this.updateSearchIndicator();
15449 return this;
15450 };
15451
15452 /**
15453 * Support function for making #onElementAttach work across browsers.
15454 *
15455 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15456 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15457 *
15458 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15459 * first time that the element gets attached to the documented.
15460 */
15461 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
15462 var mutationObserver, onRemove, topmostNode, fakeParentNode,
15463 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
15464 widget = this;
15465
15466 if ( MutationObserver ) {
15467 // The new way. If only it wasn't so ugly.
15468
15469 if ( this.$element.closest( 'html' ).length ) {
15470 // Widget is attached already, do nothing. This breaks the functionality of this function when
15471 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15472 // would require observation of the whole document, which would hurt performance of other,
15473 // more important code.
15474 return;
15475 }
15476
15477 // Find topmost node in the tree
15478 topmostNode = this.$element[ 0 ];
15479 while ( topmostNode.parentNode ) {
15480 topmostNode = topmostNode.parentNode;
15481 }
15482
15483 // We have no way to detect the $element being attached somewhere without observing the entire
15484 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15485 // parent node of $element, and instead detect when $element is removed from it (and thus
15486 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15487 // doesn't get attached, we end up back here and create the parent.
15488
15489 mutationObserver = new MutationObserver( function ( mutations ) {
15490 var i, j, removedNodes;
15491 for ( i = 0; i < mutations.length; i++ ) {
15492 removedNodes = mutations[ i ].removedNodes;
15493 for ( j = 0; j < removedNodes.length; j++ ) {
15494 if ( removedNodes[ j ] === topmostNode ) {
15495 setTimeout( onRemove, 0 );
15496 return;
15497 }
15498 }
15499 }
15500 } );
15501
15502 onRemove = function () {
15503 // If the node was attached somewhere else, report it
15504 if ( widget.$element.closest( 'html' ).length ) {
15505 widget.onElementAttach();
15506 }
15507 mutationObserver.disconnect();
15508 widget.installParentChangeDetector();
15509 };
15510
15511 // Create a fake parent and observe it
15512 fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ];
15513 mutationObserver.observe( fakeParentNode, { childList: true } );
15514 } else {
15515 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15516 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15517 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
15518 }
15519 };
15520
15521 /**
15522 * Automatically adjust the size of the text input.
15523 *
15524 * This only affects #multiline inputs that are {@link #autosize autosized}.
15525 *
15526 * @chainable
15527 */
15528 OO.ui.TextInputWidget.prototype.adjustSize = function () {
15529 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
15530
15531 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
15532 this.$clone
15533 .val( this.$input.val() )
15534 .attr( 'rows', this.minRows )
15535 // Set inline height property to 0 to measure scroll height
15536 .css( 'height', 0 );
15537
15538 this.$clone.removeClass( 'oo-ui-element-hidden' );
15539
15540 this.valCache = this.$input.val();
15541
15542 scrollHeight = this.$clone[ 0 ].scrollHeight;
15543
15544 // Remove inline height property to measure natural heights
15545 this.$clone.css( 'height', '' );
15546 innerHeight = this.$clone.innerHeight();
15547 outerHeight = this.$clone.outerHeight();
15548
15549 // Measure max rows height
15550 this.$clone
15551 .attr( 'rows', this.maxRows )
15552 .css( 'height', 'auto' )
15553 .val( '' );
15554 maxInnerHeight = this.$clone.innerHeight();
15555
15556 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15557 // Equals 1 on Blink-based browsers and 0 everywhere else
15558 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
15559 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
15560
15561 this.$clone.addClass( 'oo-ui-element-hidden' );
15562
15563 // Only apply inline height when expansion beyond natural height is needed
15564 if ( idealHeight > innerHeight ) {
15565 // Use the difference between the inner and outer height as a buffer
15566 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
15567 } else {
15568 this.$input.css( 'height', '' );
15569 }
15570 }
15571 return this;
15572 };
15573
15574 /**
15575 * @inheritdoc
15576 * @protected
15577 */
15578 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
15579 return config.multiline ?
15580 $( '<textarea>' ) :
15581 $( '<input type="' + this.getSaneType( config ) + '" />' );
15582 };
15583
15584 /**
15585 * Get sanitized value for 'type' for given config.
15586 *
15587 * @param {Object} config Configuration options
15588 * @return {string|null}
15589 * @private
15590 */
15591 OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) {
15592 var type = [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config.type ) !== -1 ?
15593 config.type :
15594 'text';
15595 return config.multiline ? 'multiline' : type;
15596 };
15597
15598 /**
15599 * Check if the input supports multiple lines.
15600 *
15601 * @return {boolean}
15602 */
15603 OO.ui.TextInputWidget.prototype.isMultiline = function () {
15604 return !!this.multiline;
15605 };
15606
15607 /**
15608 * Check if the input automatically adjusts its size.
15609 *
15610 * @return {boolean}
15611 */
15612 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
15613 return !!this.autosize;
15614 };
15615
15616 /**
15617 * Select the entire text of the input.
15618 *
15619 * @chainable
15620 */
15621 OO.ui.TextInputWidget.prototype.select = function () {
15622 this.$input.select();
15623 return this;
15624 };
15625
15626 /**
15627 * Focus the input and move the cursor to the end.
15628 */
15629 OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () {
15630 var textRange,
15631 element = this.$input[ 0 ];
15632 this.focus();
15633 if ( element.selectionStart !== undefined ) {
15634 element.selectionStart = element.selectionEnd = element.value.length;
15635 } else if ( element.createTextRange ) {
15636 // IE 8 and below
15637 textRange = element.createTextRange();
15638 textRange.collapse( false );
15639 textRange.select();
15640 }
15641 };
15642
15643 /**
15644 * Set the validation pattern.
15645 *
15646 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15647 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15648 * value must contain only numbers).
15649 *
15650 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15651 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15652 */
15653 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
15654 if ( validate instanceof RegExp || validate instanceof Function ) {
15655 this.validate = validate;
15656 } else {
15657 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
15658 }
15659 };
15660
15661 /**
15662 * Sets the 'invalid' flag appropriately.
15663 *
15664 * @param {boolean} [isValid] Optionally override validation result
15665 */
15666 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
15667 var widget = this,
15668 setFlag = function ( valid ) {
15669 if ( !valid ) {
15670 widget.$input.attr( 'aria-invalid', 'true' );
15671 } else {
15672 widget.$input.removeAttr( 'aria-invalid' );
15673 }
15674 widget.setFlags( { invalid: !valid } );
15675 };
15676
15677 if ( isValid !== undefined ) {
15678 setFlag( isValid );
15679 } else {
15680 this.getValidity().then( function () {
15681 setFlag( true );
15682 }, function () {
15683 setFlag( false );
15684 } );
15685 }
15686 };
15687
15688 /**
15689 * Check if a value is valid.
15690 *
15691 * This method returns a promise that resolves with a boolean `true` if the current value is
15692 * considered valid according to the supplied {@link #validate validation pattern}.
15693 *
15694 * @deprecated
15695 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15696 */
15697 OO.ui.TextInputWidget.prototype.isValid = function () {
15698 var result;
15699
15700 if ( this.validate instanceof Function ) {
15701 result = this.validate( this.getValue() );
15702 if ( $.isFunction( result.promise ) ) {
15703 return result.promise();
15704 } else {
15705 return $.Deferred().resolve( !!result ).promise();
15706 }
15707 } else {
15708 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
15709 }
15710 };
15711
15712 /**
15713 * Get the validity of current value.
15714 *
15715 * This method returns a promise that resolves if the value is valid and rejects if
15716 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15717 *
15718 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15719 */
15720 OO.ui.TextInputWidget.prototype.getValidity = function () {
15721 var result, promise;
15722
15723 function rejectOrResolve( valid ) {
15724 if ( valid ) {
15725 return $.Deferred().resolve().promise();
15726 } else {
15727 return $.Deferred().reject().promise();
15728 }
15729 }
15730
15731 if ( this.validate instanceof Function ) {
15732 result = this.validate( this.getValue() );
15733
15734 if ( $.isFunction( result.promise ) ) {
15735 promise = $.Deferred();
15736
15737 result.then( function ( valid ) {
15738 if ( valid ) {
15739 promise.resolve();
15740 } else {
15741 promise.reject();
15742 }
15743 }, function () {
15744 promise.reject();
15745 } );
15746
15747 return promise.promise();
15748 } else {
15749 return rejectOrResolve( result );
15750 }
15751 } else {
15752 return rejectOrResolve( this.getValue().match( this.validate ) );
15753 }
15754 };
15755
15756 /**
15757 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15758 *
15759 * @param {string} labelPosition Label position, 'before' or 'after'
15760 * @chainable
15761 */
15762 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
15763 this.labelPosition = labelPosition;
15764 this.updatePosition();
15765 return this;
15766 };
15767
15768 /**
15769 * Deprecated alias of #setLabelPosition
15770 *
15771 * @deprecated Use setLabelPosition instead.
15772 */
15773 OO.ui.TextInputWidget.prototype.setPosition =
15774 OO.ui.TextInputWidget.prototype.setLabelPosition;
15775
15776 /**
15777 * Update the position of the inline label.
15778 *
15779 * This method is called by #setLabelPosition, and can also be called on its own if
15780 * something causes the label to be mispositioned.
15781 *
15782 * @chainable
15783 */
15784 OO.ui.TextInputWidget.prototype.updatePosition = function () {
15785 var after = this.labelPosition === 'after';
15786
15787 this.$element
15788 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
15789 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
15790
15791 this.positionLabel();
15792
15793 return this;
15794 };
15795
15796 /**
15797 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15798 * already empty or when it's not editable.
15799 */
15800 OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () {
15801 if ( this.type === 'search' ) {
15802 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15803 this.setIndicator( null );
15804 } else {
15805 this.setIndicator( 'clear' );
15806 }
15807 }
15808 };
15809
15810 /**
15811 * Position the label by setting the correct padding on the input.
15812 *
15813 * @private
15814 * @chainable
15815 */
15816 OO.ui.TextInputWidget.prototype.positionLabel = function () {
15817 var after, rtl, property;
15818 // Clear old values
15819 this.$input
15820 // Clear old values if present
15821 .css( {
15822 'padding-right': '',
15823 'padding-left': ''
15824 } );
15825
15826 if ( this.label ) {
15827 this.$element.append( this.$label );
15828 } else {
15829 this.$label.detach();
15830 return;
15831 }
15832
15833 after = this.labelPosition === 'after';
15834 rtl = this.$element.css( 'direction' ) === 'rtl';
15835 property = after === rtl ? 'padding-left' : 'padding-right';
15836
15837 this.$input.css( property, this.$label.outerWidth( true ) );
15838
15839 return this;
15840 };
15841
15842 /**
15843 * @inheritdoc
15844 */
15845 OO.ui.TextInputWidget.prototype.gatherPreInfuseState = function ( node ) {
15846 var
15847 state = OO.ui.TextInputWidget.parent.prototype.gatherPreInfuseState.call( this, node ),
15848 $input = $( node ).find( '.oo-ui-inputWidget-input' );
15849 state.$input = $input; // shortcut for performance, used in InputWidget
15850 if ( this.multiline ) {
15851 state.scrollTop = $input.scrollTop();
15852 }
15853 return state;
15854 };
15855
15856 /**
15857 * @inheritdoc
15858 */
15859 OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) {
15860 OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state );
15861 if ( state.scrollTop !== undefined ) {
15862 this.$input.scrollTop( state.scrollTop );
15863 }
15864 };
15865
15866 /**
15867 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15868 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15869 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15870 *
15871 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15872 * option, that option will appear to be selected.
15873 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15874 * input field.
15875 *
15876 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15877 *
15878 * @example
15879 * // Example: A ComboBoxWidget.
15880 * var comboBox = new OO.ui.ComboBoxWidget( {
15881 * label: 'ComboBoxWidget',
15882 * input: { value: 'Option One' },
15883 * menu: {
15884 * items: [
15885 * new OO.ui.MenuOptionWidget( {
15886 * data: 'Option 1',
15887 * label: 'Option One'
15888 * } ),
15889 * new OO.ui.MenuOptionWidget( {
15890 * data: 'Option 2',
15891 * label: 'Option Two'
15892 * } ),
15893 * new OO.ui.MenuOptionWidget( {
15894 * data: 'Option 3',
15895 * label: 'Option Three'
15896 * } ),
15897 * new OO.ui.MenuOptionWidget( {
15898 * data: 'Option 4',
15899 * label: 'Option Four'
15900 * } ),
15901 * new OO.ui.MenuOptionWidget( {
15902 * data: 'Option 5',
15903 * label: 'Option Five'
15904 * } )
15905 * ]
15906 * }
15907 * } );
15908 * $( 'body' ).append( comboBox.$element );
15909 *
15910 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15911 *
15912 * @class
15913 * @extends OO.ui.Widget
15914 * @mixins OO.ui.mixin.TabIndexedElement
15915 *
15916 * @constructor
15917 * @param {Object} [config] Configuration options
15918 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15919 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15920 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15921 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15922 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15923 */
15924 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
15925 // Configuration initialization
15926 config = config || {};
15927
15928 // Parent constructor
15929 OO.ui.ComboBoxWidget.parent.call( this, config );
15930
15931 // Properties (must be set before TabIndexedElement constructor call)
15932 this.$indicator = this.$( '<span>' );
15933
15934 // Mixin constructors
15935 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
15936
15937 // Properties
15938 this.$overlay = config.$overlay || this.$element;
15939 this.input = new OO.ui.TextInputWidget( $.extend(
15940 {
15941 indicator: 'down',
15942 $indicator: this.$indicator,
15943 disabled: this.isDisabled()
15944 },
15945 config.input
15946 ) );
15947 this.input.$input.eq( 0 ).attr( {
15948 role: 'combobox',
15949 'aria-autocomplete': 'list'
15950 } );
15951 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
15952 {
15953 widget: this,
15954 input: this.input,
15955 $container: this.input.$element,
15956 disabled: this.isDisabled()
15957 },
15958 config.menu
15959 ) );
15960
15961 // Events
15962 this.$indicator.on( {
15963 click: this.onClick.bind( this ),
15964 keypress: this.onKeyPress.bind( this )
15965 } );
15966 this.input.connect( this, {
15967 change: 'onInputChange',
15968 enter: 'onInputEnter'
15969 } );
15970 this.menu.connect( this, {
15971 choose: 'onMenuChoose',
15972 add: 'onMenuItemsChange',
15973 remove: 'onMenuItemsChange'
15974 } );
15975
15976 // Initialization
15977 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
15978 this.$overlay.append( this.menu.$element );
15979 this.onMenuItemsChange();
15980 };
15981
15982 /* Setup */
15983
15984 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
15985 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.mixin.TabIndexedElement );
15986
15987 /* Methods */
15988
15989 /**
15990 * Get the combobox's menu.
15991 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
15992 */
15993 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
15994 return this.menu;
15995 };
15996
15997 /**
15998 * Get the combobox's text input widget.
15999 * @return {OO.ui.TextInputWidget} Text input widget
16000 */
16001 OO.ui.ComboBoxWidget.prototype.getInput = function () {
16002 return this.input;
16003 };
16004
16005 /**
16006 * Handle input change events.
16007 *
16008 * @private
16009 * @param {string} value New value
16010 */
16011 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
16012 var match = this.menu.getItemFromData( value );
16013
16014 this.menu.selectItem( match );
16015 if ( this.menu.getHighlightedItem() ) {
16016 this.menu.highlightItem( match );
16017 }
16018
16019 if ( !this.isDisabled() ) {
16020 this.menu.toggle( true );
16021 }
16022 };
16023
16024 /**
16025 * Handle mouse click events.
16026 *
16027 *
16028 * @private
16029 * @param {jQuery.Event} e Mouse click event
16030 */
16031 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
16032 if ( !this.isDisabled() && e.which === 1 ) {
16033 this.menu.toggle();
16034 this.input.$input[ 0 ].focus();
16035 }
16036 return false;
16037 };
16038
16039 /**
16040 * Handle key press events.
16041 *
16042 *
16043 * @private
16044 * @param {jQuery.Event} e Key press event
16045 */
16046 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
16047 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16048 this.menu.toggle();
16049 this.input.$input[ 0 ].focus();
16050 return false;
16051 }
16052 };
16053
16054 /**
16055 * Handle input enter events.
16056 *
16057 * @private
16058 */
16059 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
16060 if ( !this.isDisabled() ) {
16061 this.menu.toggle( false );
16062 }
16063 };
16064
16065 /**
16066 * Handle menu choose events.
16067 *
16068 * @private
16069 * @param {OO.ui.OptionWidget} item Chosen item
16070 */
16071 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
16072 this.input.setValue( item.getData() );
16073 };
16074
16075 /**
16076 * Handle menu item change events.
16077 *
16078 * @private
16079 */
16080 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
16081 var match = this.menu.getItemFromData( this.input.getValue() );
16082 this.menu.selectItem( match );
16083 if ( this.menu.getHighlightedItem() ) {
16084 this.menu.highlightItem( match );
16085 }
16086 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
16087 };
16088
16089 /**
16090 * @inheritdoc
16091 */
16092 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
16093 // Parent method
16094 OO.ui.ComboBoxWidget.parent.prototype.setDisabled.call( this, disabled );
16095
16096 if ( this.input ) {
16097 this.input.setDisabled( this.isDisabled() );
16098 }
16099 if ( this.menu ) {
16100 this.menu.setDisabled( this.isDisabled() );
16101 }
16102
16103 return this;
16104 };
16105
16106 /**
16107 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16108 * be configured with a `label` option that is set to a string, a label node, or a function:
16109 *
16110 * - String: a plaintext string
16111 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16112 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16113 * - Function: a function that will produce a string in the future. Functions are used
16114 * in cases where the value of the label is not currently defined.
16115 *
16116 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16117 * will come into focus when the label is clicked.
16118 *
16119 * @example
16120 * // Examples of LabelWidgets
16121 * var label1 = new OO.ui.LabelWidget( {
16122 * label: 'plaintext label'
16123 * } );
16124 * var label2 = new OO.ui.LabelWidget( {
16125 * label: $( '<a href="default.html">jQuery label</a>' )
16126 * } );
16127 * // Create a fieldset layout with fields for each example
16128 * var fieldset = new OO.ui.FieldsetLayout();
16129 * fieldset.addItems( [
16130 * new OO.ui.FieldLayout( label1 ),
16131 * new OO.ui.FieldLayout( label2 )
16132 * ] );
16133 * $( 'body' ).append( fieldset.$element );
16134 *
16135 *
16136 * @class
16137 * @extends OO.ui.Widget
16138 * @mixins OO.ui.mixin.LabelElement
16139 *
16140 * @constructor
16141 * @param {Object} [config] Configuration options
16142 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16143 * Clicking the label will focus the specified input field.
16144 */
16145 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
16146 // Configuration initialization
16147 config = config || {};
16148
16149 // Parent constructor
16150 OO.ui.LabelWidget.parent.call( this, config );
16151
16152 // Mixin constructors
16153 OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
16154 OO.ui.mixin.TitledElement.call( this, config );
16155
16156 // Properties
16157 this.input = config.input;
16158
16159 // Events
16160 if ( this.input instanceof OO.ui.InputWidget ) {
16161 this.$element.on( 'click', this.onClick.bind( this ) );
16162 }
16163
16164 // Initialization
16165 this.$element.addClass( 'oo-ui-labelWidget' );
16166 };
16167
16168 /* Setup */
16169
16170 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
16171 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement );
16172 OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement );
16173
16174 /* Static Properties */
16175
16176 OO.ui.LabelWidget.static.tagName = 'span';
16177
16178 /* Methods */
16179
16180 /**
16181 * Handles label mouse click events.
16182 *
16183 * @private
16184 * @param {jQuery.Event} e Mouse click event
16185 */
16186 OO.ui.LabelWidget.prototype.onClick = function () {
16187 this.input.simulateLabelClick();
16188 return false;
16189 };
16190
16191 /**
16192 * OptionWidgets are special elements that can be selected and configured with data. The
16193 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16194 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16195 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16196 *
16197 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16198 *
16199 * @class
16200 * @extends OO.ui.Widget
16201 * @mixins OO.ui.mixin.LabelElement
16202 * @mixins OO.ui.mixin.FlaggedElement
16203 *
16204 * @constructor
16205 * @param {Object} [config] Configuration options
16206 */
16207 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
16208 // Configuration initialization
16209 config = config || {};
16210
16211 // Parent constructor
16212 OO.ui.OptionWidget.parent.call( this, config );
16213
16214 // Mixin constructors
16215 OO.ui.mixin.ItemWidget.call( this );
16216 OO.ui.mixin.LabelElement.call( this, config );
16217 OO.ui.mixin.FlaggedElement.call( this, config );
16218
16219 // Properties
16220 this.selected = false;
16221 this.highlighted = false;
16222 this.pressed = false;
16223
16224 // Initialization
16225 this.$element
16226 .data( 'oo-ui-optionWidget', this )
16227 .attr( 'role', 'option' )
16228 .attr( 'aria-selected', 'false' )
16229 .addClass( 'oo-ui-optionWidget' )
16230 .append( this.$label );
16231 };
16232
16233 /* Setup */
16234
16235 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
16236 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget );
16237 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement );
16238 OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement );
16239
16240 /* Static Properties */
16241
16242 OO.ui.OptionWidget.static.selectable = true;
16243
16244 OO.ui.OptionWidget.static.highlightable = true;
16245
16246 OO.ui.OptionWidget.static.pressable = true;
16247
16248 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
16249
16250 /* Methods */
16251
16252 /**
16253 * Check if the option can be selected.
16254 *
16255 * @return {boolean} Item is selectable
16256 */
16257 OO.ui.OptionWidget.prototype.isSelectable = function () {
16258 return this.constructor.static.selectable && !this.isDisabled() && this.isVisible();
16259 };
16260
16261 /**
16262 * Check if the option can be highlighted. A highlight indicates that the option
16263 * may be selected when a user presses enter or clicks. Disabled items cannot
16264 * be highlighted.
16265 *
16266 * @return {boolean} Item is highlightable
16267 */
16268 OO.ui.OptionWidget.prototype.isHighlightable = function () {
16269 return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible();
16270 };
16271
16272 /**
16273 * Check if the option can be pressed. The pressed state occurs when a user mouses
16274 * down on an item, but has not yet let go of the mouse.
16275 *
16276 * @return {boolean} Item is pressable
16277 */
16278 OO.ui.OptionWidget.prototype.isPressable = function () {
16279 return this.constructor.static.pressable && !this.isDisabled() && this.isVisible();
16280 };
16281
16282 /**
16283 * Check if the option is selected.
16284 *
16285 * @return {boolean} Item is selected
16286 */
16287 OO.ui.OptionWidget.prototype.isSelected = function () {
16288 return this.selected;
16289 };
16290
16291 /**
16292 * Check if the option is highlighted. A highlight indicates that the
16293 * item may be selected when a user presses enter or clicks.
16294 *
16295 * @return {boolean} Item is highlighted
16296 */
16297 OO.ui.OptionWidget.prototype.isHighlighted = function () {
16298 return this.highlighted;
16299 };
16300
16301 /**
16302 * Check if the option is pressed. The pressed state occurs when a user mouses
16303 * down on an item, but has not yet let go of the mouse. The item may appear
16304 * selected, but it will not be selected until the user releases the mouse.
16305 *
16306 * @return {boolean} Item is pressed
16307 */
16308 OO.ui.OptionWidget.prototype.isPressed = function () {
16309 return this.pressed;
16310 };
16311
16312 /**
16313 * Set the option’s selected state. In general, all modifications to the selection
16314 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16315 * method instead of this method.
16316 *
16317 * @param {boolean} [state=false] Select option
16318 * @chainable
16319 */
16320 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
16321 if ( this.constructor.static.selectable ) {
16322 this.selected = !!state;
16323 this.$element
16324 .toggleClass( 'oo-ui-optionWidget-selected', state )
16325 .attr( 'aria-selected', state.toString() );
16326 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
16327 this.scrollElementIntoView();
16328 }
16329 this.updateThemeClasses();
16330 }
16331 return this;
16332 };
16333
16334 /**
16335 * Set the option’s highlighted state. In general, all programmatic
16336 * modifications to the highlight should be handled by the
16337 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16338 * method instead of this method.
16339 *
16340 * @param {boolean} [state=false] Highlight option
16341 * @chainable
16342 */
16343 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
16344 if ( this.constructor.static.highlightable ) {
16345 this.highlighted = !!state;
16346 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
16347 this.updateThemeClasses();
16348 }
16349 return this;
16350 };
16351
16352 /**
16353 * Set the option’s pressed state. In general, all
16354 * programmatic modifications to the pressed state should be handled by the
16355 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16356 * method instead of this method.
16357 *
16358 * @param {boolean} [state=false] Press option
16359 * @chainable
16360 */
16361 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
16362 if ( this.constructor.static.pressable ) {
16363 this.pressed = !!state;
16364 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
16365 this.updateThemeClasses();
16366 }
16367 return this;
16368 };
16369
16370 /**
16371 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16372 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16373 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16374 * options. For more information about options and selects, please see the
16375 * [OOjs UI documentation on MediaWiki][1].
16376 *
16377 * @example
16378 * // Decorated options in a select widget
16379 * var select = new OO.ui.SelectWidget( {
16380 * items: [
16381 * new OO.ui.DecoratedOptionWidget( {
16382 * data: 'a',
16383 * label: 'Option with icon',
16384 * icon: 'help'
16385 * } ),
16386 * new OO.ui.DecoratedOptionWidget( {
16387 * data: 'b',
16388 * label: 'Option with indicator',
16389 * indicator: 'next'
16390 * } )
16391 * ]
16392 * } );
16393 * $( 'body' ).append( select.$element );
16394 *
16395 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16396 *
16397 * @class
16398 * @extends OO.ui.OptionWidget
16399 * @mixins OO.ui.mixin.IconElement
16400 * @mixins OO.ui.mixin.IndicatorElement
16401 *
16402 * @constructor
16403 * @param {Object} [config] Configuration options
16404 */
16405 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
16406 // Parent constructor
16407 OO.ui.DecoratedOptionWidget.parent.call( this, config );
16408
16409 // Mixin constructors
16410 OO.ui.mixin.IconElement.call( this, config );
16411 OO.ui.mixin.IndicatorElement.call( this, config );
16412
16413 // Initialization
16414 this.$element
16415 .addClass( 'oo-ui-decoratedOptionWidget' )
16416 .prepend( this.$icon )
16417 .append( this.$indicator );
16418 };
16419
16420 /* Setup */
16421
16422 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
16423 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement );
16424 OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement );
16425
16426 /**
16427 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16428 * can be selected and configured with data. The class is
16429 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16430 * [OOjs UI documentation on MediaWiki] [1] for more information.
16431 *
16432 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16433 *
16434 * @class
16435 * @extends OO.ui.DecoratedOptionWidget
16436 * @mixins OO.ui.mixin.ButtonElement
16437 * @mixins OO.ui.mixin.TabIndexedElement
16438 * @mixins OO.ui.mixin.TitledElement
16439 *
16440 * @constructor
16441 * @param {Object} [config] Configuration options
16442 */
16443 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
16444 // Configuration initialization
16445 config = config || {};
16446
16447 // Parent constructor
16448 OO.ui.ButtonOptionWidget.parent.call( this, config );
16449
16450 // Mixin constructors
16451 OO.ui.mixin.ButtonElement.call( this, config );
16452 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
16453 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
16454 $tabIndexed: this.$button,
16455 tabIndex: -1
16456 } ) );
16457
16458 // Initialization
16459 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
16460 this.$button.append( this.$element.contents() );
16461 this.$element.append( this.$button );
16462 };
16463
16464 /* Setup */
16465
16466 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
16467 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
16468 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
16469 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
16470
16471 /* Static Properties */
16472
16473 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16474 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
16475
16476 OO.ui.ButtonOptionWidget.static.highlightable = false;
16477
16478 /* Methods */
16479
16480 /**
16481 * @inheritdoc
16482 */
16483 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
16484 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
16485
16486 if ( this.constructor.static.selectable ) {
16487 this.setActive( state );
16488 }
16489
16490 return this;
16491 };
16492
16493 /**
16494 * RadioOptionWidget is an option widget that looks like a radio button.
16495 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16496 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16497 *
16498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16499 *
16500 * @class
16501 * @extends OO.ui.OptionWidget
16502 *
16503 * @constructor
16504 * @param {Object} [config] Configuration options
16505 */
16506 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
16507 // Configuration initialization
16508 config = config || {};
16509
16510 // Properties (must be done before parent constructor which calls #setDisabled)
16511 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
16512
16513 // Parent constructor
16514 OO.ui.RadioOptionWidget.parent.call( this, config );
16515
16516 // Events
16517 this.radio.$input.on( 'focus', this.onInputFocus.bind( this ) );
16518
16519 // Initialization
16520 // Remove implicit role, we're handling it ourselves
16521 this.radio.$input.attr( 'role', 'presentation' );
16522 this.$element
16523 .addClass( 'oo-ui-radioOptionWidget' )
16524 .attr( 'role', 'radio' )
16525 .attr( 'aria-checked', 'false' )
16526 .removeAttr( 'aria-selected' )
16527 .prepend( this.radio.$element );
16528 };
16529
16530 /* Setup */
16531
16532 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
16533
16534 /* Static Properties */
16535
16536 OO.ui.RadioOptionWidget.static.highlightable = false;
16537
16538 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
16539
16540 OO.ui.RadioOptionWidget.static.pressable = false;
16541
16542 OO.ui.RadioOptionWidget.static.tagName = 'label';
16543
16544 /* Methods */
16545
16546 /**
16547 * @param {jQuery.Event} e Focus event
16548 * @private
16549 */
16550 OO.ui.RadioOptionWidget.prototype.onInputFocus = function () {
16551 this.radio.$input.blur();
16552 this.$element.parent().focus();
16553 };
16554
16555 /**
16556 * @inheritdoc
16557 */
16558 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
16559 OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state );
16560
16561 this.radio.setSelected( state );
16562 this.$element
16563 .attr( 'aria-checked', state.toString() )
16564 .removeAttr( 'aria-selected' );
16565
16566 return this;
16567 };
16568
16569 /**
16570 * @inheritdoc
16571 */
16572 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
16573 OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled );
16574
16575 this.radio.setDisabled( this.isDisabled() );
16576
16577 return this;
16578 };
16579
16580 /**
16581 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16582 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16583 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16584 *
16585 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16586 *
16587 * @class
16588 * @extends OO.ui.DecoratedOptionWidget
16589 *
16590 * @constructor
16591 * @param {Object} [config] Configuration options
16592 */
16593 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
16594 // Configuration initialization
16595 config = $.extend( { icon: 'check' }, config );
16596
16597 // Parent constructor
16598 OO.ui.MenuOptionWidget.parent.call( this, config );
16599
16600 // Initialization
16601 this.$element
16602 .attr( 'role', 'menuitem' )
16603 .addClass( 'oo-ui-menuOptionWidget' );
16604 };
16605
16606 /* Setup */
16607
16608 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
16609
16610 /* Static Properties */
16611
16612 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
16613
16614 /**
16615 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16616 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16617 *
16618 * @example
16619 * var myDropdown = new OO.ui.DropdownWidget( {
16620 * menu: {
16621 * items: [
16622 * new OO.ui.MenuSectionOptionWidget( {
16623 * label: 'Dogs'
16624 * } ),
16625 * new OO.ui.MenuOptionWidget( {
16626 * data: 'corgi',
16627 * label: 'Welsh Corgi'
16628 * } ),
16629 * new OO.ui.MenuOptionWidget( {
16630 * data: 'poodle',
16631 * label: 'Standard Poodle'
16632 * } ),
16633 * new OO.ui.MenuSectionOptionWidget( {
16634 * label: 'Cats'
16635 * } ),
16636 * new OO.ui.MenuOptionWidget( {
16637 * data: 'lion',
16638 * label: 'Lion'
16639 * } )
16640 * ]
16641 * }
16642 * } );
16643 * $( 'body' ).append( myDropdown.$element );
16644 *
16645 *
16646 * @class
16647 * @extends OO.ui.DecoratedOptionWidget
16648 *
16649 * @constructor
16650 * @param {Object} [config] Configuration options
16651 */
16652 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
16653 // Parent constructor
16654 OO.ui.MenuSectionOptionWidget.parent.call( this, config );
16655
16656 // Initialization
16657 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
16658 };
16659
16660 /* Setup */
16661
16662 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
16663
16664 /* Static Properties */
16665
16666 OO.ui.MenuSectionOptionWidget.static.selectable = false;
16667
16668 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
16669
16670 /**
16671 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16672 *
16673 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16674 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16675 * for an example.
16676 *
16677 * @class
16678 * @extends OO.ui.DecoratedOptionWidget
16679 *
16680 * @constructor
16681 * @param {Object} [config] Configuration options
16682 * @cfg {number} [level] Indentation level
16683 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16684 */
16685 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
16686 // Configuration initialization
16687 config = config || {};
16688
16689 // Parent constructor
16690 OO.ui.OutlineOptionWidget.parent.call( this, config );
16691
16692 // Properties
16693 this.level = 0;
16694 this.movable = !!config.movable;
16695 this.removable = !!config.removable;
16696
16697 // Initialization
16698 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
16699 this.setLevel( config.level );
16700 };
16701
16702 /* Setup */
16703
16704 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
16705
16706 /* Static Properties */
16707
16708 OO.ui.OutlineOptionWidget.static.highlightable = false;
16709
16710 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
16711
16712 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
16713
16714 OO.ui.OutlineOptionWidget.static.levels = 3;
16715
16716 /* Methods */
16717
16718 /**
16719 * Check if item is movable.
16720 *
16721 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16722 *
16723 * @return {boolean} Item is movable
16724 */
16725 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
16726 return this.movable;
16727 };
16728
16729 /**
16730 * Check if item is removable.
16731 *
16732 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16733 *
16734 * @return {boolean} Item is removable
16735 */
16736 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
16737 return this.removable;
16738 };
16739
16740 /**
16741 * Get indentation level.
16742 *
16743 * @return {number} Indentation level
16744 */
16745 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
16746 return this.level;
16747 };
16748
16749 /**
16750 * Set movability.
16751 *
16752 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16753 *
16754 * @param {boolean} movable Item is movable
16755 * @chainable
16756 */
16757 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
16758 this.movable = !!movable;
16759 this.updateThemeClasses();
16760 return this;
16761 };
16762
16763 /**
16764 * Set removability.
16765 *
16766 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16767 *
16768 * @param {boolean} movable Item is removable
16769 * @chainable
16770 */
16771 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
16772 this.removable = !!removable;
16773 this.updateThemeClasses();
16774 return this;
16775 };
16776
16777 /**
16778 * Set indentation level.
16779 *
16780 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16781 * @chainable
16782 */
16783 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
16784 var levels = this.constructor.static.levels,
16785 levelClass = this.constructor.static.levelClass,
16786 i = levels;
16787
16788 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
16789 while ( i-- ) {
16790 if ( this.level === i ) {
16791 this.$element.addClass( levelClass + i );
16792 } else {
16793 this.$element.removeClass( levelClass + i );
16794 }
16795 }
16796 this.updateThemeClasses();
16797
16798 return this;
16799 };
16800
16801 /**
16802 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16803 *
16804 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16805 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16806 * for an example.
16807 *
16808 * @class
16809 * @extends OO.ui.OptionWidget
16810 *
16811 * @constructor
16812 * @param {Object} [config] Configuration options
16813 */
16814 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
16815 // Configuration initialization
16816 config = config || {};
16817
16818 // Parent constructor
16819 OO.ui.TabOptionWidget.parent.call( this, config );
16820
16821 // Initialization
16822 this.$element.addClass( 'oo-ui-tabOptionWidget' );
16823 };
16824
16825 /* Setup */
16826
16827 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
16828
16829 /* Static Properties */
16830
16831 OO.ui.TabOptionWidget.static.highlightable = false;
16832
16833 /**
16834 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16835 * By default, each popup has an anchor that points toward its origin.
16836 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16837 *
16838 * @example
16839 * // A popup widget.
16840 * var popup = new OO.ui.PopupWidget( {
16841 * $content: $( '<p>Hi there!</p>' ),
16842 * padded: true,
16843 * width: 300
16844 * } );
16845 *
16846 * $( 'body' ).append( popup.$element );
16847 * // To display the popup, toggle the visibility to 'true'.
16848 * popup.toggle( true );
16849 *
16850 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16851 *
16852 * @class
16853 * @extends OO.ui.Widget
16854 * @mixins OO.ui.mixin.LabelElement
16855 *
16856 * @constructor
16857 * @param {Object} [config] Configuration options
16858 * @cfg {number} [width=320] Width of popup in pixels
16859 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16860 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16861 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16862 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16863 * popup is leaning towards the right of the screen.
16864 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16865 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16866 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16867 * sentence in the given language.
16868 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16869 * See the [OOjs UI docs on MediaWiki][3] for an example.
16870 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16871 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16872 * @cfg {jQuery} [$content] Content to append to the popup's body
16873 * @cfg {jQuery} [$footer] Content to append to the popup's footer
16874 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16875 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16876 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16877 * for an example.
16878 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16879 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16880 * button.
16881 * @cfg {boolean} [padded] Add padding to the popup's body
16882 */
16883 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
16884 // Configuration initialization
16885 config = config || {};
16886
16887 // Parent constructor
16888 OO.ui.PopupWidget.parent.call( this, config );
16889
16890 // Properties (must be set before ClippableElement constructor call)
16891 this.$body = $( '<div>' );
16892 this.$popup = $( '<div>' );
16893
16894 // Mixin constructors
16895 OO.ui.mixin.LabelElement.call( this, config );
16896 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, {
16897 $clippable: this.$body,
16898 $clippableContainer: this.$popup
16899 } ) );
16900
16901 // Properties
16902 this.$head = $( '<div>' );
16903 this.$footer = $( '<div>' );
16904 this.$anchor = $( '<div>' );
16905 // If undefined, will be computed lazily in updateDimensions()
16906 this.$container = config.$container;
16907 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
16908 this.autoClose = !!config.autoClose;
16909 this.$autoCloseIgnore = config.$autoCloseIgnore;
16910 this.transitionTimeout = null;
16911 this.anchor = null;
16912 this.width = config.width !== undefined ? config.width : 320;
16913 this.height = config.height !== undefined ? config.height : null;
16914 this.setAlignment( config.align );
16915 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
16916 this.onMouseDownHandler = this.onMouseDown.bind( this );
16917 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
16918
16919 // Events
16920 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
16921
16922 // Initialization
16923 this.toggleAnchor( config.anchor === undefined || config.anchor );
16924 this.$body.addClass( 'oo-ui-popupWidget-body' );
16925 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
16926 this.$head
16927 .addClass( 'oo-ui-popupWidget-head' )
16928 .append( this.$label, this.closeButton.$element );
16929 this.$footer.addClass( 'oo-ui-popupWidget-footer' );
16930 if ( !config.head ) {
16931 this.$head.addClass( 'oo-ui-element-hidden' );
16932 }
16933 if ( !config.$footer ) {
16934 this.$footer.addClass( 'oo-ui-element-hidden' );
16935 }
16936 this.$popup
16937 .addClass( 'oo-ui-popupWidget-popup' )
16938 .append( this.$head, this.$body, this.$footer );
16939 this.$element
16940 .addClass( 'oo-ui-popupWidget' )
16941 .append( this.$popup, this.$anchor );
16942 // Move content, which was added to #$element by OO.ui.Widget, to the body
16943 if ( config.$content instanceof jQuery ) {
16944 this.$body.append( config.$content );
16945 }
16946 if ( config.$footer instanceof jQuery ) {
16947 this.$footer.append( config.$footer );
16948 }
16949 if ( config.padded ) {
16950 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
16951 }
16952
16953 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16954 // that reference properties not initialized at that time of parent class construction
16955 // TODO: Find a better way to handle post-constructor setup
16956 this.visible = false;
16957 this.$element.addClass( 'oo-ui-element-hidden' );
16958 };
16959
16960 /* Setup */
16961
16962 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
16963 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement );
16964 OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement );
16965
16966 /* Methods */
16967
16968 /**
16969 * Handles mouse down events.
16970 *
16971 * @private
16972 * @param {MouseEvent} e Mouse down event
16973 */
16974 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
16975 if (
16976 this.isVisible() &&
16977 !$.contains( this.$element[ 0 ], e.target ) &&
16978 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
16979 ) {
16980 this.toggle( false );
16981 }
16982 };
16983
16984 /**
16985 * Bind mouse down listener.
16986 *
16987 * @private
16988 */
16989 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
16990 // Capture clicks outside popup
16991 OO.ui.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
16992 };
16993
16994 /**
16995 * Handles close button click events.
16996 *
16997 * @private
16998 */
16999 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
17000 if ( this.isVisible() ) {
17001 this.toggle( false );
17002 }
17003 };
17004
17005 /**
17006 * Unbind mouse down listener.
17007 *
17008 * @private
17009 */
17010 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
17011 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler );
17012 };
17013
17014 /**
17015 * Handles key down events.
17016 *
17017 * @private
17018 * @param {KeyboardEvent} e Key down event
17019 */
17020 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
17021 if (
17022 e.which === OO.ui.Keys.ESCAPE &&
17023 this.isVisible()
17024 ) {
17025 this.toggle( false );
17026 e.preventDefault();
17027 e.stopPropagation();
17028 }
17029 };
17030
17031 /**
17032 * Bind key down listener.
17033 *
17034 * @private
17035 */
17036 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
17037 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17038 };
17039
17040 /**
17041 * Unbind key down listener.
17042 *
17043 * @private
17044 */
17045 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
17046 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler );
17047 };
17048
17049 /**
17050 * Show, hide, or toggle the visibility of the anchor.
17051 *
17052 * @param {boolean} [show] Show anchor, omit to toggle
17053 */
17054 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
17055 show = show === undefined ? !this.anchored : !!show;
17056
17057 if ( this.anchored !== show ) {
17058 if ( show ) {
17059 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
17060 } else {
17061 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
17062 }
17063 this.anchored = show;
17064 }
17065 };
17066
17067 /**
17068 * Check if the anchor is visible.
17069 *
17070 * @return {boolean} Anchor is visible
17071 */
17072 OO.ui.PopupWidget.prototype.hasAnchor = function () {
17073 return this.anchor;
17074 };
17075
17076 /**
17077 * @inheritdoc
17078 */
17079 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
17080 var change;
17081 show = show === undefined ? !this.isVisible() : !!show;
17082
17083 change = show !== this.isVisible();
17084
17085 // Parent method
17086 OO.ui.PopupWidget.parent.prototype.toggle.call( this, show );
17087
17088 if ( change ) {
17089 if ( show ) {
17090 if ( this.autoClose ) {
17091 this.bindMouseDownListener();
17092 this.bindKeyDownListener();
17093 }
17094 this.updateDimensions();
17095 this.toggleClipping( true );
17096 } else {
17097 this.toggleClipping( false );
17098 if ( this.autoClose ) {
17099 this.unbindMouseDownListener();
17100 this.unbindKeyDownListener();
17101 }
17102 }
17103 }
17104
17105 return this;
17106 };
17107
17108 /**
17109 * Set the size of the popup.
17110 *
17111 * Changing the size may also change the popup's position depending on the alignment.
17112 *
17113 * @param {number} width Width in pixels
17114 * @param {number} height Height in pixels
17115 * @param {boolean} [transition=false] Use a smooth transition
17116 * @chainable
17117 */
17118 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
17119 this.width = width;
17120 this.height = height !== undefined ? height : null;
17121 if ( this.isVisible() ) {
17122 this.updateDimensions( transition );
17123 }
17124 };
17125
17126 /**
17127 * Update the size and position.
17128 *
17129 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17130 * be called automatically.
17131 *
17132 * @param {boolean} [transition=false] Use a smooth transition
17133 * @chainable
17134 */
17135 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
17136 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
17137 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
17138 align = this.align,
17139 widget = this;
17140
17141 if ( !this.$container ) {
17142 // Lazy-initialize $container if not specified in constructor
17143 this.$container = $( this.getClosestScrollableElementContainer() );
17144 }
17145
17146 // Set height and width before measuring things, since it might cause our measurements
17147 // to change (e.g. due to scrollbars appearing or disappearing)
17148 this.$popup.css( {
17149 width: this.width,
17150 height: this.height !== null ? this.height : 'auto'
17151 } );
17152
17153 // If we are in RTL, we need to flip the alignment, unless it is center
17154 if ( align === 'forwards' || align === 'backwards' ) {
17155 if ( this.$container.css( 'direction' ) === 'rtl' ) {
17156 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
17157 } else {
17158 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
17159 }
17160
17161 }
17162
17163 // Compute initial popupOffset based on alignment
17164 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
17165
17166 // Figure out if this will cause the popup to go beyond the edge of the container
17167 originOffset = this.$element.offset().left;
17168 containerLeft = this.$container.offset().left;
17169 containerWidth = this.$container.innerWidth();
17170 containerRight = containerLeft + containerWidth;
17171 popupLeft = popupOffset - this.containerPadding;
17172 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
17173 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
17174 overlapRight = containerRight - ( originOffset + popupRight );
17175
17176 // Adjust offset to make the popup not go beyond the edge, if needed
17177 if ( overlapRight < 0 ) {
17178 popupOffset += overlapRight;
17179 } else if ( overlapLeft < 0 ) {
17180 popupOffset -= overlapLeft;
17181 }
17182
17183 // Adjust offset to avoid anchor being rendered too close to the edge
17184 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17185 // TODO: Find a measurement that works for CSS anchors and image anchors
17186 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
17187 if ( popupOffset + this.width < anchorWidth ) {
17188 popupOffset = anchorWidth - this.width;
17189 } else if ( -popupOffset < anchorWidth ) {
17190 popupOffset = -anchorWidth;
17191 }
17192
17193 // Prevent transition from being interrupted
17194 clearTimeout( this.transitionTimeout );
17195 if ( transition ) {
17196 // Enable transition
17197 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
17198 }
17199
17200 // Position body relative to anchor
17201 this.$popup.css( 'margin-left', popupOffset );
17202
17203 if ( transition ) {
17204 // Prevent transitioning after transition is complete
17205 this.transitionTimeout = setTimeout( function () {
17206 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17207 }, 200 );
17208 } else {
17209 // Prevent transitioning immediately
17210 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
17211 }
17212
17213 // Reevaluate clipping state since we've relocated and resized the popup
17214 this.clip();
17215
17216 return this;
17217 };
17218
17219 /**
17220 * Set popup alignment
17221 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17222 * `backwards` or `forwards`.
17223 */
17224 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
17225 // Validate alignment and transform deprecated values
17226 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
17227 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
17228 } else {
17229 this.align = 'center';
17230 }
17231 };
17232
17233 /**
17234 * Get popup alignment
17235 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17236 * `backwards` or `forwards`.
17237 */
17238 OO.ui.PopupWidget.prototype.getAlignment = function () {
17239 return this.align;
17240 };
17241
17242 /**
17243 * Progress bars visually display the status of an operation, such as a download,
17244 * and can be either determinate or indeterminate:
17245 *
17246 * - **determinate** process bars show the percent of an operation that is complete.
17247 *
17248 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17249 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17250 * not use percentages.
17251 *
17252 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17253 *
17254 * @example
17255 * // Examples of determinate and indeterminate progress bars.
17256 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17257 * progress: 33
17258 * } );
17259 * var progressBar2 = new OO.ui.ProgressBarWidget();
17260 *
17261 * // Create a FieldsetLayout to layout progress bars
17262 * var fieldset = new OO.ui.FieldsetLayout;
17263 * fieldset.addItems( [
17264 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17265 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17266 * ] );
17267 * $( 'body' ).append( fieldset.$element );
17268 *
17269 * @class
17270 * @extends OO.ui.Widget
17271 *
17272 * @constructor
17273 * @param {Object} [config] Configuration options
17274 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17275 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17276 * By default, the progress bar is indeterminate.
17277 */
17278 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
17279 // Configuration initialization
17280 config = config || {};
17281
17282 // Parent constructor
17283 OO.ui.ProgressBarWidget.parent.call( this, config );
17284
17285 // Properties
17286 this.$bar = $( '<div>' );
17287 this.progress = null;
17288
17289 // Initialization
17290 this.setProgress( config.progress !== undefined ? config.progress : false );
17291 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
17292 this.$element
17293 .attr( {
17294 role: 'progressbar',
17295 'aria-valuemin': 0,
17296 'aria-valuemax': 100
17297 } )
17298 .addClass( 'oo-ui-progressBarWidget' )
17299 .append( this.$bar );
17300 };
17301
17302 /* Setup */
17303
17304 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
17305
17306 /* Static Properties */
17307
17308 OO.ui.ProgressBarWidget.static.tagName = 'div';
17309
17310 /* Methods */
17311
17312 /**
17313 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17314 *
17315 * @return {number|boolean} Progress percent
17316 */
17317 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
17318 return this.progress;
17319 };
17320
17321 /**
17322 * Set the percent of the process completed or `false` for an indeterminate process.
17323 *
17324 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17325 */
17326 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
17327 this.progress = progress;
17328
17329 if ( progress !== false ) {
17330 this.$bar.css( 'width', this.progress + '%' );
17331 this.$element.attr( 'aria-valuenow', this.progress );
17332 } else {
17333 this.$bar.css( 'width', '' );
17334 this.$element.removeAttr( 'aria-valuenow' );
17335 }
17336 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
17337 };
17338
17339 /**
17340 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17341 * and a menu of search results, which is displayed beneath the query
17342 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17343 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17344 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17345 *
17346 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17347 * the [OOjs UI demos][1] for an example.
17348 *
17349 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17350 *
17351 * @class
17352 * @extends OO.ui.Widget
17353 *
17354 * @constructor
17355 * @param {Object} [config] Configuration options
17356 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17357 * @cfg {string} [value] Initial query value
17358 */
17359 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
17360 // Configuration initialization
17361 config = config || {};
17362
17363 // Parent constructor
17364 OO.ui.SearchWidget.parent.call( this, config );
17365
17366 // Properties
17367 this.query = new OO.ui.TextInputWidget( {
17368 icon: 'search',
17369 placeholder: config.placeholder,
17370 value: config.value
17371 } );
17372 this.results = new OO.ui.SelectWidget();
17373 this.$query = $( '<div>' );
17374 this.$results = $( '<div>' );
17375
17376 // Events
17377 this.query.connect( this, {
17378 change: 'onQueryChange',
17379 enter: 'onQueryEnter'
17380 } );
17381 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
17382
17383 // Initialization
17384 this.$query
17385 .addClass( 'oo-ui-searchWidget-query' )
17386 .append( this.query.$element );
17387 this.$results
17388 .addClass( 'oo-ui-searchWidget-results' )
17389 .append( this.results.$element );
17390 this.$element
17391 .addClass( 'oo-ui-searchWidget' )
17392 .append( this.$results, this.$query );
17393 };
17394
17395 /* Setup */
17396
17397 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
17398
17399 /* Methods */
17400
17401 /**
17402 * Handle query key down events.
17403 *
17404 * @private
17405 * @param {jQuery.Event} e Key down event
17406 */
17407 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
17408 var highlightedItem, nextItem,
17409 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
17410
17411 if ( dir ) {
17412 highlightedItem = this.results.getHighlightedItem();
17413 if ( !highlightedItem ) {
17414 highlightedItem = this.results.getSelectedItem();
17415 }
17416 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
17417 this.results.highlightItem( nextItem );
17418 nextItem.scrollElementIntoView();
17419 }
17420 };
17421
17422 /**
17423 * Handle select widget select events.
17424 *
17425 * Clears existing results. Subclasses should repopulate items according to new query.
17426 *
17427 * @private
17428 * @param {string} value New value
17429 */
17430 OO.ui.SearchWidget.prototype.onQueryChange = function () {
17431 // Reset
17432 this.results.clearItems();
17433 };
17434
17435 /**
17436 * Handle select widget enter key events.
17437 *
17438 * Chooses highlighted item.
17439 *
17440 * @private
17441 * @param {string} value New value
17442 */
17443 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
17444 // Reset
17445 this.results.chooseItem( this.results.getHighlightedItem() );
17446 };
17447
17448 /**
17449 * Get the query input.
17450 *
17451 * @return {OO.ui.TextInputWidget} Query input
17452 */
17453 OO.ui.SearchWidget.prototype.getQuery = function () {
17454 return this.query;
17455 };
17456
17457 /**
17458 * Get the search results menu.
17459 *
17460 * @return {OO.ui.SelectWidget} Menu of search results
17461 */
17462 OO.ui.SearchWidget.prototype.getResults = function () {
17463 return this.results;
17464 };
17465
17466 /**
17467 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17468 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17469 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17470 * menu selects}.
17471 *
17472 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17473 * information, please see the [OOjs UI documentation on MediaWiki][1].
17474 *
17475 * @example
17476 * // Example of a select widget with three options
17477 * var select = new OO.ui.SelectWidget( {
17478 * items: [
17479 * new OO.ui.OptionWidget( {
17480 * data: 'a',
17481 * label: 'Option One',
17482 * } ),
17483 * new OO.ui.OptionWidget( {
17484 * data: 'b',
17485 * label: 'Option Two',
17486 * } ),
17487 * new OO.ui.OptionWidget( {
17488 * data: 'c',
17489 * label: 'Option Three',
17490 * } )
17491 * ]
17492 * } );
17493 * $( 'body' ).append( select.$element );
17494 *
17495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17496 *
17497 * @abstract
17498 * @class
17499 * @extends OO.ui.Widget
17500 * @mixins OO.ui.mixin.GroupWidget
17501 *
17502 * @constructor
17503 * @param {Object} [config] Configuration options
17504 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17505 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17506 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17507 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17508 */
17509 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
17510 // Configuration initialization
17511 config = config || {};
17512
17513 // Parent constructor
17514 OO.ui.SelectWidget.parent.call( this, config );
17515
17516 // Mixin constructors
17517 OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
17518
17519 // Properties
17520 this.pressed = false;
17521 this.selecting = null;
17522 this.onMouseUpHandler = this.onMouseUp.bind( this );
17523 this.onMouseMoveHandler = this.onMouseMove.bind( this );
17524 this.onKeyDownHandler = this.onKeyDown.bind( this );
17525 this.onKeyPressHandler = this.onKeyPress.bind( this );
17526 this.keyPressBuffer = '';
17527 this.keyPressBufferTimer = null;
17528
17529 // Events
17530 this.connect( this, {
17531 toggle: 'onToggle'
17532 } );
17533 this.$element.on( {
17534 mousedown: this.onMouseDown.bind( this ),
17535 mouseover: this.onMouseOver.bind( this ),
17536 mouseleave: this.onMouseLeave.bind( this )
17537 } );
17538
17539 // Initialization
17540 this.$element
17541 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17542 .attr( 'role', 'listbox' );
17543 if ( Array.isArray( config.items ) ) {
17544 this.addItems( config.items );
17545 }
17546 };
17547
17548 /* Setup */
17549
17550 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
17551
17552 // Need to mixin base class as well
17553 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupElement );
17554 OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget );
17555
17556 /* Static */
17557 OO.ui.SelectWidget.static.passAllFilter = function () {
17558 return true;
17559 };
17560
17561 /* Events */
17562
17563 /**
17564 * @event highlight
17565 *
17566 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17567 *
17568 * @param {OO.ui.OptionWidget|null} item Highlighted item
17569 */
17570
17571 /**
17572 * @event press
17573 *
17574 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17575 * pressed state of an option.
17576 *
17577 * @param {OO.ui.OptionWidget|null} item Pressed item
17578 */
17579
17580 /**
17581 * @event select
17582 *
17583 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17584 *
17585 * @param {OO.ui.OptionWidget|null} item Selected item
17586 */
17587
17588 /**
17589 * @event choose
17590 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17591 * @param {OO.ui.OptionWidget} item Chosen item
17592 */
17593
17594 /**
17595 * @event add
17596 *
17597 * An `add` event is emitted when options are added to the select with the #addItems method.
17598 *
17599 * @param {OO.ui.OptionWidget[]} items Added items
17600 * @param {number} index Index of insertion point
17601 */
17602
17603 /**
17604 * @event remove
17605 *
17606 * A `remove` event is emitted when options are removed from the select with the #clearItems
17607 * or #removeItems methods.
17608 *
17609 * @param {OO.ui.OptionWidget[]} items Removed items
17610 */
17611
17612 /* Methods */
17613
17614 /**
17615 * Handle mouse down events.
17616 *
17617 * @private
17618 * @param {jQuery.Event} e Mouse down event
17619 */
17620 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
17621 var item;
17622
17623 if ( !this.isDisabled() && e.which === 1 ) {
17624 this.togglePressed( true );
17625 item = this.getTargetItem( e );
17626 if ( item && item.isSelectable() ) {
17627 this.pressItem( item );
17628 this.selecting = item;
17629 OO.ui.addCaptureEventListener(
17630 this.getElementDocument(),
17631 'mouseup',
17632 this.onMouseUpHandler
17633 );
17634 OO.ui.addCaptureEventListener(
17635 this.getElementDocument(),
17636 'mousemove',
17637 this.onMouseMoveHandler
17638 );
17639 }
17640 }
17641 return false;
17642 };
17643
17644 /**
17645 * Handle mouse up events.
17646 *
17647 * @private
17648 * @param {jQuery.Event} e Mouse up event
17649 */
17650 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
17651 var item;
17652
17653 this.togglePressed( false );
17654 if ( !this.selecting ) {
17655 item = this.getTargetItem( e );
17656 if ( item && item.isSelectable() ) {
17657 this.selecting = item;
17658 }
17659 }
17660 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
17661 this.pressItem( null );
17662 this.chooseItem( this.selecting );
17663 this.selecting = null;
17664 }
17665
17666 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17667 this.onMouseUpHandler );
17668 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17669 this.onMouseMoveHandler );
17670
17671 return false;
17672 };
17673
17674 /**
17675 * Handle mouse move events.
17676 *
17677 * @private
17678 * @param {jQuery.Event} e Mouse move event
17679 */
17680 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
17681 var item;
17682
17683 if ( !this.isDisabled() && this.pressed ) {
17684 item = this.getTargetItem( e );
17685 if ( item && item !== this.selecting && item.isSelectable() ) {
17686 this.pressItem( item );
17687 this.selecting = item;
17688 }
17689 }
17690 return false;
17691 };
17692
17693 /**
17694 * Handle mouse over events.
17695 *
17696 * @private
17697 * @param {jQuery.Event} e Mouse over event
17698 */
17699 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
17700 var item;
17701
17702 if ( !this.isDisabled() ) {
17703 item = this.getTargetItem( e );
17704 this.highlightItem( item && item.isHighlightable() ? item : null );
17705 }
17706 return false;
17707 };
17708
17709 /**
17710 * Handle mouse leave events.
17711 *
17712 * @private
17713 * @param {jQuery.Event} e Mouse over event
17714 */
17715 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
17716 if ( !this.isDisabled() ) {
17717 this.highlightItem( null );
17718 }
17719 return false;
17720 };
17721
17722 /**
17723 * Handle key down events.
17724 *
17725 * @protected
17726 * @param {jQuery.Event} e Key down event
17727 */
17728 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
17729 var nextItem,
17730 handled = false,
17731 currentItem = this.getHighlightedItem() || this.getSelectedItem();
17732
17733 if ( !this.isDisabled() && this.isVisible() ) {
17734 switch ( e.keyCode ) {
17735 case OO.ui.Keys.ENTER:
17736 if ( currentItem && currentItem.constructor.static.highlightable ) {
17737 // Was only highlighted, now let's select it. No-op if already selected.
17738 this.chooseItem( currentItem );
17739 handled = true;
17740 }
17741 break;
17742 case OO.ui.Keys.UP:
17743 case OO.ui.Keys.LEFT:
17744 this.clearKeyPressBuffer();
17745 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
17746 handled = true;
17747 break;
17748 case OO.ui.Keys.DOWN:
17749 case OO.ui.Keys.RIGHT:
17750 this.clearKeyPressBuffer();
17751 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
17752 handled = true;
17753 break;
17754 case OO.ui.Keys.ESCAPE:
17755 case OO.ui.Keys.TAB:
17756 if ( currentItem && currentItem.constructor.static.highlightable ) {
17757 currentItem.setHighlighted( false );
17758 }
17759 this.unbindKeyDownListener();
17760 this.unbindKeyPressListener();
17761 // Don't prevent tabbing away / defocusing
17762 handled = false;
17763 break;
17764 }
17765
17766 if ( nextItem ) {
17767 if ( nextItem.constructor.static.highlightable ) {
17768 this.highlightItem( nextItem );
17769 } else {
17770 this.chooseItem( nextItem );
17771 }
17772 nextItem.scrollElementIntoView();
17773 }
17774
17775 if ( handled ) {
17776 // Can't just return false, because e is not always a jQuery event
17777 e.preventDefault();
17778 e.stopPropagation();
17779 }
17780 }
17781 };
17782
17783 /**
17784 * Bind key down listener.
17785 *
17786 * @protected
17787 */
17788 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
17789 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17790 };
17791
17792 /**
17793 * Unbind key down listener.
17794 *
17795 * @protected
17796 */
17797 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
17798 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler );
17799 };
17800
17801 /**
17802 * Clear the key-press buffer
17803 *
17804 * @protected
17805 */
17806 OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () {
17807 if ( this.keyPressBufferTimer ) {
17808 clearTimeout( this.keyPressBufferTimer );
17809 this.keyPressBufferTimer = null;
17810 }
17811 this.keyPressBuffer = '';
17812 };
17813
17814 /**
17815 * Handle key press events.
17816 *
17817 * @protected
17818 * @param {jQuery.Event} e Key press event
17819 */
17820 OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) {
17821 var c, filter, item;
17822
17823 if ( !e.charCode ) {
17824 if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) {
17825 this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 );
17826 return false;
17827 }
17828 return;
17829 }
17830 if ( String.fromCodePoint ) {
17831 c = String.fromCodePoint( e.charCode );
17832 } else {
17833 c = String.fromCharCode( e.charCode );
17834 }
17835
17836 if ( this.keyPressBufferTimer ) {
17837 clearTimeout( this.keyPressBufferTimer );
17838 }
17839 this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 );
17840
17841 item = this.getHighlightedItem() || this.getSelectedItem();
17842
17843 if ( this.keyPressBuffer === c ) {
17844 // Common (if weird) special case: typing "xxxx" will cycle through all
17845 // the items beginning with "x".
17846 if ( item ) {
17847 item = this.getRelativeSelectableItem( item, 1 );
17848 }
17849 } else {
17850 this.keyPressBuffer += c;
17851 }
17852
17853 filter = this.getItemMatcher( this.keyPressBuffer, false );
17854 if ( !item || !filter( item ) ) {
17855 item = this.getRelativeSelectableItem( item, 1, filter );
17856 }
17857 if ( item ) {
17858 if ( item.constructor.static.highlightable ) {
17859 this.highlightItem( item );
17860 } else {
17861 this.chooseItem( item );
17862 }
17863 item.scrollElementIntoView();
17864 }
17865
17866 return false;
17867 };
17868
17869 /**
17870 * Get a matcher for the specific string
17871 *
17872 * @protected
17873 * @param {string} s String to match against items
17874 * @param {boolean} [exact=false] Only accept exact matches
17875 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17876 */
17877 OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) {
17878 var re;
17879
17880 if ( s.normalize ) {
17881 s = s.normalize();
17882 }
17883 s = exact ? s.trim() : s.replace( /^\s+/, '' );
17884 re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17885 if ( exact ) {
17886 re += '\\s*$';
17887 }
17888 re = new RegExp( re, 'i' );
17889 return function ( item ) {
17890 var l = item.getLabel();
17891 if ( typeof l !== 'string' ) {
17892 l = item.$label.text();
17893 }
17894 if ( l.normalize ) {
17895 l = l.normalize();
17896 }
17897 return re.test( l );
17898 };
17899 };
17900
17901 /**
17902 * Bind key press listener.
17903 *
17904 * @protected
17905 */
17906 OO.ui.SelectWidget.prototype.bindKeyPressListener = function () {
17907 OO.ui.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17908 };
17909
17910 /**
17911 * Unbind key down listener.
17912 *
17913 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17914 * implementation.
17915 *
17916 * @protected
17917 */
17918 OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () {
17919 OO.ui.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler );
17920 this.clearKeyPressBuffer();
17921 };
17922
17923 /**
17924 * Visibility change handler
17925 *
17926 * @protected
17927 * @param {boolean} visible
17928 */
17929 OO.ui.SelectWidget.prototype.onToggle = function ( visible ) {
17930 if ( !visible ) {
17931 this.clearKeyPressBuffer();
17932 }
17933 };
17934
17935 /**
17936 * Get the closest item to a jQuery.Event.
17937 *
17938 * @private
17939 * @param {jQuery.Event} e
17940 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17941 */
17942 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
17943 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17944 };
17945
17946 /**
17947 * Get selected item.
17948 *
17949 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17950 */
17951 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
17952 var i, len;
17953
17954 for ( i = 0, len = this.items.length; i < len; i++ ) {
17955 if ( this.items[ i ].isSelected() ) {
17956 return this.items[ i ];
17957 }
17958 }
17959 return null;
17960 };
17961
17962 /**
17963 * Get highlighted item.
17964 *
17965 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17966 */
17967 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
17968 var i, len;
17969
17970 for ( i = 0, len = this.items.length; i < len; i++ ) {
17971 if ( this.items[ i ].isHighlighted() ) {
17972 return this.items[ i ];
17973 }
17974 }
17975 return null;
17976 };
17977
17978 /**
17979 * Toggle pressed state.
17980 *
17981 * Press is a state that occurs when a user mouses down on an item, but
17982 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17983 * until the user releases the mouse.
17984 *
17985 * @param {boolean} pressed An option is being pressed
17986 */
17987 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
17988 if ( pressed === undefined ) {
17989 pressed = !this.pressed;
17990 }
17991 if ( pressed !== this.pressed ) {
17992 this.$element
17993 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
17994 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
17995 this.pressed = pressed;
17996 }
17997 };
17998
17999 /**
18000 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18001 * and any existing highlight will be removed. The highlight is mutually exclusive.
18002 *
18003 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18004 * @fires highlight
18005 * @chainable
18006 */
18007 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
18008 var i, len, highlighted,
18009 changed = false;
18010
18011 for ( i = 0, len = this.items.length; i < len; i++ ) {
18012 highlighted = this.items[ i ] === item;
18013 if ( this.items[ i ].isHighlighted() !== highlighted ) {
18014 this.items[ i ].setHighlighted( highlighted );
18015 changed = true;
18016 }
18017 }
18018 if ( changed ) {
18019 this.emit( 'highlight', item );
18020 }
18021
18022 return this;
18023 };
18024
18025 /**
18026 * Fetch an item by its label.
18027 *
18028 * @param {string} label Label of the item to select.
18029 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18030 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18031 */
18032 OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) {
18033 var i, item, found,
18034 len = this.items.length,
18035 filter = this.getItemMatcher( label, true );
18036
18037 for ( i = 0; i < len; i++ ) {
18038 item = this.items[ i ];
18039 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18040 return item;
18041 }
18042 }
18043
18044 if ( prefix ) {
18045 found = null;
18046 filter = this.getItemMatcher( label, false );
18047 for ( i = 0; i < len; i++ ) {
18048 item = this.items[ i ];
18049 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18050 if ( found ) {
18051 return null;
18052 }
18053 found = item;
18054 }
18055 }
18056 if ( found ) {
18057 return found;
18058 }
18059 }
18060
18061 return null;
18062 };
18063
18064 /**
18065 * Programmatically select an option by its label. If the item does not exist,
18066 * all options will be deselected.
18067 *
18068 * @param {string} [label] Label of the item to select.
18069 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18070 * @fires select
18071 * @chainable
18072 */
18073 OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) {
18074 var itemFromLabel = this.getItemFromLabel( label, !!prefix );
18075 if ( label === undefined || !itemFromLabel ) {
18076 return this.selectItem();
18077 }
18078 return this.selectItem( itemFromLabel );
18079 };
18080
18081 /**
18082 * Programmatically select an option by its data. If the `data` parameter is omitted,
18083 * or if the item does not exist, all options will be deselected.
18084 *
18085 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18086 * @fires select
18087 * @chainable
18088 */
18089 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
18090 var itemFromData = this.getItemFromData( data );
18091 if ( data === undefined || !itemFromData ) {
18092 return this.selectItem();
18093 }
18094 return this.selectItem( itemFromData );
18095 };
18096
18097 /**
18098 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18099 * all options will be deselected.
18100 *
18101 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18102 * @fires select
18103 * @chainable
18104 */
18105 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
18106 var i, len, selected,
18107 changed = false;
18108
18109 for ( i = 0, len = this.items.length; i < len; i++ ) {
18110 selected = this.items[ i ] === item;
18111 if ( this.items[ i ].isSelected() !== selected ) {
18112 this.items[ i ].setSelected( selected );
18113 changed = true;
18114 }
18115 }
18116 if ( changed ) {
18117 this.emit( 'select', item );
18118 }
18119
18120 return this;
18121 };
18122
18123 /**
18124 * Press an item.
18125 *
18126 * Press is a state that occurs when a user mouses down on an item, but has not
18127 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18128 * releases the mouse.
18129 *
18130 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18131 * @fires press
18132 * @chainable
18133 */
18134 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
18135 var i, len, pressed,
18136 changed = false;
18137
18138 for ( i = 0, len = this.items.length; i < len; i++ ) {
18139 pressed = this.items[ i ] === item;
18140 if ( this.items[ i ].isPressed() !== pressed ) {
18141 this.items[ i ].setPressed( pressed );
18142 changed = true;
18143 }
18144 }
18145 if ( changed ) {
18146 this.emit( 'press', item );
18147 }
18148
18149 return this;
18150 };
18151
18152 /**
18153 * Choose an item.
18154 *
18155 * Note that ‘choose’ should never be modified programmatically. A user can choose
18156 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18157 * use the #selectItem method.
18158 *
18159 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18160 * when users choose an item with the keyboard or mouse.
18161 *
18162 * @param {OO.ui.OptionWidget} item Item to choose
18163 * @fires choose
18164 * @chainable
18165 */
18166 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
18167 this.selectItem( item );
18168 this.emit( 'choose', item );
18169
18170 return this;
18171 };
18172
18173 /**
18174 * Get an option by its position relative to the specified item (or to the start of the option array,
18175 * if item is `null`). The direction in which to search through the option array is specified with a
18176 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18177 * `null` if there are no options in the array.
18178 *
18179 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18180 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18181 * @param {Function} filter Only consider items for which this function returns
18182 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18183 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18184 */
18185 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) {
18186 var currentIndex, nextIndex, i,
18187 increase = direction > 0 ? 1 : -1,
18188 len = this.items.length;
18189
18190 if ( !$.isFunction( filter ) ) {
18191 filter = OO.ui.SelectWidget.static.passAllFilter;
18192 }
18193
18194 if ( item instanceof OO.ui.OptionWidget ) {
18195 currentIndex = this.items.indexOf( item );
18196 nextIndex = ( currentIndex + increase + len ) % len;
18197 } else {
18198 // If no item is selected and moving forward, start at the beginning.
18199 // If moving backward, start at the end.
18200 nextIndex = direction > 0 ? 0 : len - 1;
18201 }
18202
18203 for ( i = 0; i < len; i++ ) {
18204 item = this.items[ nextIndex ];
18205 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) {
18206 return item;
18207 }
18208 nextIndex = ( nextIndex + increase + len ) % len;
18209 }
18210 return null;
18211 };
18212
18213 /**
18214 * Get the next selectable item or `null` if there are no selectable items.
18215 * Disabled options and menu-section markers and breaks are not selectable.
18216 *
18217 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18218 */
18219 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
18220 var i, len, item;
18221
18222 for ( i = 0, len = this.items.length; i < len; i++ ) {
18223 item = this.items[ i ];
18224 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
18225 return item;
18226 }
18227 }
18228
18229 return null;
18230 };
18231
18232 /**
18233 * Add an array of options to the select. Optionally, an index number can be used to
18234 * specify an insertion point.
18235 *
18236 * @param {OO.ui.OptionWidget[]} items Items to add
18237 * @param {number} [index] Index to insert items after
18238 * @fires add
18239 * @chainable
18240 */
18241 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
18242 // Mixin method
18243 OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index );
18244
18245 // Always provide an index, even if it was omitted
18246 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
18247
18248 return this;
18249 };
18250
18251 /**
18252 * Remove the specified array of options from the select. Options will be detached
18253 * from the DOM, not removed, so they can be reused later. To remove all options from
18254 * the select, you may wish to use the #clearItems method instead.
18255 *
18256 * @param {OO.ui.OptionWidget[]} items Items to remove
18257 * @fires remove
18258 * @chainable
18259 */
18260 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
18261 var i, len, item;
18262
18263 // Deselect items being removed
18264 for ( i = 0, len = items.length; i < len; i++ ) {
18265 item = items[ i ];
18266 if ( item.isSelected() ) {
18267 this.selectItem( null );
18268 }
18269 }
18270
18271 // Mixin method
18272 OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items );
18273
18274 this.emit( 'remove', items );
18275
18276 return this;
18277 };
18278
18279 /**
18280 * Clear all options from the select. Options will be detached from the DOM, not removed,
18281 * so that they can be reused later. To remove a subset of options from the select, use
18282 * the #removeItems method.
18283 *
18284 * @fires remove
18285 * @chainable
18286 */
18287 OO.ui.SelectWidget.prototype.clearItems = function () {
18288 var items = this.items.slice();
18289
18290 // Mixin method
18291 OO.ui.mixin.GroupWidget.prototype.clearItems.call( this );
18292
18293 // Clear selection
18294 this.selectItem( null );
18295
18296 this.emit( 'remove', items );
18297
18298 return this;
18299 };
18300
18301 /**
18302 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18303 * button options and is used together with
18304 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18305 * highlighting, choosing, and selecting mutually exclusive options. Please see
18306 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18307 *
18308 * @example
18309 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18310 * var option1 = new OO.ui.ButtonOptionWidget( {
18311 * data: 1,
18312 * label: 'Option 1',
18313 * title: 'Button option 1'
18314 * } );
18315 *
18316 * var option2 = new OO.ui.ButtonOptionWidget( {
18317 * data: 2,
18318 * label: 'Option 2',
18319 * title: 'Button option 2'
18320 * } );
18321 *
18322 * var option3 = new OO.ui.ButtonOptionWidget( {
18323 * data: 3,
18324 * label: 'Option 3',
18325 * title: 'Button option 3'
18326 * } );
18327 *
18328 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18329 * items: [ option1, option2, option3 ]
18330 * } );
18331 * $( 'body' ).append( buttonSelect.$element );
18332 *
18333 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18334 *
18335 * @class
18336 * @extends OO.ui.SelectWidget
18337 * @mixins OO.ui.mixin.TabIndexedElement
18338 *
18339 * @constructor
18340 * @param {Object} [config] Configuration options
18341 */
18342 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
18343 // Parent constructor
18344 OO.ui.ButtonSelectWidget.parent.call( this, config );
18345
18346 // Mixin constructors
18347 OO.ui.mixin.TabIndexedElement.call( this, config );
18348
18349 // Events
18350 this.$element.on( {
18351 focus: this.bindKeyDownListener.bind( this ),
18352 blur: this.unbindKeyDownListener.bind( this )
18353 } );
18354
18355 // Initialization
18356 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
18357 };
18358
18359 /* Setup */
18360
18361 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
18362 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
18363
18364 /**
18365 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18366 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18367 * an interface for adding, removing and selecting options.
18368 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18369 *
18370 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18371 * OO.ui.RadioSelectInputWidget instead.
18372 *
18373 * @example
18374 * // A RadioSelectWidget with RadioOptions.
18375 * var option1 = new OO.ui.RadioOptionWidget( {
18376 * data: 'a',
18377 * label: 'Selected radio option'
18378 * } );
18379 *
18380 * var option2 = new OO.ui.RadioOptionWidget( {
18381 * data: 'b',
18382 * label: 'Unselected radio option'
18383 * } );
18384 *
18385 * var radioSelect=new OO.ui.RadioSelectWidget( {
18386 * items: [ option1, option2 ]
18387 * } );
18388 *
18389 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18390 * radioSelect.selectItem( option1 );
18391 *
18392 * $( 'body' ).append( radioSelect.$element );
18393 *
18394 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18395
18396 *
18397 * @class
18398 * @extends OO.ui.SelectWidget
18399 * @mixins OO.ui.mixin.TabIndexedElement
18400 *
18401 * @constructor
18402 * @param {Object} [config] Configuration options
18403 */
18404 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
18405 // Parent constructor
18406 OO.ui.RadioSelectWidget.parent.call( this, config );
18407
18408 // Mixin constructors
18409 OO.ui.mixin.TabIndexedElement.call( this, config );
18410
18411 // Events
18412 this.$element.on( {
18413 focus: this.bindKeyDownListener.bind( this ),
18414 blur: this.unbindKeyDownListener.bind( this )
18415 } );
18416
18417 // Initialization
18418 this.$element
18419 .addClass( 'oo-ui-radioSelectWidget' )
18420 .attr( 'role', 'radiogroup' );
18421 };
18422
18423 /* Setup */
18424
18425 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
18426 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement );
18427
18428 /**
18429 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18430 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18431 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18432 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18433 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18434 * and customized to be opened, closed, and displayed as needed.
18435 *
18436 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18437 * mouse outside the menu.
18438 *
18439 * Menus also have support for keyboard interaction:
18440 *
18441 * - Enter/Return key: choose and select a menu option
18442 * - Up-arrow key: highlight the previous menu option
18443 * - Down-arrow key: highlight the next menu option
18444 * - Esc key: hide the menu
18445 *
18446 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18447 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18448 *
18449 * @class
18450 * @extends OO.ui.SelectWidget
18451 * @mixins OO.ui.mixin.ClippableElement
18452 *
18453 * @constructor
18454 * @param {Object} [config] Configuration options
18455 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18456 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18457 * and {@link OO.ui.mixin.LookupElement LookupElement}
18458 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18459 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18460 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18461 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18462 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18463 * that button, unless the button (or its parent widget) is passed in here.
18464 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18465 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18466 */
18467 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
18468 // Configuration initialization
18469 config = config || {};
18470
18471 // Parent constructor
18472 OO.ui.MenuSelectWidget.parent.call( this, config );
18473
18474 // Mixin constructors
18475 OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
18476
18477 // Properties
18478 this.newItems = null;
18479 this.autoHide = config.autoHide === undefined || !!config.autoHide;
18480 this.filterFromInput = !!config.filterFromInput;
18481 this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
18482 this.$widget = config.widget ? config.widget.$element : null;
18483 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
18484 this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
18485
18486 // Initialization
18487 this.$element
18488 .addClass( 'oo-ui-menuSelectWidget' )
18489 .attr( 'role', 'menu' );
18490
18491 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18492 // that reference properties not initialized at that time of parent class construction
18493 // TODO: Find a better way to handle post-constructor setup
18494 this.visible = false;
18495 this.$element.addClass( 'oo-ui-element-hidden' );
18496 };
18497
18498 /* Setup */
18499
18500 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
18501 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
18502
18503 /* Methods */
18504
18505 /**
18506 * Handles document mouse down events.
18507 *
18508 * @protected
18509 * @param {jQuery.Event} e Key down event
18510 */
18511 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
18512 if (
18513 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
18514 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
18515 ) {
18516 this.toggle( false );
18517 }
18518 };
18519
18520 /**
18521 * @inheritdoc
18522 */
18523 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
18524 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
18525
18526 if ( !this.isDisabled() && this.isVisible() ) {
18527 switch ( e.keyCode ) {
18528 case OO.ui.Keys.LEFT:
18529 case OO.ui.Keys.RIGHT:
18530 // Do nothing if a text field is associated, arrow keys will be handled natively
18531 if ( !this.$input ) {
18532 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18533 }
18534 break;
18535 case OO.ui.Keys.ESCAPE:
18536 case OO.ui.Keys.TAB:
18537 if ( currentItem ) {
18538 currentItem.setHighlighted( false );
18539 }
18540 this.toggle( false );
18541 // Don't prevent tabbing away, prevent defocusing
18542 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
18543 e.preventDefault();
18544 e.stopPropagation();
18545 }
18546 break;
18547 default:
18548 OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
18549 return;
18550 }
18551 }
18552 };
18553
18554 /**
18555 * Update menu item visibility after input changes.
18556 * @protected
18557 */
18558 OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
18559 var i, item,
18560 len = this.items.length,
18561 showAll = !this.isVisible(),
18562 filter = showAll ? null : this.getItemMatcher( this.$input.val() );
18563
18564 for ( i = 0; i < len; i++ ) {
18565 item = this.items[ i ];
18566 if ( item instanceof OO.ui.OptionWidget ) {
18567 item.toggle( showAll || filter( item ) );
18568 }
18569 }
18570
18571 // Reevaluate clipping
18572 this.clip();
18573 };
18574
18575 /**
18576 * @inheritdoc
18577 */
18578 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
18579 if ( this.$input ) {
18580 this.$input.on( 'keydown', this.onKeyDownHandler );
18581 } else {
18582 OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
18583 }
18584 };
18585
18586 /**
18587 * @inheritdoc
18588 */
18589 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
18590 if ( this.$input ) {
18591 this.$input.off( 'keydown', this.onKeyDownHandler );
18592 } else {
18593 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
18594 }
18595 };
18596
18597 /**
18598 * @inheritdoc
18599 */
18600 OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
18601 if ( this.$input ) {
18602 if ( this.filterFromInput ) {
18603 this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18604 }
18605 } else {
18606 OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
18607 }
18608 };
18609
18610 /**
18611 * @inheritdoc
18612 */
18613 OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
18614 if ( this.$input ) {
18615 if ( this.filterFromInput ) {
18616 this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
18617 this.updateItemVisibility();
18618 }
18619 } else {
18620 OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
18621 }
18622 };
18623
18624 /**
18625 * Choose an item.
18626 *
18627 * When a user chooses an item, the menu is closed.
18628 *
18629 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18630 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18631 * @param {OO.ui.OptionWidget} item Item to choose
18632 * @chainable
18633 */
18634 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
18635 OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
18636 this.toggle( false );
18637 return this;
18638 };
18639
18640 /**
18641 * @inheritdoc
18642 */
18643 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
18644 var i, len, item;
18645
18646 // Parent method
18647 OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );
18648
18649 // Auto-initialize
18650 if ( !this.newItems ) {
18651 this.newItems = [];
18652 }
18653
18654 for ( i = 0, len = items.length; i < len; i++ ) {
18655 item = items[ i ];
18656 if ( this.isVisible() ) {
18657 // Defer fitting label until item has been attached
18658 item.fitLabel();
18659 } else {
18660 this.newItems.push( item );
18661 }
18662 }
18663
18664 // Reevaluate clipping
18665 this.clip();
18666
18667 return this;
18668 };
18669
18670 /**
18671 * @inheritdoc
18672 */
18673 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
18674 // Parent method
18675 OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );
18676
18677 // Reevaluate clipping
18678 this.clip();
18679
18680 return this;
18681 };
18682
18683 /**
18684 * @inheritdoc
18685 */
18686 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
18687 // Parent method
18688 OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );
18689
18690 // Reevaluate clipping
18691 this.clip();
18692
18693 return this;
18694 };
18695
18696 /**
18697 * @inheritdoc
18698 */
18699 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
18700 var i, len, change;
18701
18702 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
18703 change = visible !== this.isVisible();
18704
18705 // Parent method
18706 OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );
18707
18708 if ( change ) {
18709 if ( visible ) {
18710 this.bindKeyDownListener();
18711 this.bindKeyPressListener();
18712
18713 if ( this.newItems && this.newItems.length ) {
18714 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
18715 this.newItems[ i ].fitLabel();
18716 }
18717 this.newItems = null;
18718 }
18719 this.toggleClipping( true );
18720
18721 // Auto-hide
18722 if ( this.autoHide ) {
18723 OO.ui.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18724 }
18725 } else {
18726 this.unbindKeyDownListener();
18727 this.unbindKeyPressListener();
18728 OO.ui.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler );
18729 this.toggleClipping( false );
18730 }
18731 }
18732
18733 return this;
18734 };
18735
18736 /**
18737 * FloatingMenuSelectWidget is a menu that will stick under a specified
18738 * container, even when it is inserted elsewhere in the document (for example,
18739 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18740 * menu from being clipped too aggresively.
18741 *
18742 * The menu's position is automatically calculated and maintained when the menu
18743 * is toggled or the window is resized.
18744 *
18745 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18746 *
18747 * @class
18748 * @extends OO.ui.MenuSelectWidget
18749 *
18750 * @constructor
18751 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18752 * Deprecated, omit this parameter and specify `$container` instead.
18753 * @param {Object} [config] Configuration options
18754 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18755 */
18756 OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) {
18757 // Allow 'inputWidget' parameter and config for backwards compatibility
18758 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
18759 config = inputWidget;
18760 inputWidget = config.inputWidget;
18761 }
18762
18763 // Configuration initialization
18764 config = config || {};
18765
18766 // Parent constructor
18767 OO.ui.FloatingMenuSelectWidget.parent.call( this, config );
18768
18769 // Properties
18770 this.inputWidget = inputWidget; // For backwards compatibility
18771 this.$container = config.$container || this.inputWidget.$element;
18772 this.onWindowResizeHandler = this.onWindowResize.bind( this );
18773
18774 // Initialization
18775 this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' );
18776 // For backwards compatibility
18777 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
18778 };
18779
18780 /* Setup */
18781
18782 OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget );
18783
18784 // For backwards compatibility
18785 OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget;
18786
18787 /* Methods */
18788
18789 /**
18790 * Handle window resize event.
18791 *
18792 * @private
18793 * @param {jQuery.Event} e Window resize event
18794 */
18795 OO.ui.FloatingMenuSelectWidget.prototype.onWindowResize = function () {
18796 this.position();
18797 };
18798
18799 /**
18800 * @inheritdoc
18801 */
18802 OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) {
18803 var change;
18804 visible = visible === undefined ? !this.isVisible() : !!visible;
18805
18806 change = visible !== this.isVisible();
18807
18808 if ( change && visible ) {
18809 // Make sure the width is set before the parent method runs.
18810 // After this we have to call this.position(); again to actually
18811 // position ourselves correctly.
18812 this.position();
18813 }
18814
18815 // Parent method
18816 OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible );
18817
18818 if ( change ) {
18819 if ( this.isVisible() ) {
18820 this.position();
18821 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
18822 } else {
18823 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
18824 }
18825 }
18826
18827 return this;
18828 };
18829
18830 /**
18831 * Position the menu.
18832 *
18833 * @private
18834 * @chainable
18835 */
18836 OO.ui.FloatingMenuSelectWidget.prototype.position = function () {
18837 var $container = this.$container,
18838 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
18839
18840 // Position under input
18841 pos.top += $container.height();
18842 this.$element.css( pos );
18843
18844 // Set width
18845 this.setIdealSize( $container.width() );
18846 // We updated the position, so re-evaluate the clipping state
18847 this.clip();
18848
18849 return this;
18850 };
18851
18852 /**
18853 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18854 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18855 *
18856 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18857 *
18858 * @class
18859 * @extends OO.ui.SelectWidget
18860 * @mixins OO.ui.mixin.TabIndexedElement
18861 *
18862 * @constructor
18863 * @param {Object} [config] Configuration options
18864 */
18865 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
18866 // Parent constructor
18867 OO.ui.OutlineSelectWidget.parent.call( this, config );
18868
18869 // Mixin constructors
18870 OO.ui.mixin.TabIndexedElement.call( this, config );
18871
18872 // Events
18873 this.$element.on( {
18874 focus: this.bindKeyDownListener.bind( this ),
18875 blur: this.unbindKeyDownListener.bind( this )
18876 } );
18877
18878 // Initialization
18879 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
18880 };
18881
18882 /* Setup */
18883
18884 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
18885 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
18886
18887 /**
18888 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18889 *
18890 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18891 *
18892 * @class
18893 * @extends OO.ui.SelectWidget
18894 * @mixins OO.ui.mixin.TabIndexedElement
18895 *
18896 * @constructor
18897 * @param {Object} [config] Configuration options
18898 */
18899 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
18900 // Parent constructor
18901 OO.ui.TabSelectWidget.parent.call( this, config );
18902
18903 // Mixin constructors
18904 OO.ui.mixin.TabIndexedElement.call( this, config );
18905
18906 // Events
18907 this.$element.on( {
18908 focus: this.bindKeyDownListener.bind( this ),
18909 blur: this.unbindKeyDownListener.bind( this )
18910 } );
18911
18912 // Initialization
18913 this.$element.addClass( 'oo-ui-tabSelectWidget' );
18914 };
18915
18916 /* Setup */
18917
18918 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
18919 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
18920
18921 /**
18922 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18923 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18924 * (to adjust the value in increments) to allow the user to enter a number.
18925 *
18926 * @example
18927 * // Example: A NumberInputWidget.
18928 * var numberInput = new OO.ui.NumberInputWidget( {
18929 * label: 'NumberInputWidget',
18930 * input: { value: 5, min: 1, max: 10 }
18931 * } );
18932 * $( 'body' ).append( numberInput.$element );
18933 *
18934 * @class
18935 * @extends OO.ui.Widget
18936 *
18937 * @constructor
18938 * @param {Object} [config] Configuration options
18939 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18940 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18941 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18942 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18943 * @cfg {number} [min=-Infinity] Minimum allowed value
18944 * @cfg {number} [max=Infinity] Maximum allowed value
18945 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18946 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18947 */
18948 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
18949 // Configuration initialization
18950 config = $.extend( {
18951 isInteger: false,
18952 min: -Infinity,
18953 max: Infinity,
18954 step: 1,
18955 pageStep: null
18956 }, config );
18957
18958 // Parent constructor
18959 OO.ui.NumberInputWidget.parent.call( this, config );
18960
18961 // Properties
18962 this.input = new OO.ui.TextInputWidget( $.extend(
18963 {
18964 disabled: this.isDisabled()
18965 },
18966 config.input
18967 ) );
18968 this.minusButton = new OO.ui.ButtonWidget( $.extend(
18969 {
18970 disabled: this.isDisabled(),
18971 tabIndex: -1
18972 },
18973 config.minusButton,
18974 {
18975 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
18976 label: '−'
18977 }
18978 ) );
18979 this.plusButton = new OO.ui.ButtonWidget( $.extend(
18980 {
18981 disabled: this.isDisabled(),
18982 tabIndex: -1
18983 },
18984 config.plusButton,
18985 {
18986 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
18987 label: '+'
18988 }
18989 ) );
18990
18991 // Events
18992 this.input.connect( this, {
18993 change: this.emit.bind( this, 'change' ),
18994 enter: this.emit.bind( this, 'enter' )
18995 } );
18996 this.input.$input.on( {
18997 keydown: this.onKeyDown.bind( this ),
18998 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
18999 } );
19000 this.plusButton.connect( this, {
19001 click: [ 'onButtonClick', +1 ]
19002 } );
19003 this.minusButton.connect( this, {
19004 click: [ 'onButtonClick', -1 ]
19005 } );
19006
19007 // Initialization
19008 this.setIsInteger( !!config.isInteger );
19009 this.setRange( config.min, config.max );
19010 this.setStep( config.step, config.pageStep );
19011
19012 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19013 .append(
19014 this.minusButton.$element,
19015 this.input.$element,
19016 this.plusButton.$element
19017 );
19018 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
19019 this.input.setValidation( this.validateNumber.bind( this ) );
19020 };
19021
19022 /* Setup */
19023
19024 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
19025
19026 /* Events */
19027
19028 /**
19029 * A `change` event is emitted when the value of the input changes.
19030 *
19031 * @event change
19032 */
19033
19034 /**
19035 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19036 *
19037 * @event enter
19038 */
19039
19040 /* Methods */
19041
19042 /**
19043 * Set whether only integers are allowed
19044 * @param {boolean} flag
19045 */
19046 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
19047 this.isInteger = !!flag;
19048 this.input.setValidityFlag();
19049 };
19050
19051 /**
19052 * Get whether only integers are allowed
19053 * @return {boolean} Flag value
19054 */
19055 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
19056 return this.isInteger;
19057 };
19058
19059 /**
19060 * Set the range of allowed values
19061 * @param {number} min Minimum allowed value
19062 * @param {number} max Maximum allowed value
19063 */
19064 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
19065 if ( min > max ) {
19066 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
19067 }
19068 this.min = min;
19069 this.max = max;
19070 this.input.setValidityFlag();
19071 };
19072
19073 /**
19074 * Get the current range
19075 * @return {number[]} Minimum and maximum values
19076 */
19077 OO.ui.NumberInputWidget.prototype.getRange = function () {
19078 return [ this.min, this.max ];
19079 };
19080
19081 /**
19082 * Set the stepping deltas
19083 * @param {number} step Normal step
19084 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19085 */
19086 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
19087 if ( step <= 0 ) {
19088 throw new Error( 'Step value must be positive' );
19089 }
19090 if ( pageStep === null ) {
19091 pageStep = step * 10;
19092 } else if ( pageStep <= 0 ) {
19093 throw new Error( 'Page step value must be positive' );
19094 }
19095 this.step = step;
19096 this.pageStep = pageStep;
19097 };
19098
19099 /**
19100 * Get the current stepping values
19101 * @return {number[]} Step and page step
19102 */
19103 OO.ui.NumberInputWidget.prototype.getStep = function () {
19104 return [ this.step, this.pageStep ];
19105 };
19106
19107 /**
19108 * Get the current value of the widget
19109 * @return {string}
19110 */
19111 OO.ui.NumberInputWidget.prototype.getValue = function () {
19112 return this.input.getValue();
19113 };
19114
19115 /**
19116 * Get the current value of the widget as a number
19117 * @return {number} May be NaN, or an invalid number
19118 */
19119 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
19120 return +this.input.getValue();
19121 };
19122
19123 /**
19124 * Set the value of the widget
19125 * @param {string} value Invalid values are allowed
19126 */
19127 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
19128 this.input.setValue( value );
19129 };
19130
19131 /**
19132 * Adjust the value of the widget
19133 * @param {number} delta Adjustment amount
19134 */
19135 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
19136 var n, v = this.getNumericValue();
19137
19138 delta = +delta;
19139 if ( isNaN( delta ) || !isFinite( delta ) ) {
19140 throw new Error( 'Delta must be a finite number' );
19141 }
19142
19143 if ( isNaN( v ) ) {
19144 n = 0;
19145 } else {
19146 n = v + delta;
19147 n = Math.max( Math.min( n, this.max ), this.min );
19148 if ( this.isInteger ) {
19149 n = Math.round( n );
19150 }
19151 }
19152
19153 if ( n !== v ) {
19154 this.setValue( n );
19155 }
19156 };
19157
19158 /**
19159 * Validate input
19160 * @private
19161 * @param {string} value Field value
19162 * @return {boolean}
19163 */
19164 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
19165 var n = +value;
19166 if ( isNaN( n ) || !isFinite( n ) ) {
19167 return false;
19168 }
19169
19170 /*jshint bitwise: false */
19171 if ( this.isInteger && ( n | 0 ) !== n ) {
19172 return false;
19173 }
19174 /*jshint bitwise: true */
19175
19176 if ( n < this.min || n > this.max ) {
19177 return false;
19178 }
19179
19180 return true;
19181 };
19182
19183 /**
19184 * Handle mouse click events.
19185 *
19186 * @private
19187 * @param {number} dir +1 or -1
19188 */
19189 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
19190 this.adjustValue( dir * this.step );
19191 };
19192
19193 /**
19194 * Handle mouse wheel events.
19195 *
19196 * @private
19197 * @param {jQuery.Event} event
19198 */
19199 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
19200 var delta = 0;
19201
19202 // Standard 'wheel' event
19203 if ( event.originalEvent.deltaMode !== undefined ) {
19204 this.sawWheelEvent = true;
19205 }
19206 if ( event.originalEvent.deltaY ) {
19207 delta = -event.originalEvent.deltaY;
19208 } else if ( event.originalEvent.deltaX ) {
19209 delta = event.originalEvent.deltaX;
19210 }
19211
19212 // Non-standard events
19213 if ( !this.sawWheelEvent ) {
19214 if ( event.originalEvent.wheelDeltaX ) {
19215 delta = -event.originalEvent.wheelDeltaX;
19216 } else if ( event.originalEvent.wheelDeltaY ) {
19217 delta = event.originalEvent.wheelDeltaY;
19218 } else if ( event.originalEvent.wheelDelta ) {
19219 delta = event.originalEvent.wheelDelta;
19220 } else if ( event.originalEvent.detail ) {
19221 delta = -event.originalEvent.detail;
19222 }
19223 }
19224
19225 if ( delta ) {
19226 delta = delta < 0 ? -1 : 1;
19227 this.adjustValue( delta * this.step );
19228 }
19229
19230 return false;
19231 };
19232
19233 /**
19234 * Handle key down events.
19235 *
19236 *
19237 * @private
19238 * @param {jQuery.Event} e Key down event
19239 */
19240 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
19241 if ( !this.isDisabled() ) {
19242 switch ( e.which ) {
19243 case OO.ui.Keys.UP:
19244 this.adjustValue( this.step );
19245 return false;
19246 case OO.ui.Keys.DOWN:
19247 this.adjustValue( -this.step );
19248 return false;
19249 case OO.ui.Keys.PAGEUP:
19250 this.adjustValue( this.pageStep );
19251 return false;
19252 case OO.ui.Keys.PAGEDOWN:
19253 this.adjustValue( -this.pageStep );
19254 return false;
19255 }
19256 }
19257 };
19258
19259 /**
19260 * @inheritdoc
19261 */
19262 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
19263 // Parent method
19264 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
19265
19266 if ( this.input ) {
19267 this.input.setDisabled( this.isDisabled() );
19268 }
19269 if ( this.minusButton ) {
19270 this.minusButton.setDisabled( this.isDisabled() );
19271 }
19272 if ( this.plusButton ) {
19273 this.plusButton.setDisabled( this.isDisabled() );
19274 }
19275
19276 return this;
19277 };
19278
19279 /**
19280 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19281 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19282 * visually by a slider in the leftmost position.
19283 *
19284 * @example
19285 * // Toggle switches in the 'off' and 'on' position.
19286 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19287 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19288 * value: true
19289 * } );
19290 *
19291 * // Create a FieldsetLayout to layout and label switches
19292 * var fieldset = new OO.ui.FieldsetLayout( {
19293 * label: 'Toggle switches'
19294 * } );
19295 * fieldset.addItems( [
19296 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19297 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19298 * ] );
19299 * $( 'body' ).append( fieldset.$element );
19300 *
19301 * @class
19302 * @extends OO.ui.ToggleWidget
19303 * @mixins OO.ui.mixin.TabIndexedElement
19304 *
19305 * @constructor
19306 * @param {Object} [config] Configuration options
19307 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19308 * By default, the toggle switch is in the 'off' position.
19309 */
19310 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
19311 // Parent constructor
19312 OO.ui.ToggleSwitchWidget.parent.call( this, config );
19313
19314 // Mixin constructors
19315 OO.ui.mixin.TabIndexedElement.call( this, config );
19316
19317 // Properties
19318 this.dragging = false;
19319 this.dragStart = null;
19320 this.sliding = false;
19321 this.$glow = $( '<span>' );
19322 this.$grip = $( '<span>' );
19323
19324 // Events
19325 this.$element.on( {
19326 click: this.onClick.bind( this ),
19327 keypress: this.onKeyPress.bind( this )
19328 } );
19329
19330 // Initialization
19331 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19332 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19333 this.$element
19334 .addClass( 'oo-ui-toggleSwitchWidget' )
19335 .attr( 'role', 'checkbox' )
19336 .append( this.$glow, this.$grip );
19337 };
19338
19339 /* Setup */
19340
19341 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
19342 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
19343
19344 /* Methods */
19345
19346 /**
19347 * Handle mouse click events.
19348 *
19349 * @private
19350 * @param {jQuery.Event} e Mouse click event
19351 */
19352 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
19353 if ( !this.isDisabled() && e.which === 1 ) {
19354 this.setValue( !this.value );
19355 }
19356 return false;
19357 };
19358
19359 /**
19360 * Handle key press events.
19361 *
19362 * @private
19363 * @param {jQuery.Event} e Key press event
19364 */
19365 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
19366 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
19367 this.setValue( !this.value );
19368 return false;
19369 }
19370 };
19371
19372 /*!
19373 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19374 */
19375
19376 /**
19377 * @inheritdoc OO.ui.mixin.ButtonElement
19378 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19379 */
19380 OO.ui.ButtonElement = OO.ui.mixin.ButtonElement;
19381
19382 /**
19383 * @inheritdoc OO.ui.mixin.ClippableElement
19384 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19385 */
19386 OO.ui.ClippableElement = OO.ui.mixin.ClippableElement;
19387
19388 /**
19389 * @inheritdoc OO.ui.mixin.DraggableElement
19390 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19391 */
19392 OO.ui.DraggableElement = OO.ui.mixin.DraggableElement;
19393
19394 /**
19395 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19396 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19397 */
19398 OO.ui.DraggableGroupElement = OO.ui.mixin.DraggableGroupElement;
19399
19400 /**
19401 * @inheritdoc OO.ui.mixin.FlaggedElement
19402 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19403 */
19404 OO.ui.FlaggedElement = OO.ui.mixin.FlaggedElement;
19405
19406 /**
19407 * @inheritdoc OO.ui.mixin.GroupElement
19408 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19409 */
19410 OO.ui.GroupElement = OO.ui.mixin.GroupElement;
19411
19412 /**
19413 * @inheritdoc OO.ui.mixin.GroupWidget
19414 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19415 */
19416 OO.ui.GroupWidget = OO.ui.mixin.GroupWidget;
19417
19418 /**
19419 * @inheritdoc OO.ui.mixin.IconElement
19420 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19421 */
19422 OO.ui.IconElement = OO.ui.mixin.IconElement;
19423
19424 /**
19425 * @inheritdoc OO.ui.mixin.IndicatorElement
19426 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19427 */
19428 OO.ui.IndicatorElement = OO.ui.mixin.IndicatorElement;
19429
19430 /**
19431 * @inheritdoc OO.ui.mixin.ItemWidget
19432 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19433 */
19434 OO.ui.ItemWidget = OO.ui.mixin.ItemWidget;
19435
19436 /**
19437 * @inheritdoc OO.ui.mixin.LabelElement
19438 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19439 */
19440 OO.ui.LabelElement = OO.ui.mixin.LabelElement;
19441
19442 /**
19443 * @inheritdoc OO.ui.mixin.LookupElement
19444 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19445 */
19446 OO.ui.LookupElement = OO.ui.mixin.LookupElement;
19447
19448 /**
19449 * @inheritdoc OO.ui.mixin.PendingElement
19450 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19451 */
19452 OO.ui.PendingElement = OO.ui.mixin.PendingElement;
19453
19454 /**
19455 * @inheritdoc OO.ui.mixin.PopupElement
19456 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19457 */
19458 OO.ui.PopupElement = OO.ui.mixin.PopupElement;
19459
19460 /**
19461 * @inheritdoc OO.ui.mixin.TabIndexedElement
19462 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19463 */
19464 OO.ui.TabIndexedElement = OO.ui.mixin.TabIndexedElement;
19465
19466 /**
19467 * @inheritdoc OO.ui.mixin.TitledElement
19468 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19469 */
19470 OO.ui.TitledElement = OO.ui.mixin.TitledElement;
19471
19472 }( OO ) );