Merge "Made JobQueueAggregatorRedis make sure the wiki set key is up-to-date"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.11.1
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-05-05T00:40:50Z
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 * Check if an element is focusable.
49 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
50 *
51 * @param {jQuery} element Element to test
52 * @return {Boolean} [description]
53 */
54 OO.ui.isFocusableElement = function ( $element ) {
55 var node = $element[0],
56 nodeName = node.nodeName.toLowerCase(),
57 // Check if the element have tabindex set
58 isInElementGroup = /^(input|select|textarea|button|object)$/.test( nodeName ),
59 // Check if the element is a link with href or if it has tabindex
60 isOtherElement = (
61 ( nodeName === 'a' && node.href ) ||
62 !isNaN( $element.attr( 'tabindex' ) )
63 ),
64 // Check if the element is visible
65 isVisible = (
66 // This is quicker than calling $element.is( ':visible' )
67 $.expr.filters.visible( node ) &&
68 // Check that all parents are visible
69 !$element.parents().addBack().filter( function () {
70 return $.css( this, 'visibility' ) === 'hidden';
71 } ).length
72 );
73
74 return (
75 ( isInElementGroup ? !node.disabled : isOtherElement ) &&
76 isVisible
77 );
78 };
79
80 /**
81 * Get the user's language and any fallback languages.
82 *
83 * These language codes are used to localize user interface elements in the user's language.
84 *
85 * In environments that provide a localization system, this function should be overridden to
86 * return the user's language(s). The default implementation returns English (en) only.
87 *
88 * @return {string[]} Language codes, in descending order of priority
89 */
90 OO.ui.getUserLanguages = function () {
91 return [ 'en' ];
92 };
93
94 /**
95 * Get a value in an object keyed by language code.
96 *
97 * @param {Object.<string,Mixed>} obj Object keyed by language code
98 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
99 * @param {string} [fallback] Fallback code, used if no matching language can be found
100 * @return {Mixed} Local value
101 */
102 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
103 var i, len, langs;
104
105 // Requested language
106 if ( obj[ lang ] ) {
107 return obj[ lang ];
108 }
109 // Known user language
110 langs = OO.ui.getUserLanguages();
111 for ( i = 0, len = langs.length; i < len; i++ ) {
112 lang = langs[ i ];
113 if ( obj[ lang ] ) {
114 return obj[ lang ];
115 }
116 }
117 // Fallback language
118 if ( obj[ fallback ] ) {
119 return obj[ fallback ];
120 }
121 // First existing language
122 for ( lang in obj ) {
123 return obj[ lang ];
124 }
125
126 return undefined;
127 };
128
129 /**
130 * Check if a node is contained within another node
131 *
132 * Similar to jQuery#contains except a list of containers can be supplied
133 * and a boolean argument allows you to include the container in the match list
134 *
135 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
136 * @param {HTMLElement} contained Node to find
137 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
138 * @return {boolean} The node is in the list of target nodes
139 */
140 OO.ui.contains = function ( containers, contained, matchContainers ) {
141 var i;
142 if ( !Array.isArray( containers ) ) {
143 containers = [ containers ];
144 }
145 for ( i = containers.length - 1; i >= 0; i-- ) {
146 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
147 return true;
148 }
149 }
150 return false;
151 };
152
153 /**
154 * Return a function, that, as long as it continues to be invoked, will not
155 * be triggered. The function will be called after it stops being called for
156 * N milliseconds. If `immediate` is passed, trigger the function on the
157 * leading edge, instead of the trailing.
158 *
159 * Ported from: http://underscorejs.org/underscore.js
160 *
161 * @param {Function} func
162 * @param {number} wait
163 * @param {boolean} immediate
164 * @return {Function}
165 */
166 OO.ui.debounce = function ( func, wait, immediate ) {
167 var timeout;
168 return function () {
169 var context = this,
170 args = arguments,
171 later = function () {
172 timeout = null;
173 if ( !immediate ) {
174 func.apply( context, args );
175 }
176 };
177 if ( immediate && !timeout ) {
178 func.apply( context, args );
179 }
180 clearTimeout( timeout );
181 timeout = setTimeout( later, wait );
182 };
183 };
184
185 /**
186 * Reconstitute a JavaScript object corresponding to a widget created by
187 * the PHP implementation.
188 *
189 * This is an alias for `OO.ui.Element.static.infuse()`.
190 *
191 * @param {string|HTMLElement|jQuery} idOrNode
192 * A DOM id (if a string) or node for the widget to infuse.
193 * @return {OO.ui.Element}
194 * The `OO.ui.Element` corresponding to this (infusable) document node.
195 */
196 OO.ui.infuse = function ( idOrNode ) {
197 return OO.ui.Element.static.infuse( idOrNode );
198 };
199
200 ( function () {
201 /**
202 * Message store for the default implementation of OO.ui.msg
203 *
204 * Environments that provide a localization system should not use this, but should override
205 * OO.ui.msg altogether.
206 *
207 * @private
208 */
209 var messages = {
210 // Tool tip for a button that moves items in a list down one place
211 'ooui-outline-control-move-down': 'Move item down',
212 // Tool tip for a button that moves items in a list up one place
213 'ooui-outline-control-move-up': 'Move item up',
214 // Tool tip for a button that removes items from a list
215 'ooui-outline-control-remove': 'Remove item',
216 // Label for the toolbar group that contains a list of all other available tools
217 'ooui-toolbar-more': 'More',
218 // Label for the fake tool that expands the full list of tools in a toolbar group
219 'ooui-toolgroup-expand': 'More',
220 // Label for the fake tool that collapses the full list of tools in a toolbar group
221 'ooui-toolgroup-collapse': 'Fewer',
222 // Default label for the accept button of a confirmation dialog
223 'ooui-dialog-message-accept': 'OK',
224 // Default label for the reject button of a confirmation dialog
225 'ooui-dialog-message-reject': 'Cancel',
226 // Title for process dialog error description
227 'ooui-dialog-process-error': 'Something went wrong',
228 // Label for process dialog dismiss error button, visible when describing errors
229 'ooui-dialog-process-dismiss': 'Dismiss',
230 // Label for process dialog retry action button, visible when describing only recoverable errors
231 'ooui-dialog-process-retry': 'Try again',
232 // Label for process dialog retry action button, visible when describing only warnings
233 'ooui-dialog-process-continue': 'Continue'
234 };
235
236 /**
237 * Get a localized message.
238 *
239 * In environments that provide a localization system, this function should be overridden to
240 * return the message translated in the user's language. The default implementation always returns
241 * English messages.
242 *
243 * After the message key, message parameters may optionally be passed. In the default implementation,
244 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
245 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
246 * they support unnamed, ordered message parameters.
247 *
248 * @abstract
249 * @param {string} key Message key
250 * @param {Mixed...} [params] Message parameters
251 * @return {string} Translated message with parameters substituted
252 */
253 OO.ui.msg = function ( key ) {
254 var message = messages[ key ],
255 params = Array.prototype.slice.call( arguments, 1 );
256 if ( typeof message === 'string' ) {
257 // Perform $1 substitution
258 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
259 var i = parseInt( n, 10 );
260 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
261 } );
262 } else {
263 // Return placeholder if message not found
264 message = '[' + key + ']';
265 }
266 return message;
267 };
268
269 /**
270 * Package a message and arguments for deferred resolution.
271 *
272 * Use this when you are statically specifying a message and the message may not yet be present.
273 *
274 * @param {string} key Message key
275 * @param {Mixed...} [params] Message parameters
276 * @return {Function} Function that returns the resolved message when executed
277 */
278 OO.ui.deferMsg = function () {
279 var args = arguments;
280 return function () {
281 return OO.ui.msg.apply( OO.ui, args );
282 };
283 };
284
285 /**
286 * Resolve a message.
287 *
288 * If the message is a function it will be executed, otherwise it will pass through directly.
289 *
290 * @param {Function|string} msg Deferred message, or message text
291 * @return {string} Resolved message
292 */
293 OO.ui.resolveMsg = function ( msg ) {
294 if ( $.isFunction( msg ) ) {
295 return msg();
296 }
297 return msg;
298 };
299
300 } )();
301
302 /**
303 * Element that can be marked as pending.
304 *
305 * @abstract
306 * @class
307 *
308 * @constructor
309 * @param {Object} [config] Configuration options
310 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
311 */
312 OO.ui.PendingElement = function OoUiPendingElement( config ) {
313 // Configuration initialization
314 config = config || {};
315
316 // Properties
317 this.pending = 0;
318 this.$pending = null;
319
320 // Initialisation
321 this.setPendingElement( config.$pending || this.$element );
322 };
323
324 /* Setup */
325
326 OO.initClass( OO.ui.PendingElement );
327
328 /* Methods */
329
330 /**
331 * Set the pending element (and clean up any existing one).
332 *
333 * @param {jQuery} $pending The element to set to pending.
334 */
335 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
336 if ( this.$pending ) {
337 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
338 }
339
340 this.$pending = $pending;
341 if ( this.pending > 0 ) {
342 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
343 }
344 };
345
346 /**
347 * Check if input is pending.
348 *
349 * @return {boolean}
350 */
351 OO.ui.PendingElement.prototype.isPending = function () {
352 return !!this.pending;
353 };
354
355 /**
356 * Increase the pending stack.
357 *
358 * @chainable
359 */
360 OO.ui.PendingElement.prototype.pushPending = function () {
361 if ( this.pending === 0 ) {
362 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
363 this.updateThemeClasses();
364 }
365 this.pending++;
366
367 return this;
368 };
369
370 /**
371 * Reduce the pending stack.
372 *
373 * Clamped at zero.
374 *
375 * @chainable
376 */
377 OO.ui.PendingElement.prototype.popPending = function () {
378 if ( this.pending === 1 ) {
379 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
380 this.updateThemeClasses();
381 }
382 this.pending = Math.max( 0, this.pending - 1 );
383
384 return this;
385 };
386
387 /**
388 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
389 * Actions can be made available for specific contexts (modes) and circumstances
390 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
391 *
392 * ActionSets contain two types of actions:
393 *
394 * - 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.
395 * - Other: Other actions include all non-special visible actions.
396 *
397 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
398 *
399 * @example
400 * // Example: An action set used in a process dialog
401 * function MyProcessDialog( config ) {
402 * MyProcessDialog.super.call( this, config );
403 * }
404 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
405 * MyProcessDialog.static.title = 'An action set in a process dialog';
406 * // An action set that uses modes ('edit' and 'help' mode, in this example).
407 * MyProcessDialog.static.actions = [
408 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
409 * { action: 'help', modes: 'edit', label: 'Help' },
410 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
411 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
412 * ];
413 *
414 * MyProcessDialog.prototype.initialize = function () {
415 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
416 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
417 * 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>' );
418 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
419 * 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>' );
420 * this.stackLayout = new OO.ui.StackLayout( {
421 * items: [ this.panel1, this.panel2 ]
422 * } );
423 * this.$body.append( this.stackLayout.$element );
424 * };
425 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
426 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
427 * .next( function () {
428 * this.actions.setMode( 'edit' );
429 * }, this );
430 * };
431 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
432 * if ( action === 'help' ) {
433 * this.actions.setMode( 'help' );
434 * this.stackLayout.setItem( this.panel2 );
435 * } else if ( action === 'back' ) {
436 * this.actions.setMode( 'edit' );
437 * this.stackLayout.setItem( this.panel1 );
438 * } else if ( action === 'continue' ) {
439 * var dialog = this;
440 * return new OO.ui.Process( function () {
441 * dialog.close();
442 * } );
443 * }
444 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
445 * };
446 * MyProcessDialog.prototype.getBodyHeight = function () {
447 * return this.panel1.$element.outerHeight( true );
448 * };
449 * var windowManager = new OO.ui.WindowManager();
450 * $( 'body' ).append( windowManager.$element );
451 * var dialog = new MyProcessDialog( {
452 * size: 'medium'
453 * } );
454 * windowManager.addWindows( [ dialog ] );
455 * windowManager.openWindow( dialog );
456 *
457 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
458 *
459 * @abstract
460 * @class
461 * @mixins OO.EventEmitter
462 *
463 * @constructor
464 * @param {Object} [config] Configuration options
465 */
466 OO.ui.ActionSet = function OoUiActionSet( config ) {
467 // Configuration initialization
468 config = config || {};
469
470 // Mixin constructors
471 OO.EventEmitter.call( this );
472
473 // Properties
474 this.list = [];
475 this.categories = {
476 actions: 'getAction',
477 flags: 'getFlags',
478 modes: 'getModes'
479 };
480 this.categorized = {};
481 this.special = {};
482 this.others = [];
483 this.organized = false;
484 this.changing = false;
485 this.changed = false;
486 };
487
488 /* Setup */
489
490 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
491
492 /* Static Properties */
493
494 /**
495 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
496 * header of a {@link OO.ui.ProcessDialog process dialog}.
497 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
498 *
499 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
500 *
501 * @abstract
502 * @static
503 * @inheritable
504 * @property {string}
505 */
506 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
507
508 /* Events */
509
510 /**
511 * @event click
512 *
513 * A 'click' event is emitted when an action is clicked.
514 *
515 * @param {OO.ui.ActionWidget} action Action that was clicked
516 */
517
518 /**
519 * @event resize
520 *
521 * A 'resize' event is emitted when an action widget is resized.
522 *
523 * @param {OO.ui.ActionWidget} action Action that was resized
524 */
525
526 /**
527 * @event add
528 *
529 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
530 *
531 * @param {OO.ui.ActionWidget[]} added Actions added
532 */
533
534 /**
535 * @event remove
536 *
537 * A 'remove' event is emitted when actions are {@link #method-remove removed}
538 * or {@link #clear cleared}.
539 *
540 * @param {OO.ui.ActionWidget[]} added Actions removed
541 */
542
543 /**
544 * @event change
545 *
546 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
547 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
548 *
549 */
550
551 /* Methods */
552
553 /**
554 * Handle action change events.
555 *
556 * @private
557 * @fires change
558 */
559 OO.ui.ActionSet.prototype.onActionChange = function () {
560 this.organized = false;
561 if ( this.changing ) {
562 this.changed = true;
563 } else {
564 this.emit( 'change' );
565 }
566 };
567
568 /**
569 * Check if an action is one of the special actions.
570 *
571 * @param {OO.ui.ActionWidget} action Action to check
572 * @return {boolean} Action is special
573 */
574 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
575 var flag;
576
577 for ( flag in this.special ) {
578 if ( action === this.special[ flag ] ) {
579 return true;
580 }
581 }
582
583 return false;
584 };
585
586 /**
587 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
588 * or ‘disabled’.
589 *
590 * @param {Object} [filters] Filters to use, omit to get all actions
591 * @param {string|string[]} [filters.actions] Actions that action widgets must have
592 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
593 * @param {string|string[]} [filters.modes] Modes that action widgets must have
594 * @param {boolean} [filters.visible] Action widgets must be visible
595 * @param {boolean} [filters.disabled] Action widgets must be disabled
596 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
597 */
598 OO.ui.ActionSet.prototype.get = function ( filters ) {
599 var i, len, list, category, actions, index, match, matches;
600
601 if ( filters ) {
602 this.organize();
603
604 // Collect category candidates
605 matches = [];
606 for ( category in this.categorized ) {
607 list = filters[ category ];
608 if ( list ) {
609 if ( !Array.isArray( list ) ) {
610 list = [ list ];
611 }
612 for ( i = 0, len = list.length; i < len; i++ ) {
613 actions = this.categorized[ category ][ list[ i ] ];
614 if ( Array.isArray( actions ) ) {
615 matches.push.apply( matches, actions );
616 }
617 }
618 }
619 }
620 // Remove by boolean filters
621 for ( i = 0, len = matches.length; i < len; i++ ) {
622 match = matches[ i ];
623 if (
624 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
625 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
626 ) {
627 matches.splice( i, 1 );
628 len--;
629 i--;
630 }
631 }
632 // Remove duplicates
633 for ( i = 0, len = matches.length; i < len; i++ ) {
634 match = matches[ i ];
635 index = matches.lastIndexOf( match );
636 while ( index !== i ) {
637 matches.splice( index, 1 );
638 len--;
639 index = matches.lastIndexOf( match );
640 }
641 }
642 return matches;
643 }
644 return this.list.slice();
645 };
646
647 /**
648 * Get 'special' actions.
649 *
650 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
651 * Special flags can be configured in subclasses by changing the static #specialFlags property.
652 *
653 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
654 */
655 OO.ui.ActionSet.prototype.getSpecial = function () {
656 this.organize();
657 return $.extend( {}, this.special );
658 };
659
660 /**
661 * Get 'other' actions.
662 *
663 * Other actions include all non-special visible action widgets.
664 *
665 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
666 */
667 OO.ui.ActionSet.prototype.getOthers = function () {
668 this.organize();
669 return this.others.slice();
670 };
671
672 /**
673 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
674 * to be available in the specified mode will be made visible. All other actions will be hidden.
675 *
676 * @param {string} mode The mode. Only actions configured to be available in the specified
677 * mode will be made visible.
678 * @chainable
679 * @fires toggle
680 * @fires change
681 */
682 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
683 var i, len, action;
684
685 this.changing = true;
686 for ( i = 0, len = this.list.length; i < len; i++ ) {
687 action = this.list[ i ];
688 action.toggle( action.hasMode( mode ) );
689 }
690
691 this.organized = false;
692 this.changing = false;
693 this.emit( 'change' );
694
695 return this;
696 };
697
698 /**
699 * Set the abilities of the specified actions.
700 *
701 * Action widgets that are configured with the specified actions will be enabled
702 * or disabled based on the boolean values specified in the `actions`
703 * parameter.
704 *
705 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
706 * values that indicate whether or not the action should be enabled.
707 * @chainable
708 */
709 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
710 var i, len, action, item;
711
712 for ( i = 0, len = this.list.length; i < len; i++ ) {
713 item = this.list[ i ];
714 action = item.getAction();
715 if ( actions[ action ] !== undefined ) {
716 item.setDisabled( !actions[ action ] );
717 }
718 }
719
720 return this;
721 };
722
723 /**
724 * Executes a function once per action.
725 *
726 * When making changes to multiple actions, use this method instead of iterating over the actions
727 * manually to defer emitting a #change event until after all actions have been changed.
728 *
729 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
730 * @param {Function} callback Callback to run for each action; callback is invoked with three
731 * arguments: the action, the action's index, the list of actions being iterated over
732 * @chainable
733 */
734 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
735 this.changed = false;
736 this.changing = true;
737 this.get( filter ).forEach( callback );
738 this.changing = false;
739 if ( this.changed ) {
740 this.emit( 'change' );
741 }
742
743 return this;
744 };
745
746 /**
747 * Add action widgets to the action set.
748 *
749 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
750 * @chainable
751 * @fires add
752 * @fires change
753 */
754 OO.ui.ActionSet.prototype.add = function ( actions ) {
755 var i, len, action;
756
757 this.changing = true;
758 for ( i = 0, len = actions.length; i < len; i++ ) {
759 action = actions[ i ];
760 action.connect( this, {
761 click: [ 'emit', 'click', action ],
762 resize: [ 'emit', 'resize', action ],
763 toggle: [ 'onActionChange' ]
764 } );
765 this.list.push( action );
766 }
767 this.organized = false;
768 this.emit( 'add', actions );
769 this.changing = false;
770 this.emit( 'change' );
771
772 return this;
773 };
774
775 /**
776 * Remove action widgets from the set.
777 *
778 * To remove all actions, you may wish to use the #clear method instead.
779 *
780 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
781 * @chainable
782 * @fires remove
783 * @fires change
784 */
785 OO.ui.ActionSet.prototype.remove = function ( actions ) {
786 var i, len, index, action;
787
788 this.changing = true;
789 for ( i = 0, len = actions.length; i < len; i++ ) {
790 action = actions[ i ];
791 index = this.list.indexOf( action );
792 if ( index !== -1 ) {
793 action.disconnect( this );
794 this.list.splice( index, 1 );
795 }
796 }
797 this.organized = false;
798 this.emit( 'remove', actions );
799 this.changing = false;
800 this.emit( 'change' );
801
802 return this;
803 };
804
805 /**
806 * Remove all action widets from the set.
807 *
808 * To remove only specified actions, use the {@link #method-remove remove} method instead.
809 *
810 * @chainable
811 * @fires remove
812 * @fires change
813 */
814 OO.ui.ActionSet.prototype.clear = function () {
815 var i, len, action,
816 removed = this.list.slice();
817
818 this.changing = true;
819 for ( i = 0, len = this.list.length; i < len; i++ ) {
820 action = this.list[ i ];
821 action.disconnect( this );
822 }
823
824 this.list = [];
825
826 this.organized = false;
827 this.emit( 'remove', removed );
828 this.changing = false;
829 this.emit( 'change' );
830
831 return this;
832 };
833
834 /**
835 * Organize actions.
836 *
837 * This is called whenever organized information is requested. It will only reorganize the actions
838 * if something has changed since the last time it ran.
839 *
840 * @private
841 * @chainable
842 */
843 OO.ui.ActionSet.prototype.organize = function () {
844 var i, iLen, j, jLen, flag, action, category, list, item, special,
845 specialFlags = this.constructor.static.specialFlags;
846
847 if ( !this.organized ) {
848 this.categorized = {};
849 this.special = {};
850 this.others = [];
851 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
852 action = this.list[ i ];
853 if ( action.isVisible() ) {
854 // Populate categories
855 for ( category in this.categories ) {
856 if ( !this.categorized[ category ] ) {
857 this.categorized[ category ] = {};
858 }
859 list = action[ this.categories[ category ] ]();
860 if ( !Array.isArray( list ) ) {
861 list = [ list ];
862 }
863 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
864 item = list[ j ];
865 if ( !this.categorized[ category ][ item ] ) {
866 this.categorized[ category ][ item ] = [];
867 }
868 this.categorized[ category ][ item ].push( action );
869 }
870 }
871 // Populate special/others
872 special = false;
873 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
874 flag = specialFlags[ j ];
875 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
876 this.special[ flag ] = action;
877 special = true;
878 break;
879 }
880 }
881 if ( !special ) {
882 this.others.push( action );
883 }
884 }
885 }
886 this.organized = true;
887 }
888
889 return this;
890 };
891
892 /**
893 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
894 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
895 * connected to them and can't be interacted with.
896 *
897 * @abstract
898 * @class
899 *
900 * @constructor
901 * @param {Object} [config] Configuration options
902 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
903 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
904 * for an example.
905 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
906 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
907 * @cfg {string} [text] Text to insert
908 * @cfg {Array} [content] An array of content elements to append (after #text).
909 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
910 * Instances of OO.ui.Element will have their $element appended.
911 * @cfg {jQuery} [$content] Content elements to append (after #text)
912 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
913 * Data can also be specified with the #setData method.
914 */
915 OO.ui.Element = function OoUiElement( config ) {
916 // Configuration initialization
917 config = config || {};
918
919 // Properties
920 this.$ = $;
921 this.visible = true;
922 this.data = config.data;
923 this.$element = config.$element ||
924 $( document.createElement( this.getTagName() ) );
925 this.elementGroup = null;
926 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
927 this.updateThemeClassesPending = false;
928
929 // Initialization
930 if ( Array.isArray( config.classes ) ) {
931 this.$element.addClass( config.classes.join( ' ' ) );
932 }
933 if ( config.id ) {
934 this.$element.attr( 'id', config.id );
935 }
936 if ( config.text ) {
937 this.$element.text( config.text );
938 }
939 if ( config.content ) {
940 // The `content` property treats plain strings as text; use an
941 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
942 // appropriate $element appended.
943 this.$element.append( config.content.map( function ( v ) {
944 if ( typeof v === 'string' ) {
945 // Escape string so it is properly represented in HTML.
946 return document.createTextNode( v );
947 } else if ( v instanceof OO.ui.HtmlSnippet ) {
948 // Bypass escaping.
949 return v.toString();
950 } else if ( v instanceof OO.ui.Element ) {
951 return v.$element;
952 }
953 return v;
954 } ) );
955 }
956 if ( config.$content ) {
957 // The `$content` property treats plain strings as HTML.
958 this.$element.append( config.$content );
959 }
960 };
961
962 /* Setup */
963
964 OO.initClass( OO.ui.Element );
965
966 /* Static Properties */
967
968 /**
969 * The name of the HTML tag used by the element.
970 *
971 * The static value may be ignored if the #getTagName method is overridden.
972 *
973 * @static
974 * @inheritable
975 * @property {string}
976 */
977 OO.ui.Element.static.tagName = 'div';
978
979 /* Static Methods */
980
981 /**
982 * Reconstitute a JavaScript object corresponding to a widget created
983 * by the PHP implementation.
984 *
985 * @param {string|HTMLElement|jQuery} idOrNode
986 * A DOM id (if a string) or node for the widget to infuse.
987 * @return {OO.ui.Element}
988 * The `OO.ui.Element` corresponding to this (infusable) document node.
989 * For `Tag` objects emitted on the HTML side (used occasionally for content)
990 * the value returned is a newly-created Element wrapping around the existing
991 * DOM node.
992 */
993 OO.ui.Element.static.infuse = function ( idOrNode ) {
994 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, true );
995 // Verify that the type matches up.
996 // FIXME: uncomment after T89721 is fixed (see T90929)
997 /*
998 if ( !( obj instanceof this['class'] ) ) {
999 throw new Error( 'Infusion type mismatch!' );
1000 }
1001 */
1002 return obj;
1003 };
1004
1005 /**
1006 * Implementation helper for `infuse`; skips the type check and has an
1007 * extra property so that only the top-level invocation touches the DOM.
1008 * @private
1009 * @param {string|HTMLElement|jQuery} idOrNode
1010 * @param {boolean} top True only for top-level invocation.
1011 * @return {OO.ui.Element}
1012 */
1013 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, top ) {
1014 // look for a cached result of a previous infusion.
1015 var id, $elem, data, cls, obj;
1016 if ( typeof idOrNode === 'string' ) {
1017 id = idOrNode;
1018 $elem = $( document.getElementById( id ) );
1019 } else {
1020 $elem = $( idOrNode );
1021 id = $elem.attr( 'id' );
1022 }
1023 data = $elem.data( 'ooui-infused' );
1024 if ( data ) {
1025 // cached!
1026 if ( data === true ) {
1027 throw new Error( 'Circular dependency! ' + id );
1028 }
1029 return data;
1030 }
1031 if ( !$elem.length ) {
1032 throw new Error( 'Widget not found: ' + id );
1033 }
1034 data = $elem.attr( 'data-ooui' );
1035 if ( !data ) {
1036 throw new Error( 'No infusion data found: ' + id );
1037 }
1038 try {
1039 data = $.parseJSON( data );
1040 } catch ( _ ) {
1041 data = null;
1042 }
1043 if ( !( data && data._ ) ) {
1044 throw new Error( 'No valid infusion data found: ' + id );
1045 }
1046 if ( data._ === 'Tag' ) {
1047 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1048 return new OO.ui.Element( { $element: $elem } );
1049 }
1050 cls = OO.ui[data._];
1051 if ( !cls ) {
1052 throw new Error( 'Unknown widget type: ' + id );
1053 }
1054 $elem.data( 'ooui-infused', true ); // prevent loops
1055 data.id = id; // implicit
1056 data = OO.copy( data, null, function deserialize( value ) {
1057 if ( OO.isPlainObject( value ) ) {
1058 if ( value.tag ) {
1059 return OO.ui.Element.static.unsafeInfuse( value.tag, false );
1060 }
1061 if ( value.html ) {
1062 return new OO.ui.HtmlSnippet( value.html );
1063 }
1064 }
1065 } );
1066 // jscs:disable requireCapitalizedConstructors
1067 obj = new cls( data ); // rebuild widget
1068 // now replace old DOM with this new DOM.
1069 if ( top ) {
1070 $elem.replaceWith( obj.$element );
1071 }
1072 obj.$element.data( 'ooui-infused', obj );
1073 // set the 'data-ooui' attribute so we can identify infused widgets
1074 obj.$element.attr( 'data-ooui', '' );
1075 return obj;
1076 };
1077
1078 /**
1079 * Get a jQuery function within a specific document.
1080 *
1081 * @static
1082 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1083 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1084 * not in an iframe
1085 * @return {Function} Bound jQuery function
1086 */
1087 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1088 function wrapper( selector ) {
1089 return $( selector, wrapper.context );
1090 }
1091
1092 wrapper.context = this.getDocument( context );
1093
1094 if ( $iframe ) {
1095 wrapper.$iframe = $iframe;
1096 }
1097
1098 return wrapper;
1099 };
1100
1101 /**
1102 * Get the document of an element.
1103 *
1104 * @static
1105 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1106 * @return {HTMLDocument|null} Document object
1107 */
1108 OO.ui.Element.static.getDocument = function ( obj ) {
1109 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1110 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1111 // Empty jQuery selections might have a context
1112 obj.context ||
1113 // HTMLElement
1114 obj.ownerDocument ||
1115 // Window
1116 obj.document ||
1117 // HTMLDocument
1118 ( obj.nodeType === 9 && obj ) ||
1119 null;
1120 };
1121
1122 /**
1123 * Get the window of an element or document.
1124 *
1125 * @static
1126 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1127 * @return {Window} Window object
1128 */
1129 OO.ui.Element.static.getWindow = function ( obj ) {
1130 var doc = this.getDocument( obj );
1131 return doc.parentWindow || doc.defaultView;
1132 };
1133
1134 /**
1135 * Get the direction of an element or document.
1136 *
1137 * @static
1138 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1139 * @return {string} Text direction, either 'ltr' or 'rtl'
1140 */
1141 OO.ui.Element.static.getDir = function ( obj ) {
1142 var isDoc, isWin;
1143
1144 if ( obj instanceof jQuery ) {
1145 obj = obj[ 0 ];
1146 }
1147 isDoc = obj.nodeType === 9;
1148 isWin = obj.document !== undefined;
1149 if ( isDoc || isWin ) {
1150 if ( isWin ) {
1151 obj = obj.document;
1152 }
1153 obj = obj.body;
1154 }
1155 return $( obj ).css( 'direction' );
1156 };
1157
1158 /**
1159 * Get the offset between two frames.
1160 *
1161 * TODO: Make this function not use recursion.
1162 *
1163 * @static
1164 * @param {Window} from Window of the child frame
1165 * @param {Window} [to=window] Window of the parent frame
1166 * @param {Object} [offset] Offset to start with, used internally
1167 * @return {Object} Offset object, containing left and top properties
1168 */
1169 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1170 var i, len, frames, frame, rect;
1171
1172 if ( !to ) {
1173 to = window;
1174 }
1175 if ( !offset ) {
1176 offset = { top: 0, left: 0 };
1177 }
1178 if ( from.parent === from ) {
1179 return offset;
1180 }
1181
1182 // Get iframe element
1183 frames = from.parent.document.getElementsByTagName( 'iframe' );
1184 for ( i = 0, len = frames.length; i < len; i++ ) {
1185 if ( frames[ i ].contentWindow === from ) {
1186 frame = frames[ i ];
1187 break;
1188 }
1189 }
1190
1191 // Recursively accumulate offset values
1192 if ( frame ) {
1193 rect = frame.getBoundingClientRect();
1194 offset.left += rect.left;
1195 offset.top += rect.top;
1196 if ( from !== to ) {
1197 this.getFrameOffset( from.parent, offset );
1198 }
1199 }
1200 return offset;
1201 };
1202
1203 /**
1204 * Get the offset between two elements.
1205 *
1206 * The two elements may be in a different frame, but in that case the frame $element is in must
1207 * be contained in the frame $anchor is in.
1208 *
1209 * @static
1210 * @param {jQuery} $element Element whose position to get
1211 * @param {jQuery} $anchor Element to get $element's position relative to
1212 * @return {Object} Translated position coordinates, containing top and left properties
1213 */
1214 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1215 var iframe, iframePos,
1216 pos = $element.offset(),
1217 anchorPos = $anchor.offset(),
1218 elementDocument = this.getDocument( $element ),
1219 anchorDocument = this.getDocument( $anchor );
1220
1221 // If $element isn't in the same document as $anchor, traverse up
1222 while ( elementDocument !== anchorDocument ) {
1223 iframe = elementDocument.defaultView.frameElement;
1224 if ( !iframe ) {
1225 throw new Error( '$element frame is not contained in $anchor frame' );
1226 }
1227 iframePos = $( iframe ).offset();
1228 pos.left += iframePos.left;
1229 pos.top += iframePos.top;
1230 elementDocument = iframe.ownerDocument;
1231 }
1232 pos.left -= anchorPos.left;
1233 pos.top -= anchorPos.top;
1234 return pos;
1235 };
1236
1237 /**
1238 * Get element border sizes.
1239 *
1240 * @static
1241 * @param {HTMLElement} el Element to measure
1242 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1243 */
1244 OO.ui.Element.static.getBorders = function ( el ) {
1245 var doc = el.ownerDocument,
1246 win = doc.parentWindow || doc.defaultView,
1247 style = win && win.getComputedStyle ?
1248 win.getComputedStyle( el, null ) :
1249 el.currentStyle,
1250 $el = $( el ),
1251 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1252 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1253 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1254 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1255
1256 return {
1257 top: top,
1258 left: left,
1259 bottom: bottom,
1260 right: right
1261 };
1262 };
1263
1264 /**
1265 * Get dimensions of an element or window.
1266 *
1267 * @static
1268 * @param {HTMLElement|Window} el Element to measure
1269 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1270 */
1271 OO.ui.Element.static.getDimensions = function ( el ) {
1272 var $el, $win,
1273 doc = el.ownerDocument || el.document,
1274 win = doc.parentWindow || doc.defaultView;
1275
1276 if ( win === el || el === doc.documentElement ) {
1277 $win = $( win );
1278 return {
1279 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1280 scroll: {
1281 top: $win.scrollTop(),
1282 left: $win.scrollLeft()
1283 },
1284 scrollbar: { right: 0, bottom: 0 },
1285 rect: {
1286 top: 0,
1287 left: 0,
1288 bottom: $win.innerHeight(),
1289 right: $win.innerWidth()
1290 }
1291 };
1292 } else {
1293 $el = $( el );
1294 return {
1295 borders: this.getBorders( el ),
1296 scroll: {
1297 top: $el.scrollTop(),
1298 left: $el.scrollLeft()
1299 },
1300 scrollbar: {
1301 right: $el.innerWidth() - el.clientWidth,
1302 bottom: $el.innerHeight() - el.clientHeight
1303 },
1304 rect: el.getBoundingClientRect()
1305 };
1306 }
1307 };
1308
1309 /**
1310 * Get scrollable object parent
1311 *
1312 * documentElement can't be used to get or set the scrollTop
1313 * property on Blink. Changing and testing its value lets us
1314 * use 'body' or 'documentElement' based on what is working.
1315 *
1316 * https://code.google.com/p/chromium/issues/detail?id=303131
1317 *
1318 * @static
1319 * @param {HTMLElement} el Element to find scrollable parent for
1320 * @return {HTMLElement} Scrollable parent
1321 */
1322 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1323 var scrollTop, body;
1324
1325 if ( OO.ui.scrollableElement === undefined ) {
1326 body = el.ownerDocument.body;
1327 scrollTop = body.scrollTop;
1328 body.scrollTop = 1;
1329
1330 if ( body.scrollTop === 1 ) {
1331 body.scrollTop = scrollTop;
1332 OO.ui.scrollableElement = 'body';
1333 } else {
1334 OO.ui.scrollableElement = 'documentElement';
1335 }
1336 }
1337
1338 return el.ownerDocument[ OO.ui.scrollableElement ];
1339 };
1340
1341 /**
1342 * Get closest scrollable container.
1343 *
1344 * Traverses up until either a scrollable element or the root is reached, in which case the window
1345 * will be returned.
1346 *
1347 * @static
1348 * @param {HTMLElement} el Element to find scrollable container for
1349 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1350 * @return {HTMLElement} Closest scrollable container
1351 */
1352 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1353 var i, val,
1354 props = [ 'overflow' ],
1355 $parent = $( el ).parent();
1356
1357 if ( dimension === 'x' || dimension === 'y' ) {
1358 props.push( 'overflow-' + dimension );
1359 }
1360
1361 while ( $parent.length ) {
1362 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1363 return $parent[ 0 ];
1364 }
1365 i = props.length;
1366 while ( i-- ) {
1367 val = $parent.css( props[ i ] );
1368 if ( val === 'auto' || val === 'scroll' ) {
1369 return $parent[ 0 ];
1370 }
1371 }
1372 $parent = $parent.parent();
1373 }
1374 return this.getDocument( el ).body;
1375 };
1376
1377 /**
1378 * Scroll element into view.
1379 *
1380 * @static
1381 * @param {HTMLElement} el Element to scroll into view
1382 * @param {Object} [config] Configuration options
1383 * @param {string} [config.duration] jQuery animation duration value
1384 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1385 * to scroll in both directions
1386 * @param {Function} [config.complete] Function to call when scrolling completes
1387 */
1388 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1389 // Configuration initialization
1390 config = config || {};
1391
1392 var rel, anim = {},
1393 callback = typeof config.complete === 'function' && config.complete,
1394 sc = this.getClosestScrollableContainer( el, config.direction ),
1395 $sc = $( sc ),
1396 eld = this.getDimensions( el ),
1397 scd = this.getDimensions( sc ),
1398 $win = $( this.getWindow( el ) );
1399
1400 // Compute the distances between the edges of el and the edges of the scroll viewport
1401 if ( $sc.is( 'html, body' ) ) {
1402 // If the scrollable container is the root, this is easy
1403 rel = {
1404 top: eld.rect.top,
1405 bottom: $win.innerHeight() - eld.rect.bottom,
1406 left: eld.rect.left,
1407 right: $win.innerWidth() - eld.rect.right
1408 };
1409 } else {
1410 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1411 rel = {
1412 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1413 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1414 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1415 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1416 };
1417 }
1418
1419 if ( !config.direction || config.direction === 'y' ) {
1420 if ( rel.top < 0 ) {
1421 anim.scrollTop = scd.scroll.top + rel.top;
1422 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1423 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1424 }
1425 }
1426 if ( !config.direction || config.direction === 'x' ) {
1427 if ( rel.left < 0 ) {
1428 anim.scrollLeft = scd.scroll.left + rel.left;
1429 } else if ( rel.left > 0 && rel.right < 0 ) {
1430 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1431 }
1432 }
1433 if ( !$.isEmptyObject( anim ) ) {
1434 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1435 if ( callback ) {
1436 $sc.queue( function ( next ) {
1437 callback();
1438 next();
1439 } );
1440 }
1441 } else {
1442 if ( callback ) {
1443 callback();
1444 }
1445 }
1446 };
1447
1448 /**
1449 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1450 * and reserve space for them, because it probably doesn't.
1451 *
1452 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1453 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1454 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1455 * and then reattach (or show) them back.
1456 *
1457 * @static
1458 * @param {HTMLElement} el Element to reconsider the scrollbars on
1459 */
1460 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1461 var i, len, nodes = [];
1462 // Detach all children
1463 while ( el.firstChild ) {
1464 nodes.push( el.firstChild );
1465 el.removeChild( el.firstChild );
1466 }
1467 // Force reflow
1468 void el.offsetHeight;
1469 // Reattach all children
1470 for ( i = 0, len = nodes.length; i < len; i++ ) {
1471 el.appendChild( nodes[ i ] );
1472 }
1473 };
1474
1475 /* Methods */
1476
1477 /**
1478 * Toggle visibility of an element.
1479 *
1480 * @param {boolean} [show] Make element visible, omit to toggle visibility
1481 * @fires visible
1482 * @chainable
1483 */
1484 OO.ui.Element.prototype.toggle = function ( show ) {
1485 show = show === undefined ? !this.visible : !!show;
1486
1487 if ( show !== this.isVisible() ) {
1488 this.visible = show;
1489 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1490 this.emit( 'toggle', show );
1491 }
1492
1493 return this;
1494 };
1495
1496 /**
1497 * Check if element is visible.
1498 *
1499 * @return {boolean} element is visible
1500 */
1501 OO.ui.Element.prototype.isVisible = function () {
1502 return this.visible;
1503 };
1504
1505 /**
1506 * Get element data.
1507 *
1508 * @return {Mixed} Element data
1509 */
1510 OO.ui.Element.prototype.getData = function () {
1511 return this.data;
1512 };
1513
1514 /**
1515 * Set element data.
1516 *
1517 * @param {Mixed} Element data
1518 * @chainable
1519 */
1520 OO.ui.Element.prototype.setData = function ( data ) {
1521 this.data = data;
1522 return this;
1523 };
1524
1525 /**
1526 * Check if element supports one or more methods.
1527 *
1528 * @param {string|string[]} methods Method or list of methods to check
1529 * @return {boolean} All methods are supported
1530 */
1531 OO.ui.Element.prototype.supports = function ( methods ) {
1532 var i, len,
1533 support = 0;
1534
1535 methods = Array.isArray( methods ) ? methods : [ methods ];
1536 for ( i = 0, len = methods.length; i < len; i++ ) {
1537 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1538 support++;
1539 }
1540 }
1541
1542 return methods.length === support;
1543 };
1544
1545 /**
1546 * Update the theme-provided classes.
1547 *
1548 * @localdoc This is called in element mixins and widget classes any time state changes.
1549 * Updating is debounced, minimizing overhead of changing multiple attributes and
1550 * guaranteeing that theme updates do not occur within an element's constructor
1551 */
1552 OO.ui.Element.prototype.updateThemeClasses = function () {
1553 if ( !this.updateThemeClassesPending ) {
1554 this.updateThemeClassesPending = true;
1555 setTimeout( this.debouncedUpdateThemeClassesHandler );
1556 }
1557 };
1558
1559 /**
1560 * @private
1561 */
1562 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1563 OO.ui.theme.updateElementClasses( this );
1564 this.updateThemeClassesPending = false;
1565 };
1566
1567 /**
1568 * Get the HTML tag name.
1569 *
1570 * Override this method to base the result on instance information.
1571 *
1572 * @return {string} HTML tag name
1573 */
1574 OO.ui.Element.prototype.getTagName = function () {
1575 return this.constructor.static.tagName;
1576 };
1577
1578 /**
1579 * Check if the element is attached to the DOM
1580 * @return {boolean} The element is attached to the DOM
1581 */
1582 OO.ui.Element.prototype.isElementAttached = function () {
1583 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1584 };
1585
1586 /**
1587 * Get the DOM document.
1588 *
1589 * @return {HTMLDocument} Document object
1590 */
1591 OO.ui.Element.prototype.getElementDocument = function () {
1592 // Don't cache this in other ways either because subclasses could can change this.$element
1593 return OO.ui.Element.static.getDocument( this.$element );
1594 };
1595
1596 /**
1597 * Get the DOM window.
1598 *
1599 * @return {Window} Window object
1600 */
1601 OO.ui.Element.prototype.getElementWindow = function () {
1602 return OO.ui.Element.static.getWindow( this.$element );
1603 };
1604
1605 /**
1606 * Get closest scrollable container.
1607 */
1608 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1609 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1610 };
1611
1612 /**
1613 * Get group element is in.
1614 *
1615 * @return {OO.ui.GroupElement|null} Group element, null if none
1616 */
1617 OO.ui.Element.prototype.getElementGroup = function () {
1618 return this.elementGroup;
1619 };
1620
1621 /**
1622 * Set group element is in.
1623 *
1624 * @param {OO.ui.GroupElement|null} group Group element, null if none
1625 * @chainable
1626 */
1627 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1628 this.elementGroup = group;
1629 return this;
1630 };
1631
1632 /**
1633 * Scroll element into view.
1634 *
1635 * @param {Object} [config] Configuration options
1636 */
1637 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1638 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1639 };
1640
1641 /**
1642 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1643 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1644 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1645 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1646 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1647 *
1648 * @abstract
1649 * @class
1650 * @extends OO.ui.Element
1651 * @mixins OO.EventEmitter
1652 *
1653 * @constructor
1654 * @param {Object} [config] Configuration options
1655 */
1656 OO.ui.Layout = function OoUiLayout( config ) {
1657 // Configuration initialization
1658 config = config || {};
1659
1660 // Parent constructor
1661 OO.ui.Layout.super.call( this, config );
1662
1663 // Mixin constructors
1664 OO.EventEmitter.call( this );
1665
1666 // Initialization
1667 this.$element.addClass( 'oo-ui-layout' );
1668 };
1669
1670 /* Setup */
1671
1672 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1673 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1674
1675 /**
1676 * Widgets are compositions of one or more OOjs UI elements that users can both view
1677 * and interact with. All widgets can be configured and modified via a standard API,
1678 * and their state can change dynamically according to a model.
1679 *
1680 * @abstract
1681 * @class
1682 * @extends OO.ui.Element
1683 * @mixins OO.EventEmitter
1684 *
1685 * @constructor
1686 * @param {Object} [config] Configuration options
1687 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1688 * appearance reflects this state.
1689 */
1690 OO.ui.Widget = function OoUiWidget( config ) {
1691 // Initialize config
1692 config = $.extend( { disabled: false }, config );
1693
1694 // Parent constructor
1695 OO.ui.Widget.super.call( this, config );
1696
1697 // Mixin constructors
1698 OO.EventEmitter.call( this );
1699
1700 // Properties
1701 this.disabled = null;
1702 this.wasDisabled = null;
1703
1704 // Initialization
1705 this.$element.addClass( 'oo-ui-widget' );
1706 this.setDisabled( !!config.disabled );
1707 };
1708
1709 /* Setup */
1710
1711 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1712 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1713
1714 /* Events */
1715
1716 /**
1717 * @event disable
1718 *
1719 * A 'disable' event is emitted when a widget is disabled.
1720 *
1721 * @param {boolean} disabled Widget is disabled
1722 */
1723
1724 /**
1725 * @event toggle
1726 *
1727 * A 'toggle' event is emitted when the visibility of the widget changes.
1728 *
1729 * @param {boolean} visible Widget is visible
1730 */
1731
1732 /* Methods */
1733
1734 /**
1735 * Check if the widget is disabled.
1736 *
1737 * @return {boolean} Widget is disabled
1738 */
1739 OO.ui.Widget.prototype.isDisabled = function () {
1740 return this.disabled;
1741 };
1742
1743 /**
1744 * Set the 'disabled' state of the widget.
1745 *
1746 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1747 *
1748 * @param {boolean} disabled Disable widget
1749 * @chainable
1750 */
1751 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1752 var isDisabled;
1753
1754 this.disabled = !!disabled;
1755 isDisabled = this.isDisabled();
1756 if ( isDisabled !== this.wasDisabled ) {
1757 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1758 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1759 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1760 this.emit( 'disable', isDisabled );
1761 this.updateThemeClasses();
1762 }
1763 this.wasDisabled = isDisabled;
1764
1765 return this;
1766 };
1767
1768 /**
1769 * Update the disabled state, in case of changes in parent widget.
1770 *
1771 * @chainable
1772 */
1773 OO.ui.Widget.prototype.updateDisabled = function () {
1774 this.setDisabled( this.disabled );
1775 return this;
1776 };
1777
1778 /**
1779 * A window is a container for elements that are in a child frame. They are used with
1780 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1781 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1782 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1783 * the window manager will choose a sensible fallback.
1784 *
1785 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1786 * different processes are executed:
1787 *
1788 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1789 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1790 * the window.
1791 *
1792 * - {@link #getSetupProcess} method is called and its result executed
1793 * - {@link #getReadyProcess} method is called and its result executed
1794 *
1795 * **opened**: The window is now open
1796 *
1797 * **closing**: The closing stage begins when the window manager's
1798 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1799 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1800 *
1801 * - {@link #getHoldProcess} method is called and its result executed
1802 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1803 *
1804 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1805 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1806 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1807 * processing can complete. Always assume window processes are executed asynchronously.
1808 *
1809 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1810 *
1811 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1812 *
1813 * @abstract
1814 * @class
1815 * @extends OO.ui.Element
1816 * @mixins OO.EventEmitter
1817 *
1818 * @constructor
1819 * @param {Object} [config] Configuration options
1820 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1821 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1822 */
1823 OO.ui.Window = function OoUiWindow( config ) {
1824 // Configuration initialization
1825 config = config || {};
1826
1827 // Parent constructor
1828 OO.ui.Window.super.call( this, config );
1829
1830 // Mixin constructors
1831 OO.EventEmitter.call( this );
1832
1833 // Properties
1834 this.manager = null;
1835 this.size = config.size || this.constructor.static.size;
1836 this.$frame = $( '<div>' );
1837 this.$overlay = $( '<div>' );
1838 this.$content = $( '<div>' );
1839
1840 // Initialization
1841 this.$overlay.addClass( 'oo-ui-window-overlay' );
1842 this.$content
1843 .addClass( 'oo-ui-window-content' )
1844 .attr( 'tabindex', 0 );
1845 this.$frame
1846 .addClass( 'oo-ui-window-frame' )
1847 .append( this.$content );
1848
1849 this.$element
1850 .addClass( 'oo-ui-window' )
1851 .append( this.$frame, this.$overlay );
1852
1853 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1854 // that reference properties not initialized at that time of parent class construction
1855 // TODO: Find a better way to handle post-constructor setup
1856 this.visible = false;
1857 this.$element.addClass( 'oo-ui-element-hidden' );
1858 };
1859
1860 /* Setup */
1861
1862 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1863 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1864
1865 /* Static Properties */
1866
1867 /**
1868 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1869 *
1870 * The static size is used if no #size is configured during construction.
1871 *
1872 * @static
1873 * @inheritable
1874 * @property {string}
1875 */
1876 OO.ui.Window.static.size = 'medium';
1877
1878 /* Methods */
1879
1880 /**
1881 * Handle mouse down events.
1882 *
1883 * @private
1884 * @param {jQuery.Event} e Mouse down event
1885 */
1886 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1887 // Prevent clicking on the click-block from stealing focus
1888 if ( e.target === this.$element[ 0 ] ) {
1889 return false;
1890 }
1891 };
1892
1893 /**
1894 * Check if the window has been initialized.
1895 *
1896 * Initialization occurs when a window is added to a manager.
1897 *
1898 * @return {boolean} Window has been initialized
1899 */
1900 OO.ui.Window.prototype.isInitialized = function () {
1901 return !!this.manager;
1902 };
1903
1904 /**
1905 * Check if the window is visible.
1906 *
1907 * @return {boolean} Window is visible
1908 */
1909 OO.ui.Window.prototype.isVisible = function () {
1910 return this.visible;
1911 };
1912
1913 /**
1914 * Check if the window is opening.
1915 *
1916 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1917 * method.
1918 *
1919 * @return {boolean} Window is opening
1920 */
1921 OO.ui.Window.prototype.isOpening = function () {
1922 return this.manager.isOpening( this );
1923 };
1924
1925 /**
1926 * Check if the window is closing.
1927 *
1928 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1929 *
1930 * @return {boolean} Window is closing
1931 */
1932 OO.ui.Window.prototype.isClosing = function () {
1933 return this.manager.isClosing( this );
1934 };
1935
1936 /**
1937 * Check if the window is opened.
1938 *
1939 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1940 *
1941 * @return {boolean} Window is opened
1942 */
1943 OO.ui.Window.prototype.isOpened = function () {
1944 return this.manager.isOpened( this );
1945 };
1946
1947 /**
1948 * Get the window manager.
1949 *
1950 * All windows must be attached to a window manager, which is used to open
1951 * and close the window and control its presentation.
1952 *
1953 * @return {OO.ui.WindowManager} Manager of window
1954 */
1955 OO.ui.Window.prototype.getManager = function () {
1956 return this.manager;
1957 };
1958
1959 /**
1960 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1961 *
1962 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1963 */
1964 OO.ui.Window.prototype.getSize = function () {
1965 return this.size;
1966 };
1967
1968 /**
1969 * Disable transitions on window's frame for the duration of the callback function, then enable them
1970 * back.
1971 *
1972 * @private
1973 * @param {Function} callback Function to call while transitions are disabled
1974 */
1975 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1976 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1977 // Disable transitions first, otherwise we'll get values from when the window was animating.
1978 var oldTransition,
1979 styleObj = this.$frame[ 0 ].style;
1980 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1981 styleObj.MozTransition || styleObj.WebkitTransition;
1982 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1983 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1984 callback();
1985 // Force reflow to make sure the style changes done inside callback really are not transitioned
1986 this.$frame.height();
1987 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1988 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1989 };
1990
1991 /**
1992 * Get the height of the full window contents (i.e., the window head, body and foot together).
1993 *
1994 * What consistitutes the head, body, and foot varies depending on the window type.
1995 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1996 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1997 * and special actions in the head, and dialog content in the body.
1998 *
1999 * To get just the height of the dialog body, use the #getBodyHeight method.
2000 *
2001 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2002 */
2003 OO.ui.Window.prototype.getContentHeight = function () {
2004 var bodyHeight,
2005 win = this,
2006 bodyStyleObj = this.$body[ 0 ].style,
2007 frameStyleObj = this.$frame[ 0 ].style;
2008
2009 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2010 // Disable transitions first, otherwise we'll get values from when the window was animating.
2011 this.withoutSizeTransitions( function () {
2012 var oldHeight = frameStyleObj.height,
2013 oldPosition = bodyStyleObj.position;
2014 frameStyleObj.height = '1px';
2015 // Force body to resize to new width
2016 bodyStyleObj.position = 'relative';
2017 bodyHeight = win.getBodyHeight();
2018 frameStyleObj.height = oldHeight;
2019 bodyStyleObj.position = oldPosition;
2020 } );
2021
2022 return (
2023 // Add buffer for border
2024 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2025 // Use combined heights of children
2026 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2027 );
2028 };
2029
2030 /**
2031 * Get the height of the window body.
2032 *
2033 * To get the height of the full window contents (the window body, head, and foot together),
2034 * use #getContentHeight.
2035 *
2036 * When this function is called, the window will temporarily have been resized
2037 * to height=1px, so .scrollHeight measurements can be taken accurately.
2038 *
2039 * @return {number} Height of the window body in pixels
2040 */
2041 OO.ui.Window.prototype.getBodyHeight = function () {
2042 return this.$body[ 0 ].scrollHeight;
2043 };
2044
2045 /**
2046 * Get the directionality of the frame (right-to-left or left-to-right).
2047 *
2048 * @return {string} Directionality: `'ltr'` or `'rtl'`
2049 */
2050 OO.ui.Window.prototype.getDir = function () {
2051 return this.dir;
2052 };
2053
2054 /**
2055 * Get the 'setup' process.
2056 *
2057 * The setup process is used to set up a window for use in a particular context,
2058 * based on the `data` argument. This method is called during the opening phase of the window’s
2059 * lifecycle.
2060 *
2061 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2062 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2063 * of OO.ui.Process.
2064 *
2065 * To add window content that persists between openings, you may wish to use the #initialize method
2066 * instead.
2067 *
2068 * @abstract
2069 * @param {Object} [data] Window opening data
2070 * @return {OO.ui.Process} Setup process
2071 */
2072 OO.ui.Window.prototype.getSetupProcess = function () {
2073 return new OO.ui.Process();
2074 };
2075
2076 /**
2077 * Get the ‘ready’ process.
2078 *
2079 * The ready process is used to ready a window for use in a particular
2080 * context, based on the `data` argument. This method is called during the opening phase of
2081 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2082 *
2083 * Override this method to add additional steps to the ‘ready’ process the parent method
2084 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2085 * methods of OO.ui.Process.
2086 *
2087 * @abstract
2088 * @param {Object} [data] Window opening data
2089 * @return {OO.ui.Process} Ready process
2090 */
2091 OO.ui.Window.prototype.getReadyProcess = function () {
2092 return new OO.ui.Process();
2093 };
2094
2095 /**
2096 * Get the 'hold' process.
2097 *
2098 * The hold proccess is used to keep a window from being used in a particular context,
2099 * based on the `data` argument. This method is called during the closing phase of the window’s
2100 * lifecycle.
2101 *
2102 * Override this method to add additional steps to the 'hold' process the parent method provides
2103 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2104 * of OO.ui.Process.
2105 *
2106 * @abstract
2107 * @param {Object} [data] Window closing data
2108 * @return {OO.ui.Process} Hold process
2109 */
2110 OO.ui.Window.prototype.getHoldProcess = function () {
2111 return new OO.ui.Process();
2112 };
2113
2114 /**
2115 * Get the ‘teardown’ process.
2116 *
2117 * The teardown process is used to teardown a window after use. During teardown,
2118 * user interactions within the window are conveyed and the window is closed, based on the `data`
2119 * argument. This method is called during the closing phase of the window’s lifecycle.
2120 *
2121 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2122 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2123 * of OO.ui.Process.
2124 *
2125 * @abstract
2126 * @param {Object} [data] Window closing data
2127 * @return {OO.ui.Process} Teardown process
2128 */
2129 OO.ui.Window.prototype.getTeardownProcess = function () {
2130 return new OO.ui.Process();
2131 };
2132
2133 /**
2134 * Set the window manager.
2135 *
2136 * This will cause the window to initialize. Calling it more than once will cause an error.
2137 *
2138 * @param {OO.ui.WindowManager} manager Manager for this window
2139 * @throws {Error} An error is thrown if the method is called more than once
2140 * @chainable
2141 */
2142 OO.ui.Window.prototype.setManager = function ( manager ) {
2143 if ( this.manager ) {
2144 throw new Error( 'Cannot set window manager, window already has a manager' );
2145 }
2146
2147 this.manager = manager;
2148 this.initialize();
2149
2150 return this;
2151 };
2152
2153 /**
2154 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2155 *
2156 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2157 * `full`
2158 * @chainable
2159 */
2160 OO.ui.Window.prototype.setSize = function ( size ) {
2161 this.size = size;
2162 this.updateSize();
2163 return this;
2164 };
2165
2166 /**
2167 * Update the window size.
2168 *
2169 * @throws {Error} An error is thrown if the window is not attached to a window manager
2170 * @chainable
2171 */
2172 OO.ui.Window.prototype.updateSize = function () {
2173 if ( !this.manager ) {
2174 throw new Error( 'Cannot update window size, must be attached to a manager' );
2175 }
2176
2177 this.manager.updateWindowSize( this );
2178
2179 return this;
2180 };
2181
2182 /**
2183 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2184 * when the window is opening. In general, setDimensions should not be called directly.
2185 *
2186 * To set the size of the window, use the #setSize method.
2187 *
2188 * @param {Object} dim CSS dimension properties
2189 * @param {string|number} [dim.width] Width
2190 * @param {string|number} [dim.minWidth] Minimum width
2191 * @param {string|number} [dim.maxWidth] Maximum width
2192 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2193 * @param {string|number} [dim.minWidth] Minimum height
2194 * @param {string|number} [dim.maxWidth] Maximum height
2195 * @chainable
2196 */
2197 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2198 var height,
2199 win = this,
2200 styleObj = this.$frame[ 0 ].style;
2201
2202 // Calculate the height we need to set using the correct width
2203 if ( dim.height === undefined ) {
2204 this.withoutSizeTransitions( function () {
2205 var oldWidth = styleObj.width;
2206 win.$frame.css( 'width', dim.width || '' );
2207 height = win.getContentHeight();
2208 styleObj.width = oldWidth;
2209 } );
2210 } else {
2211 height = dim.height;
2212 }
2213
2214 this.$frame.css( {
2215 width: dim.width || '',
2216 minWidth: dim.minWidth || '',
2217 maxWidth: dim.maxWidth || '',
2218 height: height || '',
2219 minHeight: dim.minHeight || '',
2220 maxHeight: dim.maxHeight || ''
2221 } );
2222
2223 return this;
2224 };
2225
2226 /**
2227 * Initialize window contents.
2228 *
2229 * Before the window is opened for the first time, #initialize is called so that content that
2230 * persists between openings can be added to the window.
2231 *
2232 * To set up a window with new content each time the window opens, use #getSetupProcess.
2233 *
2234 * @throws {Error} An error is thrown if the window is not attached to a window manager
2235 * @chainable
2236 */
2237 OO.ui.Window.prototype.initialize = function () {
2238 if ( !this.manager ) {
2239 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2240 }
2241
2242 // Properties
2243 this.$head = $( '<div>' );
2244 this.$body = $( '<div>' );
2245 this.$foot = $( '<div>' );
2246 this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2247 this.$document = $( this.getElementDocument() );
2248
2249 // Events
2250 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2251
2252 // Initialization
2253 this.$head.addClass( 'oo-ui-window-head' );
2254 this.$body.addClass( 'oo-ui-window-body' );
2255 this.$foot.addClass( 'oo-ui-window-foot' );
2256 this.$content.append( this.$head, this.$body, this.$foot );
2257
2258 return this;
2259 };
2260
2261 /**
2262 * Open the window.
2263 *
2264 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2265 * method, which returns a promise resolved when the window is done opening.
2266 *
2267 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2268 *
2269 * @param {Object} [data] Window opening data
2270 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2271 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2272 * value is a new promise, which is resolved when the window begins closing.
2273 * @throws {Error} An error is thrown if the window is not attached to a window manager
2274 */
2275 OO.ui.Window.prototype.open = function ( data ) {
2276 if ( !this.manager ) {
2277 throw new Error( 'Cannot open window, must be attached to a manager' );
2278 }
2279
2280 return this.manager.openWindow( this, data );
2281 };
2282
2283 /**
2284 * Close the window.
2285 *
2286 * This method is a wrapper around a call to the window
2287 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2288 * which returns a closing promise resolved when the window is done closing.
2289 *
2290 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2291 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2292 * the window closes.
2293 *
2294 * @param {Object} [data] Window closing data
2295 * @return {jQuery.Promise} Promise resolved when window is closed
2296 * @throws {Error} An error is thrown if the window is not attached to a window manager
2297 */
2298 OO.ui.Window.prototype.close = function ( data ) {
2299 if ( !this.manager ) {
2300 throw new Error( 'Cannot close window, must be attached to a manager' );
2301 }
2302
2303 return this.manager.closeWindow( this, data );
2304 };
2305
2306 /**
2307 * Setup window.
2308 *
2309 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2310 * by other systems.
2311 *
2312 * @param {Object} [data] Window opening data
2313 * @return {jQuery.Promise} Promise resolved when window is setup
2314 */
2315 OO.ui.Window.prototype.setup = function ( data ) {
2316 var win = this,
2317 deferred = $.Deferred();
2318
2319 this.toggle( true );
2320
2321 this.getSetupProcess( data ).execute().done( function () {
2322 // Force redraw by asking the browser to measure the elements' widths
2323 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2324 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2325 deferred.resolve();
2326 } );
2327
2328 return deferred.promise();
2329 };
2330
2331 /**
2332 * Ready window.
2333 *
2334 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2335 * by other systems.
2336 *
2337 * @param {Object} [data] Window opening data
2338 * @return {jQuery.Promise} Promise resolved when window is ready
2339 */
2340 OO.ui.Window.prototype.ready = function ( data ) {
2341 var win = this,
2342 deferred = $.Deferred();
2343
2344 this.$content.focus();
2345 this.getReadyProcess( data ).execute().done( function () {
2346 // Force redraw by asking the browser to measure the elements' widths
2347 win.$element.addClass( 'oo-ui-window-ready' ).width();
2348 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2349 deferred.resolve();
2350 } );
2351
2352 return deferred.promise();
2353 };
2354
2355 /**
2356 * Hold window.
2357 *
2358 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2359 * by other systems.
2360 *
2361 * @param {Object} [data] Window closing data
2362 * @return {jQuery.Promise} Promise resolved when window is held
2363 */
2364 OO.ui.Window.prototype.hold = function ( data ) {
2365 var win = this,
2366 deferred = $.Deferred();
2367
2368 this.getHoldProcess( data ).execute().done( function () {
2369 // Get the focused element within the window's content
2370 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2371
2372 // Blur the focused element
2373 if ( $focus.length ) {
2374 $focus[ 0 ].blur();
2375 }
2376
2377 // Force redraw by asking the browser to measure the elements' widths
2378 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2379 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2380 deferred.resolve();
2381 } );
2382
2383 return deferred.promise();
2384 };
2385
2386 /**
2387 * Teardown window.
2388 *
2389 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2390 * by other systems.
2391 *
2392 * @param {Object} [data] Window closing data
2393 * @return {jQuery.Promise} Promise resolved when window is torn down
2394 */
2395 OO.ui.Window.prototype.teardown = function ( data ) {
2396 var win = this;
2397
2398 return this.getTeardownProcess( data ).execute()
2399 .done( function () {
2400 // Force redraw by asking the browser to measure the elements' widths
2401 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2402 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2403 win.toggle( false );
2404 } );
2405 };
2406
2407 /**
2408 * The Dialog class serves as the base class for the other types of dialogs.
2409 * Unless extended to include controls, the rendered dialog box is a simple window
2410 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2411 * which opens, closes, and controls the presentation of the window. See the
2412 * [OOjs UI documentation on MediaWiki] [1] for more information.
2413 *
2414 * @example
2415 * // A simple dialog window.
2416 * function MyDialog( config ) {
2417 * MyDialog.super.call( this, config );
2418 * }
2419 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2420 * MyDialog.prototype.initialize = function () {
2421 * MyDialog.super.prototype.initialize.call( this );
2422 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2423 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2424 * this.$body.append( this.content.$element );
2425 * };
2426 * MyDialog.prototype.getBodyHeight = function () {
2427 * return this.content.$element.outerHeight( true );
2428 * };
2429 * var myDialog = new MyDialog( {
2430 * size: 'medium'
2431 * } );
2432 * // Create and append a window manager, which opens and closes the window.
2433 * var windowManager = new OO.ui.WindowManager();
2434 * $( 'body' ).append( windowManager.$element );
2435 * windowManager.addWindows( [ myDialog ] );
2436 * // Open the window!
2437 * windowManager.openWindow( myDialog );
2438 *
2439 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2440 *
2441 * @abstract
2442 * @class
2443 * @extends OO.ui.Window
2444 * @mixins OO.ui.PendingElement
2445 *
2446 * @constructor
2447 * @param {Object} [config] Configuration options
2448 */
2449 OO.ui.Dialog = function OoUiDialog( config ) {
2450 // Parent constructor
2451 OO.ui.Dialog.super.call( this, config );
2452
2453 // Mixin constructors
2454 OO.ui.PendingElement.call( this );
2455
2456 // Properties
2457 this.actions = new OO.ui.ActionSet();
2458 this.attachedActions = [];
2459 this.currentAction = null;
2460 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2461
2462 // Events
2463 this.actions.connect( this, {
2464 click: 'onActionClick',
2465 resize: 'onActionResize',
2466 change: 'onActionsChange'
2467 } );
2468
2469 // Initialization
2470 this.$element
2471 .addClass( 'oo-ui-dialog' )
2472 .attr( 'role', 'dialog' );
2473 };
2474
2475 /* Setup */
2476
2477 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2478 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2479
2480 /* Static Properties */
2481
2482 /**
2483 * Symbolic name of dialog.
2484 *
2485 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2486 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2487 *
2488 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2489 *
2490 * @abstract
2491 * @static
2492 * @inheritable
2493 * @property {string}
2494 */
2495 OO.ui.Dialog.static.name = '';
2496
2497 /**
2498 * The dialog title.
2499 *
2500 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2501 * that will produce a Label node or string. The title can also be specified with data passed to the
2502 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2503 *
2504 * @abstract
2505 * @static
2506 * @inheritable
2507 * @property {jQuery|string|Function}
2508 */
2509 OO.ui.Dialog.static.title = '';
2510
2511 /**
2512 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2513 *
2514 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2515 * value will be overriden.
2516 *
2517 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2518 *
2519 * @static
2520 * @inheritable
2521 * @property {Object[]}
2522 */
2523 OO.ui.Dialog.static.actions = [];
2524
2525 /**
2526 * Close the dialog when the 'Esc' key is pressed.
2527 *
2528 * @static
2529 * @abstract
2530 * @inheritable
2531 * @property {boolean}
2532 */
2533 OO.ui.Dialog.static.escapable = true;
2534
2535 /* Methods */
2536
2537 /**
2538 * Handle frame document key down events.
2539 *
2540 * @private
2541 * @param {jQuery.Event} e Key down event
2542 */
2543 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2544 if ( e.which === OO.ui.Keys.ESCAPE ) {
2545 this.close();
2546 e.preventDefault();
2547 e.stopPropagation();
2548 }
2549 };
2550
2551 /**
2552 * Handle action resized events.
2553 *
2554 * @private
2555 * @param {OO.ui.ActionWidget} action Action that was resized
2556 */
2557 OO.ui.Dialog.prototype.onActionResize = function () {
2558 // Override in subclass
2559 };
2560
2561 /**
2562 * Handle action click events.
2563 *
2564 * @private
2565 * @param {OO.ui.ActionWidget} action Action that was clicked
2566 */
2567 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2568 if ( !this.isPending() ) {
2569 this.executeAction( action.getAction() );
2570 }
2571 };
2572
2573 /**
2574 * Handle actions change event.
2575 *
2576 * @private
2577 */
2578 OO.ui.Dialog.prototype.onActionsChange = function () {
2579 this.detachActions();
2580 if ( !this.isClosing() ) {
2581 this.attachActions();
2582 }
2583 };
2584
2585 /**
2586 * Get the set of actions used by the dialog.
2587 *
2588 * @return {OO.ui.ActionSet}
2589 */
2590 OO.ui.Dialog.prototype.getActions = function () {
2591 return this.actions;
2592 };
2593
2594 /**
2595 * Get a process for taking action.
2596 *
2597 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2598 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2599 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2600 *
2601 * @abstract
2602 * @param {string} [action] Symbolic name of action
2603 * @return {OO.ui.Process} Action process
2604 */
2605 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2606 return new OO.ui.Process()
2607 .next( function () {
2608 if ( !action ) {
2609 // An empty action always closes the dialog without data, which should always be
2610 // safe and make no changes
2611 this.close();
2612 }
2613 }, this );
2614 };
2615
2616 /**
2617 * @inheritdoc
2618 *
2619 * @param {Object} [data] Dialog opening data
2620 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2621 * the {@link #static-title static title}
2622 * @param {Object[]} [data.actions] List of configuration options for each
2623 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2624 */
2625 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2626 data = data || {};
2627
2628 // Parent method
2629 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2630 .next( function () {
2631 var config = this.constructor.static,
2632 actions = data.actions !== undefined ? data.actions : config.actions;
2633
2634 this.title.setLabel(
2635 data.title !== undefined ? data.title : this.constructor.static.title
2636 );
2637 this.actions.add( this.getActionWidgets( actions ) );
2638
2639 if ( this.constructor.static.escapable ) {
2640 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2641 }
2642 }, this );
2643 };
2644
2645 /**
2646 * @inheritdoc
2647 */
2648 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2649 // Parent method
2650 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2651 .first( function () {
2652 if ( this.constructor.static.escapable ) {
2653 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2654 }
2655
2656 this.actions.clear();
2657 this.currentAction = null;
2658 }, this );
2659 };
2660
2661 /**
2662 * @inheritdoc
2663 */
2664 OO.ui.Dialog.prototype.initialize = function () {
2665 // Parent method
2666 OO.ui.Dialog.super.prototype.initialize.call( this );
2667
2668 // Properties
2669 this.title = new OO.ui.LabelWidget();
2670
2671 // Initialization
2672 this.$content.addClass( 'oo-ui-dialog-content' );
2673 this.setPendingElement( this.$head );
2674 };
2675
2676 /**
2677 * Get action widgets from a list of configs
2678 *
2679 * @param {Object[]} actions Action widget configs
2680 * @return {OO.ui.ActionWidget[]} Action widgets
2681 */
2682 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2683 var i, len, widgets = [];
2684 for ( i = 0, len = actions.length; i < len; i++ ) {
2685 widgets.push(
2686 new OO.ui.ActionWidget( actions[ i ] )
2687 );
2688 }
2689 return widgets;
2690 };
2691
2692 /**
2693 * Attach action actions.
2694 *
2695 * @protected
2696 */
2697 OO.ui.Dialog.prototype.attachActions = function () {
2698 // Remember the list of potentially attached actions
2699 this.attachedActions = this.actions.get();
2700 };
2701
2702 /**
2703 * Detach action actions.
2704 *
2705 * @protected
2706 * @chainable
2707 */
2708 OO.ui.Dialog.prototype.detachActions = function () {
2709 var i, len;
2710
2711 // Detach all actions that may have been previously attached
2712 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2713 this.attachedActions[ i ].$element.detach();
2714 }
2715 this.attachedActions = [];
2716 };
2717
2718 /**
2719 * Execute an action.
2720 *
2721 * @param {string} action Symbolic name of action to execute
2722 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2723 */
2724 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2725 this.pushPending();
2726 this.currentAction = action;
2727 return this.getActionProcess( action ).execute()
2728 .always( this.popPending.bind( this ) );
2729 };
2730
2731 /**
2732 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2733 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2734 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2735 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2736 * pertinent data and reused.
2737 *
2738 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2739 * `opened`, and `closing`, which represent the primary stages of the cycle:
2740 *
2741 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2742 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2743 *
2744 * - an `opening` event is emitted with an `opening` promise
2745 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2746 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2747 * window and its result executed
2748 * - a `setup` progress notification is emitted from the `opening` promise
2749 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2750 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2751 * window and its result executed
2752 * - a `ready` progress notification is emitted from the `opening` promise
2753 * - the `opening` promise is resolved with an `opened` promise
2754 *
2755 * **Opened**: the window is now open.
2756 *
2757 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2758 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2759 * to close the window.
2760 *
2761 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2762 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2763 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2764 * window and its result executed
2765 * - a `hold` progress notification is emitted from the `closing` promise
2766 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2767 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2768 * window and its result executed
2769 * - a `teardown` progress notification is emitted from the `closing` promise
2770 * - the `closing` promise is resolved. The window is now closed
2771 *
2772 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2773 *
2774 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2775 *
2776 * @class
2777 * @extends OO.ui.Element
2778 * @mixins OO.EventEmitter
2779 *
2780 * @constructor
2781 * @param {Object} [config] Configuration options
2782 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2783 * Note that window classes that are instantiated with a factory must have
2784 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2785 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2786 */
2787 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2788 // Configuration initialization
2789 config = config || {};
2790
2791 // Parent constructor
2792 OO.ui.WindowManager.super.call( this, config );
2793
2794 // Mixin constructors
2795 OO.EventEmitter.call( this );
2796
2797 // Properties
2798 this.factory = config.factory;
2799 this.modal = config.modal === undefined || !!config.modal;
2800 this.windows = {};
2801 this.opening = null;
2802 this.opened = null;
2803 this.closing = null;
2804 this.preparingToOpen = null;
2805 this.preparingToClose = null;
2806 this.currentWindow = null;
2807 this.globalEvents = false;
2808 this.$ariaHidden = null;
2809 this.onWindowResizeTimeout = null;
2810 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2811 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2812
2813 // Initialization
2814 this.$element
2815 .addClass( 'oo-ui-windowManager' )
2816 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2817 };
2818
2819 /* Setup */
2820
2821 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2822 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2823
2824 /* Events */
2825
2826 /**
2827 * An 'opening' event is emitted when the window begins to be opened.
2828 *
2829 * @event opening
2830 * @param {OO.ui.Window} win Window that's being opened
2831 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2832 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2833 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2834 * @param {Object} data Window opening data
2835 */
2836
2837 /**
2838 * A 'closing' event is emitted when the window begins to be closed.
2839 *
2840 * @event closing
2841 * @param {OO.ui.Window} win Window that's being closed
2842 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2843 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2844 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2845 * is the closing data.
2846 * @param {Object} data Window closing data
2847 */
2848
2849 /**
2850 * A 'resize' event is emitted when a window is resized.
2851 *
2852 * @event resize
2853 * @param {OO.ui.Window} win Window that was resized
2854 */
2855
2856 /* Static Properties */
2857
2858 /**
2859 * Map of the symbolic name of each window size and its CSS properties.
2860 *
2861 * @static
2862 * @inheritable
2863 * @property {Object}
2864 */
2865 OO.ui.WindowManager.static.sizes = {
2866 small: {
2867 width: 300
2868 },
2869 medium: {
2870 width: 500
2871 },
2872 large: {
2873 width: 700
2874 },
2875 larger: {
2876 width: 900
2877 },
2878 full: {
2879 // These can be non-numeric because they are never used in calculations
2880 width: '100%',
2881 height: '100%'
2882 }
2883 };
2884
2885 /**
2886 * Symbolic name of the default window size.
2887 *
2888 * The default size is used if the window's requested size is not recognized.
2889 *
2890 * @static
2891 * @inheritable
2892 * @property {string}
2893 */
2894 OO.ui.WindowManager.static.defaultSize = 'medium';
2895
2896 /* Methods */
2897
2898 /**
2899 * Handle window resize events.
2900 *
2901 * @private
2902 * @param {jQuery.Event} e Window resize event
2903 */
2904 OO.ui.WindowManager.prototype.onWindowResize = function () {
2905 clearTimeout( this.onWindowResizeTimeout );
2906 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2907 };
2908
2909 /**
2910 * Handle window resize events.
2911 *
2912 * @private
2913 * @param {jQuery.Event} e Window resize event
2914 */
2915 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2916 if ( this.currentWindow ) {
2917 this.updateWindowSize( this.currentWindow );
2918 }
2919 };
2920
2921 /**
2922 * Check if window is opening.
2923 *
2924 * @return {boolean} Window is opening
2925 */
2926 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2927 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2928 };
2929
2930 /**
2931 * Check if window is closing.
2932 *
2933 * @return {boolean} Window is closing
2934 */
2935 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2936 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2937 };
2938
2939 /**
2940 * Check if window is opened.
2941 *
2942 * @return {boolean} Window is opened
2943 */
2944 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2945 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2946 };
2947
2948 /**
2949 * Check if a window is being managed.
2950 *
2951 * @param {OO.ui.Window} win Window to check
2952 * @return {boolean} Window is being managed
2953 */
2954 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2955 var name;
2956
2957 for ( name in this.windows ) {
2958 if ( this.windows[ name ] === win ) {
2959 return true;
2960 }
2961 }
2962
2963 return false;
2964 };
2965
2966 /**
2967 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2968 *
2969 * @param {OO.ui.Window} win Window being opened
2970 * @param {Object} [data] Window opening data
2971 * @return {number} Milliseconds to wait
2972 */
2973 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2974 return 0;
2975 };
2976
2977 /**
2978 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2979 *
2980 * @param {OO.ui.Window} win Window being opened
2981 * @param {Object} [data] Window opening data
2982 * @return {number} Milliseconds to wait
2983 */
2984 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2985 return 0;
2986 };
2987
2988 /**
2989 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2990 *
2991 * @param {OO.ui.Window} win Window being closed
2992 * @param {Object} [data] Window closing data
2993 * @return {number} Milliseconds to wait
2994 */
2995 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2996 return 0;
2997 };
2998
2999 /**
3000 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3001 * executing the ‘teardown’ process.
3002 *
3003 * @param {OO.ui.Window} win Window being closed
3004 * @param {Object} [data] Window closing data
3005 * @return {number} Milliseconds to wait
3006 */
3007 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
3008 return this.modal ? 250 : 0;
3009 };
3010
3011 /**
3012 * Get a window by its symbolic name.
3013 *
3014 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3015 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3016 * for more information about using factories.
3017 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3018 *
3019 * @param {string} name Symbolic name of the window
3020 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3021 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3022 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3023 */
3024 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
3025 var deferred = $.Deferred(),
3026 win = this.windows[ name ];
3027
3028 if ( !( win instanceof OO.ui.Window ) ) {
3029 if ( this.factory ) {
3030 if ( !this.factory.lookup( name ) ) {
3031 deferred.reject( new OO.ui.Error(
3032 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3033 ) );
3034 } else {
3035 win = this.factory.create( name );
3036 this.addWindows( [ win ] );
3037 deferred.resolve( win );
3038 }
3039 } else {
3040 deferred.reject( new OO.ui.Error(
3041 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3042 ) );
3043 }
3044 } else {
3045 deferred.resolve( win );
3046 }
3047
3048 return deferred.promise();
3049 };
3050
3051 /**
3052 * Get current window.
3053 *
3054 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3055 */
3056 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3057 return this.currentWindow;
3058 };
3059
3060 /**
3061 * Open a window.
3062 *
3063 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3064 * @param {Object} [data] Window opening data
3065 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3066 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3067 * @fires opening
3068 */
3069 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3070 var manager = this,
3071 opening = $.Deferred();
3072
3073 // Argument handling
3074 if ( typeof win === 'string' ) {
3075 return this.getWindow( win ).then( function ( win ) {
3076 return manager.openWindow( win, data );
3077 } );
3078 }
3079
3080 // Error handling
3081 if ( !this.hasWindow( win ) ) {
3082 opening.reject( new OO.ui.Error(
3083 'Cannot open window: window is not attached to manager'
3084 ) );
3085 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3086 opening.reject( new OO.ui.Error(
3087 'Cannot open window: another window is opening or open'
3088 ) );
3089 }
3090
3091 // Window opening
3092 if ( opening.state() !== 'rejected' ) {
3093 // If a window is currently closing, wait for it to complete
3094 this.preparingToOpen = $.when( this.closing );
3095 // Ensure handlers get called after preparingToOpen is set
3096 this.preparingToOpen.done( function () {
3097 if ( manager.modal ) {
3098 manager.toggleGlobalEvents( true );
3099 manager.toggleAriaIsolation( true );
3100 }
3101 manager.currentWindow = win;
3102 manager.opening = opening;
3103 manager.preparingToOpen = null;
3104 manager.emit( 'opening', win, opening, data );
3105 setTimeout( function () {
3106 win.setup( data ).then( function () {
3107 manager.updateWindowSize( win );
3108 manager.opening.notify( { state: 'setup' } );
3109 setTimeout( function () {
3110 win.ready( data ).then( function () {
3111 manager.opening.notify( { state: 'ready' } );
3112 manager.opening = null;
3113 manager.opened = $.Deferred();
3114 opening.resolve( manager.opened.promise(), data );
3115 } );
3116 }, manager.getReadyDelay() );
3117 } );
3118 }, manager.getSetupDelay() );
3119 } );
3120 }
3121
3122 return opening.promise();
3123 };
3124
3125 /**
3126 * Close a window.
3127 *
3128 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3129 * @param {Object} [data] Window closing data
3130 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3131 * See {@link #event-closing 'closing' event} for more information about closing promises.
3132 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3133 * @fires closing
3134 */
3135 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3136 var manager = this,
3137 closing = $.Deferred(),
3138 opened;
3139
3140 // Argument handling
3141 if ( typeof win === 'string' ) {
3142 win = this.windows[ win ];
3143 } else if ( !this.hasWindow( win ) ) {
3144 win = null;
3145 }
3146
3147 // Error handling
3148 if ( !win ) {
3149 closing.reject( new OO.ui.Error(
3150 'Cannot close window: window is not attached to manager'
3151 ) );
3152 } else if ( win !== this.currentWindow ) {
3153 closing.reject( new OO.ui.Error(
3154 'Cannot close window: window already closed with different data'
3155 ) );
3156 } else if ( this.preparingToClose || this.closing ) {
3157 closing.reject( new OO.ui.Error(
3158 'Cannot close window: window already closing with different data'
3159 ) );
3160 }
3161
3162 // Window closing
3163 if ( closing.state() !== 'rejected' ) {
3164 // If the window is currently opening, close it when it's done
3165 this.preparingToClose = $.when( this.opening );
3166 // Ensure handlers get called after preparingToClose is set
3167 this.preparingToClose.done( function () {
3168 manager.closing = closing;
3169 manager.preparingToClose = null;
3170 manager.emit( 'closing', win, closing, data );
3171 opened = manager.opened;
3172 manager.opened = null;
3173 opened.resolve( closing.promise(), data );
3174 setTimeout( function () {
3175 win.hold( data ).then( function () {
3176 closing.notify( { state: 'hold' } );
3177 setTimeout( function () {
3178 win.teardown( data ).then( function () {
3179 closing.notify( { state: 'teardown' } );
3180 if ( manager.modal ) {
3181 manager.toggleGlobalEvents( false );
3182 manager.toggleAriaIsolation( false );
3183 }
3184 manager.closing = null;
3185 manager.currentWindow = null;
3186 closing.resolve( data );
3187 } );
3188 }, manager.getTeardownDelay() );
3189 } );
3190 }, manager.getHoldDelay() );
3191 } );
3192 }
3193
3194 return closing.promise();
3195 };
3196
3197 /**
3198 * Add windows to the window manager.
3199 *
3200 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3201 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3202 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3203 *
3204 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3205 * by reference, symbolic name, or explicitly defined symbolic names.
3206 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3207 * explicit nor a statically configured symbolic name.
3208 */
3209 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3210 var i, len, win, name, list;
3211
3212 if ( Array.isArray( windows ) ) {
3213 // Convert to map of windows by looking up symbolic names from static configuration
3214 list = {};
3215 for ( i = 0, len = windows.length; i < len; i++ ) {
3216 name = windows[ i ].constructor.static.name;
3217 if ( typeof name !== 'string' ) {
3218 throw new Error( 'Cannot add window' );
3219 }
3220 list[ name ] = windows[ i ];
3221 }
3222 } else if ( OO.isPlainObject( windows ) ) {
3223 list = windows;
3224 }
3225
3226 // Add windows
3227 for ( name in list ) {
3228 win = list[ name ];
3229 this.windows[ name ] = win.toggle( false );
3230 this.$element.append( win.$element );
3231 win.setManager( this );
3232 }
3233 };
3234
3235 /**
3236 * Remove the specified windows from the windows manager.
3237 *
3238 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3239 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3240 * longer listens to events, use the #destroy method.
3241 *
3242 * @param {string[]} names Symbolic names of windows to remove
3243 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3244 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3245 */
3246 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3247 var i, len, win, name, cleanupWindow,
3248 manager = this,
3249 promises = [],
3250 cleanup = function ( name, win ) {
3251 delete manager.windows[ name ];
3252 win.$element.detach();
3253 };
3254
3255 for ( i = 0, len = names.length; i < len; i++ ) {
3256 name = names[ i ];
3257 win = this.windows[ name ];
3258 if ( !win ) {
3259 throw new Error( 'Cannot remove window' );
3260 }
3261 cleanupWindow = cleanup.bind( null, name, win );
3262 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3263 }
3264
3265 return $.when.apply( $, promises );
3266 };
3267
3268 /**
3269 * Remove all windows from the window manager.
3270 *
3271 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3272 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3273 * To remove just a subset of windows, use the #removeWindows method.
3274 *
3275 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3276 */
3277 OO.ui.WindowManager.prototype.clearWindows = function () {
3278 return this.removeWindows( Object.keys( this.windows ) );
3279 };
3280
3281 /**
3282 * Set dialog size. In general, this method should not be called directly.
3283 *
3284 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3285 *
3286 * @chainable
3287 */
3288 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3289 // Bypass for non-current, and thus invisible, windows
3290 if ( win !== this.currentWindow ) {
3291 return;
3292 }
3293
3294 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3295 sizes = this.constructor.static.sizes,
3296 size = win.getSize();
3297
3298 if ( !sizes[ size ] ) {
3299 size = this.constructor.static.defaultSize;
3300 }
3301 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3302 size = 'full';
3303 }
3304
3305 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3306 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3307 win.setDimensions( sizes[ size ] );
3308
3309 this.emit( 'resize', win );
3310
3311 return this;
3312 };
3313
3314 /**
3315 * Bind or unbind global events for scrolling.
3316 *
3317 * @private
3318 * @param {boolean} [on] Bind global events
3319 * @chainable
3320 */
3321 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3322 on = on === undefined ? !!this.globalEvents : !!on;
3323
3324 var scrollWidth, bodyMargin,
3325 $body = $( this.getElementDocument().body ),
3326 // We could have multiple window managers open so only modify
3327 // the body css at the bottom of the stack
3328 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3329
3330 if ( on ) {
3331 if ( !this.globalEvents ) {
3332 $( this.getElementWindow() ).on( {
3333 // Start listening for top-level window dimension changes
3334 'orientationchange resize': this.onWindowResizeHandler
3335 } );
3336 if ( stackDepth === 0 ) {
3337 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3338 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3339 $body.css( {
3340 overflow: 'hidden',
3341 'margin-right': bodyMargin + scrollWidth
3342 } );
3343 }
3344 stackDepth++;
3345 this.globalEvents = true;
3346 }
3347 } else if ( this.globalEvents ) {
3348 $( this.getElementWindow() ).off( {
3349 // Stop listening for top-level window dimension changes
3350 'orientationchange resize': this.onWindowResizeHandler
3351 } );
3352 stackDepth--;
3353 if ( stackDepth === 0 ) {
3354 $body.css( {
3355 overflow: '',
3356 'margin-right': ''
3357 } );
3358 }
3359 this.globalEvents = false;
3360 }
3361 $body.data( 'windowManagerGlobalEvents', stackDepth );
3362
3363 return this;
3364 };
3365
3366 /**
3367 * Toggle screen reader visibility of content other than the window manager.
3368 *
3369 * @private
3370 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3371 * @chainable
3372 */
3373 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3374 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3375
3376 if ( isolate ) {
3377 if ( !this.$ariaHidden ) {
3378 // Hide everything other than the window manager from screen readers
3379 this.$ariaHidden = $( 'body' )
3380 .children()
3381 .not( this.$element.parentsUntil( 'body' ).last() )
3382 .attr( 'aria-hidden', '' );
3383 }
3384 } else if ( this.$ariaHidden ) {
3385 // Restore screen reader visibility
3386 this.$ariaHidden.removeAttr( 'aria-hidden' );
3387 this.$ariaHidden = null;
3388 }
3389
3390 return this;
3391 };
3392
3393 /**
3394 * Destroy the window manager.
3395 *
3396 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3397 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3398 * instead.
3399 */
3400 OO.ui.WindowManager.prototype.destroy = function () {
3401 this.toggleGlobalEvents( false );
3402 this.toggleAriaIsolation( false );
3403 this.clearWindows();
3404 this.$element.remove();
3405 };
3406
3407 /**
3408 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3409 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3410 * appearance and functionality of the error interface.
3411 *
3412 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3413 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3414 * that initiated the failed process will be disabled.
3415 *
3416 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3417 * process again.
3418 *
3419 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3420 *
3421 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3422 *
3423 * @class
3424 *
3425 * @constructor
3426 * @param {string|jQuery} message Description of error
3427 * @param {Object} [config] Configuration options
3428 * @cfg {boolean} [recoverable=true] Error is recoverable.
3429 * By default, errors are recoverable, and users can try the process again.
3430 * @cfg {boolean} [warning=false] Error is a warning.
3431 * If the error is a warning, the error interface will include a
3432 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3433 * is not triggered a second time if the user chooses to continue.
3434 */
3435 OO.ui.Error = function OoUiError( message, config ) {
3436 // Allow passing positional parameters inside the config object
3437 if ( OO.isPlainObject( message ) && config === undefined ) {
3438 config = message;
3439 message = config.message;
3440 }
3441
3442 // Configuration initialization
3443 config = config || {};
3444
3445 // Properties
3446 this.message = message instanceof jQuery ? message : String( message );
3447 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3448 this.warning = !!config.warning;
3449 };
3450
3451 /* Setup */
3452
3453 OO.initClass( OO.ui.Error );
3454
3455 /* Methods */
3456
3457 /**
3458 * Check if the error is recoverable.
3459 *
3460 * If the error is recoverable, users are able to try the process again.
3461 *
3462 * @return {boolean} Error is recoverable
3463 */
3464 OO.ui.Error.prototype.isRecoverable = function () {
3465 return this.recoverable;
3466 };
3467
3468 /**
3469 * Check if the error is a warning.
3470 *
3471 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3472 *
3473 * @return {boolean} Error is warning
3474 */
3475 OO.ui.Error.prototype.isWarning = function () {
3476 return this.warning;
3477 };
3478
3479 /**
3480 * Get error message as DOM nodes.
3481 *
3482 * @return {jQuery} Error message in DOM nodes
3483 */
3484 OO.ui.Error.prototype.getMessage = function () {
3485 return this.message instanceof jQuery ?
3486 this.message.clone() :
3487 $( '<div>' ).text( this.message ).contents();
3488 };
3489
3490 /**
3491 * Get the error message text.
3492 *
3493 * @return {string} Error message
3494 */
3495 OO.ui.Error.prototype.getMessageText = function () {
3496 return this.message instanceof jQuery ? this.message.text() : this.message;
3497 };
3498
3499 /**
3500 * Wraps an HTML snippet for use with configuration values which default
3501 * to strings. This bypasses the default html-escaping done to string
3502 * values.
3503 *
3504 * @class
3505 *
3506 * @constructor
3507 * @param {string} [content] HTML content
3508 */
3509 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3510 // Properties
3511 this.content = content;
3512 };
3513
3514 /* Setup */
3515
3516 OO.initClass( OO.ui.HtmlSnippet );
3517
3518 /* Methods */
3519
3520 /**
3521 * Render into HTML.
3522 *
3523 * @return {string} Unchanged HTML snippet.
3524 */
3525 OO.ui.HtmlSnippet.prototype.toString = function () {
3526 return this.content;
3527 };
3528
3529 /**
3530 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3531 * or a function:
3532 *
3533 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3534 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3535 * or stop if the promise is rejected.
3536 * - **function**: the process will execute the function. The process will stop if the function returns
3537 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3538 * will wait for that number of milliseconds before proceeding.
3539 *
3540 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3541 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3542 * its remaining steps will not be performed.
3543 *
3544 * @class
3545 *
3546 * @constructor
3547 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3548 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3549 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3550 * a number or promise.
3551 * @return {Object} Step object, with `callback` and `context` properties
3552 */
3553 OO.ui.Process = function ( step, context ) {
3554 // Properties
3555 this.steps = [];
3556
3557 // Initialization
3558 if ( step !== undefined ) {
3559 this.next( step, context );
3560 }
3561 };
3562
3563 /* Setup */
3564
3565 OO.initClass( OO.ui.Process );
3566
3567 /* Methods */
3568
3569 /**
3570 * Start the process.
3571 *
3572 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3573 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3574 * and any remaining steps are not performed.
3575 */
3576 OO.ui.Process.prototype.execute = function () {
3577 var i, len, promise;
3578
3579 /**
3580 * Continue execution.
3581 *
3582 * @ignore
3583 * @param {Array} step A function and the context it should be called in
3584 * @return {Function} Function that continues the process
3585 */
3586 function proceed( step ) {
3587 return function () {
3588 // Execute step in the correct context
3589 var deferred,
3590 result = step.callback.call( step.context );
3591
3592 if ( result === false ) {
3593 // Use rejected promise for boolean false results
3594 return $.Deferred().reject( [] ).promise();
3595 }
3596 if ( typeof result === 'number' ) {
3597 if ( result < 0 ) {
3598 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3599 }
3600 // Use a delayed promise for numbers, expecting them to be in milliseconds
3601 deferred = $.Deferred();
3602 setTimeout( deferred.resolve, result );
3603 return deferred.promise();
3604 }
3605 if ( result instanceof OO.ui.Error ) {
3606 // Use rejected promise for error
3607 return $.Deferred().reject( [ result ] ).promise();
3608 }
3609 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3610 // Use rejected promise for list of errors
3611 return $.Deferred().reject( result ).promise();
3612 }
3613 // Duck-type the object to see if it can produce a promise
3614 if ( result && $.isFunction( result.promise ) ) {
3615 // Use a promise generated from the result
3616 return result.promise();
3617 }
3618 // Use resolved promise for other results
3619 return $.Deferred().resolve().promise();
3620 };
3621 }
3622
3623 if ( this.steps.length ) {
3624 // Generate a chain reaction of promises
3625 promise = proceed( this.steps[ 0 ] )();
3626 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3627 promise = promise.then( proceed( this.steps[ i ] ) );
3628 }
3629 } else {
3630 promise = $.Deferred().resolve().promise();
3631 }
3632
3633 return promise;
3634 };
3635
3636 /**
3637 * Create a process step.
3638 *
3639 * @private
3640 * @param {number|jQuery.Promise|Function} step
3641 *
3642 * - Number of milliseconds to wait before proceeding
3643 * - Promise that must be resolved before proceeding
3644 * - Function to execute
3645 * - If the function returns a boolean false the process will stop
3646 * - If the function returns a promise, the process will continue to the next
3647 * step when the promise is resolved or stop if the promise is rejected
3648 * - If the function returns a number, the process will wait for that number of
3649 * milliseconds before proceeding
3650 * @param {Object} [context=null] Execution context of the function. The context is
3651 * ignored if the step is a number or promise.
3652 * @return {Object} Step object, with `callback` and `context` properties
3653 */
3654 OO.ui.Process.prototype.createStep = function ( step, context ) {
3655 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3656 return {
3657 callback: function () {
3658 return step;
3659 },
3660 context: null
3661 };
3662 }
3663 if ( $.isFunction( step ) ) {
3664 return {
3665 callback: step,
3666 context: context
3667 };
3668 }
3669 throw new Error( 'Cannot create process step: number, promise or function expected' );
3670 };
3671
3672 /**
3673 * Add step to the beginning of the process.
3674 *
3675 * @inheritdoc #createStep
3676 * @return {OO.ui.Process} this
3677 * @chainable
3678 */
3679 OO.ui.Process.prototype.first = function ( step, context ) {
3680 this.steps.unshift( this.createStep( step, context ) );
3681 return this;
3682 };
3683
3684 /**
3685 * Add step to the end of the process.
3686 *
3687 * @inheritdoc #createStep
3688 * @return {OO.ui.Process} this
3689 * @chainable
3690 */
3691 OO.ui.Process.prototype.next = function ( step, context ) {
3692 this.steps.push( this.createStep( step, context ) );
3693 return this;
3694 };
3695
3696 /**
3697 * Factory for tools.
3698 *
3699 * @class
3700 * @extends OO.Factory
3701 * @constructor
3702 */
3703 OO.ui.ToolFactory = function OoUiToolFactory() {
3704 // Parent constructor
3705 OO.ui.ToolFactory.super.call( this );
3706 };
3707
3708 /* Setup */
3709
3710 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3711
3712 /* Methods */
3713
3714 /**
3715 * Get tools from the factory
3716 *
3717 * @param {Array} include Included tools
3718 * @param {Array} exclude Excluded tools
3719 * @param {Array} promote Promoted tools
3720 * @param {Array} demote Demoted tools
3721 * @return {string[]} List of tools
3722 */
3723 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3724 var i, len, included, promoted, demoted,
3725 auto = [],
3726 used = {};
3727
3728 // Collect included and not excluded tools
3729 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3730
3731 // Promotion
3732 promoted = this.extract( promote, used );
3733 demoted = this.extract( demote, used );
3734
3735 // Auto
3736 for ( i = 0, len = included.length; i < len; i++ ) {
3737 if ( !used[ included[ i ] ] ) {
3738 auto.push( included[ i ] );
3739 }
3740 }
3741
3742 return promoted.concat( auto ).concat( demoted );
3743 };
3744
3745 /**
3746 * Get a flat list of names from a list of names or groups.
3747 *
3748 * Tools can be specified in the following ways:
3749 *
3750 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3751 * - All tools in a group: `{ group: 'group-name' }`
3752 * - All tools: `'*'`
3753 *
3754 * @private
3755 * @param {Array|string} collection List of tools
3756 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3757 * names will be added as properties
3758 * @return {string[]} List of extracted names
3759 */
3760 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3761 var i, len, item, name, tool,
3762 names = [];
3763
3764 if ( collection === '*' ) {
3765 for ( name in this.registry ) {
3766 tool = this.registry[ name ];
3767 if (
3768 // Only add tools by group name when auto-add is enabled
3769 tool.static.autoAddToCatchall &&
3770 // Exclude already used tools
3771 ( !used || !used[ name ] )
3772 ) {
3773 names.push( name );
3774 if ( used ) {
3775 used[ name ] = true;
3776 }
3777 }
3778 }
3779 } else if ( Array.isArray( collection ) ) {
3780 for ( i = 0, len = collection.length; i < len; i++ ) {
3781 item = collection[ i ];
3782 // Allow plain strings as shorthand for named tools
3783 if ( typeof item === 'string' ) {
3784 item = { name: item };
3785 }
3786 if ( OO.isPlainObject( item ) ) {
3787 if ( item.group ) {
3788 for ( name in this.registry ) {
3789 tool = this.registry[ name ];
3790 if (
3791 // Include tools with matching group
3792 tool.static.group === item.group &&
3793 // Only add tools by group name when auto-add is enabled
3794 tool.static.autoAddToGroup &&
3795 // Exclude already used tools
3796 ( !used || !used[ name ] )
3797 ) {
3798 names.push( name );
3799 if ( used ) {
3800 used[ name ] = true;
3801 }
3802 }
3803 }
3804 // Include tools with matching name and exclude already used tools
3805 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3806 names.push( item.name );
3807 if ( used ) {
3808 used[ item.name ] = true;
3809 }
3810 }
3811 }
3812 }
3813 }
3814 return names;
3815 };
3816
3817 /**
3818 * Factory for tool groups.
3819 *
3820 * @class
3821 * @extends OO.Factory
3822 * @constructor
3823 */
3824 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3825 // Parent constructor
3826 OO.Factory.call( this );
3827
3828 var i, l,
3829 defaultClasses = this.constructor.static.getDefaultClasses();
3830
3831 // Register default toolgroups
3832 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3833 this.register( defaultClasses[ i ] );
3834 }
3835 };
3836
3837 /* Setup */
3838
3839 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3840
3841 /* Static Methods */
3842
3843 /**
3844 * Get a default set of classes to be registered on construction
3845 *
3846 * @return {Function[]} Default classes
3847 */
3848 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3849 return [
3850 OO.ui.BarToolGroup,
3851 OO.ui.ListToolGroup,
3852 OO.ui.MenuToolGroup
3853 ];
3854 };
3855
3856 /**
3857 * Theme logic.
3858 *
3859 * @abstract
3860 * @class
3861 *
3862 * @constructor
3863 * @param {Object} [config] Configuration options
3864 */
3865 OO.ui.Theme = function OoUiTheme( config ) {
3866 // Configuration initialization
3867 config = config || {};
3868 };
3869
3870 /* Setup */
3871
3872 OO.initClass( OO.ui.Theme );
3873
3874 /* Methods */
3875
3876 /**
3877 * Get a list of classes to be applied to a widget.
3878 *
3879 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3880 * otherwise state transitions will not work properly.
3881 *
3882 * @param {OO.ui.Element} element Element for which to get classes
3883 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3884 */
3885 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3886 return { on: [], off: [] };
3887 };
3888
3889 /**
3890 * Update CSS classes provided by the theme.
3891 *
3892 * For elements with theme logic hooks, this should be called any time there's a state change.
3893 *
3894 * @param {OO.ui.Element} element Element for which to update classes
3895 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3896 */
3897 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3898 var classes = this.getElementClasses( element );
3899
3900 element.$element
3901 .removeClass( classes.off.join( ' ' ) )
3902 .addClass( classes.on.join( ' ' ) );
3903 };
3904
3905 /**
3906 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3907 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3908 * order in which users will navigate through the focusable elements via the "tab" key.
3909 *
3910 * @example
3911 * // TabIndexedElement is mixed into the ButtonWidget class
3912 * // to provide a tabIndex property.
3913 * var button1 = new OO.ui.ButtonWidget( {
3914 * label: 'fourth',
3915 * tabIndex: 4
3916 * } );
3917 * var button2 = new OO.ui.ButtonWidget( {
3918 * label: 'second',
3919 * tabIndex: 2
3920 * } );
3921 * var button3 = new OO.ui.ButtonWidget( {
3922 * label: 'third',
3923 * tabIndex: 3
3924 * } );
3925 * var button4 = new OO.ui.ButtonWidget( {
3926 * label: 'first',
3927 * tabIndex: 1
3928 * } );
3929 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3930 *
3931 * @abstract
3932 * @class
3933 *
3934 * @constructor
3935 * @param {Object} [config] Configuration options
3936 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3937 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3938 * functionality will be applied to it instead.
3939 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3940 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3941 * to remove the element from the tab-navigation flow.
3942 */
3943 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3944 // Configuration initialization
3945 config = $.extend( { tabIndex: 0 }, config );
3946
3947 // Properties
3948 this.$tabIndexed = null;
3949 this.tabIndex = null;
3950
3951 // Events
3952 this.connect( this, { disable: 'onDisable' } );
3953
3954 // Initialization
3955 this.setTabIndex( config.tabIndex );
3956 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3957 };
3958
3959 /* Setup */
3960
3961 OO.initClass( OO.ui.TabIndexedElement );
3962
3963 /* Methods */
3964
3965 /**
3966 * Set the element that should use the tabindex functionality.
3967 *
3968 * This method is used to retarget a tabindex mixin so that its functionality applies
3969 * to the specified element. If an element is currently using the functionality, the mixin’s
3970 * effect on that element is removed before the new element is set up.
3971 *
3972 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3973 * @chainable
3974 */
3975 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3976 var tabIndex = this.tabIndex;
3977 // Remove attributes from old $tabIndexed
3978 this.setTabIndex( null );
3979 // Force update of new $tabIndexed
3980 this.$tabIndexed = $tabIndexed;
3981 this.tabIndex = tabIndex;
3982 return this.updateTabIndex();
3983 };
3984
3985 /**
3986 * Set the value of the tabindex.
3987 *
3988 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3989 * @chainable
3990 */
3991 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3992 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3993
3994 if ( this.tabIndex !== tabIndex ) {
3995 this.tabIndex = tabIndex;
3996 this.updateTabIndex();
3997 }
3998
3999 return this;
4000 };
4001
4002 /**
4003 * Update the `tabindex` attribute, in case of changes to tab index or
4004 * disabled state.
4005 *
4006 * @private
4007 * @chainable
4008 */
4009 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
4010 if ( this.$tabIndexed ) {
4011 if ( this.tabIndex !== null ) {
4012 // Do not index over disabled elements
4013 this.$tabIndexed.attr( {
4014 tabindex: this.isDisabled() ? -1 : this.tabIndex,
4015 // ChromeVox and NVDA do not seem to inherit this from parent elements
4016 'aria-disabled': this.isDisabled().toString()
4017 } );
4018 } else {
4019 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
4020 }
4021 }
4022 return this;
4023 };
4024
4025 /**
4026 * Handle disable events.
4027 *
4028 * @private
4029 * @param {boolean} disabled Element is disabled
4030 */
4031 OO.ui.TabIndexedElement.prototype.onDisable = function () {
4032 this.updateTabIndex();
4033 };
4034
4035 /**
4036 * Get the value of the tabindex.
4037 *
4038 * @return {number|null} Tabindex value
4039 */
4040 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
4041 return this.tabIndex;
4042 };
4043
4044 /**
4045 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4046 * interface element that can be configured with access keys for accessibility.
4047 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4048 *
4049 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4050 * @abstract
4051 * @class
4052 *
4053 * @constructor
4054 * @param {Object} [config] Configuration options
4055 * @cfg {jQuery} [$button] The button element created by the class.
4056 * If this configuration is omitted, the button element will use a generated `<a>`.
4057 * @cfg {boolean} [framed=true] Render the button with a frame
4058 * @cfg {string} [accessKey] Button's access key
4059 */
4060 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
4061 // Configuration initialization
4062 config = config || {};
4063
4064 // Properties
4065 this.$button = null;
4066 this.framed = null;
4067 this.accessKey = null;
4068 this.active = false;
4069 this.onMouseUpHandler = this.onMouseUp.bind( this );
4070 this.onMouseDownHandler = this.onMouseDown.bind( this );
4071 this.onKeyDownHandler = this.onKeyDown.bind( this );
4072 this.onKeyUpHandler = this.onKeyUp.bind( this );
4073 this.onClickHandler = this.onClick.bind( this );
4074 this.onKeyPressHandler = this.onKeyPress.bind( this );
4075
4076 // Initialization
4077 this.$element.addClass( 'oo-ui-buttonElement' );
4078 this.toggleFramed( config.framed === undefined || config.framed );
4079 this.setAccessKey( config.accessKey );
4080 this.setButtonElement( config.$button || $( '<a>' ) );
4081 };
4082
4083 /* Setup */
4084
4085 OO.initClass( OO.ui.ButtonElement );
4086
4087 /* Static Properties */
4088
4089 /**
4090 * Cancel mouse down events.
4091 *
4092 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4093 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4094 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4095 * parent widget.
4096 *
4097 * @static
4098 * @inheritable
4099 * @property {boolean}
4100 */
4101 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
4102
4103 /* Events */
4104
4105 /**
4106 * A 'click' event is emitted when the button element is clicked.
4107 *
4108 * @event click
4109 */
4110
4111 /* Methods */
4112
4113 /**
4114 * Set the button element.
4115 *
4116 * This method is used to retarget a button mixin so that its functionality applies to
4117 * the specified button element instead of the one created by the class. If a button element
4118 * is already set, the method will remove the mixin’s effect on that element.
4119 *
4120 * @param {jQuery} $button Element to use as button
4121 */
4122 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
4123 if ( this.$button ) {
4124 this.$button
4125 .removeClass( 'oo-ui-buttonElement-button' )
4126 .removeAttr( 'role accesskey' )
4127 .off( {
4128 mousedown: this.onMouseDownHandler,
4129 keydown: this.onKeyDownHandler,
4130 click: this.onClickHandler,
4131 keypress: this.onKeyPressHandler
4132 } );
4133 }
4134
4135 this.$button = $button
4136 .addClass( 'oo-ui-buttonElement-button' )
4137 .attr( { role: 'button', accesskey: this.accessKey } )
4138 .on( {
4139 mousedown: this.onMouseDownHandler,
4140 keydown: this.onKeyDownHandler,
4141 click: this.onClickHandler,
4142 keypress: this.onKeyPressHandler
4143 } );
4144 };
4145
4146 /**
4147 * Handles mouse down events.
4148 *
4149 * @protected
4150 * @param {jQuery.Event} e Mouse down event
4151 */
4152 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
4153 if ( this.isDisabled() || e.which !== 1 ) {
4154 return;
4155 }
4156 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4157 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4158 // reliably remove the pressed class
4159 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4160 // Prevent change of focus unless specifically configured otherwise
4161 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4162 return false;
4163 }
4164 };
4165
4166 /**
4167 * Handles mouse up events.
4168 *
4169 * @protected
4170 * @param {jQuery.Event} e Mouse up event
4171 */
4172 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
4173 if ( this.isDisabled() || e.which !== 1 ) {
4174 return;
4175 }
4176 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4177 // Stop listening for mouseup, since we only needed this once
4178 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4179 };
4180
4181 /**
4182 * Handles mouse click events.
4183 *
4184 * @protected
4185 * @param {jQuery.Event} e Mouse click event
4186 * @fires click
4187 */
4188 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
4189 if ( !this.isDisabled() && e.which === 1 ) {
4190 this.emit( 'click' );
4191 }
4192 return false;
4193 };
4194
4195 /**
4196 * Handles key down events.
4197 *
4198 * @protected
4199 * @param {jQuery.Event} e Key down event
4200 */
4201 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4202 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4203 return;
4204 }
4205 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4206 // Run the keyup handler no matter where the key is when the button is let go, so we can
4207 // reliably remove the pressed class
4208 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4209 };
4210
4211 /**
4212 * Handles key up events.
4213 *
4214 * @protected
4215 * @param {jQuery.Event} e Key up event
4216 */
4217 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4218 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4219 return;
4220 }
4221 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4222 // Stop listening for keyup, since we only needed this once
4223 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4224 };
4225
4226 /**
4227 * Handles key press events.
4228 *
4229 * @protected
4230 * @param {jQuery.Event} e Key press event
4231 * @fires click
4232 */
4233 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4234 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4235 this.emit( 'click' );
4236 return false;
4237 }
4238 };
4239
4240 /**
4241 * Check if button has a frame.
4242 *
4243 * @return {boolean} Button is framed
4244 */
4245 OO.ui.ButtonElement.prototype.isFramed = function () {
4246 return this.framed;
4247 };
4248
4249 /**
4250 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4251 *
4252 * @param {boolean} [framed] Make button framed, omit to toggle
4253 * @chainable
4254 */
4255 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4256 framed = framed === undefined ? !this.framed : !!framed;
4257 if ( framed !== this.framed ) {
4258 this.framed = framed;
4259 this.$element
4260 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4261 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4262 this.updateThemeClasses();
4263 }
4264
4265 return this;
4266 };
4267
4268 /**
4269 * Set the button's access key.
4270 *
4271 * @param {string} accessKey Button's access key, use empty string to remove
4272 * @chainable
4273 */
4274 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4275 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4276
4277 if ( this.accessKey !== accessKey ) {
4278 if ( this.$button ) {
4279 if ( accessKey !== null ) {
4280 this.$button.attr( 'accesskey', accessKey );
4281 } else {
4282 this.$button.removeAttr( 'accesskey' );
4283 }
4284 }
4285 this.accessKey = accessKey;
4286 }
4287
4288 return this;
4289 };
4290
4291 /**
4292 * Set the button to its 'active' state.
4293 *
4294 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4295 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4296 * for other button types.
4297 *
4298 * @param {boolean} [value] Make button active
4299 * @chainable
4300 */
4301 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4302 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4303 return this;
4304 };
4305
4306 /**
4307 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4308 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4309 * items from the group is done through the interface the class provides.
4310 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4311 *
4312 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4313 *
4314 * @abstract
4315 * @class
4316 *
4317 * @constructor
4318 * @param {Object} [config] Configuration options
4319 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4320 * is omitted, the group element will use a generated `<div>`.
4321 */
4322 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4323 // Configuration initialization
4324 config = config || {};
4325
4326 // Properties
4327 this.$group = null;
4328 this.items = [];
4329 this.aggregateItemEvents = {};
4330
4331 // Initialization
4332 this.setGroupElement( config.$group || $( '<div>' ) );
4333 };
4334
4335 /* Methods */
4336
4337 /**
4338 * Set the group element.
4339 *
4340 * If an element is already set, items will be moved to the new element.
4341 *
4342 * @param {jQuery} $group Element to use as group
4343 */
4344 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4345 var i, len;
4346
4347 this.$group = $group;
4348 for ( i = 0, len = this.items.length; i < len; i++ ) {
4349 this.$group.append( this.items[ i ].$element );
4350 }
4351 };
4352
4353 /**
4354 * Check if a group contains no items.
4355 *
4356 * @return {boolean} Group is empty
4357 */
4358 OO.ui.GroupElement.prototype.isEmpty = function () {
4359 return !this.items.length;
4360 };
4361
4362 /**
4363 * Get all items in the group.
4364 *
4365 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4366 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4367 * from a group).
4368 *
4369 * @return {OO.ui.Element[]} An array of items.
4370 */
4371 OO.ui.GroupElement.prototype.getItems = function () {
4372 return this.items.slice( 0 );
4373 };
4374
4375 /**
4376 * Get an item by its data.
4377 *
4378 * Only the first item with matching data will be returned. To return all matching items,
4379 * use the #getItemsFromData method.
4380 *
4381 * @param {Object} data Item data to search for
4382 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4383 */
4384 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4385 var i, len, item,
4386 hash = OO.getHash( data );
4387
4388 for ( i = 0, len = this.items.length; i < len; i++ ) {
4389 item = this.items[ i ];
4390 if ( hash === OO.getHash( item.getData() ) ) {
4391 return item;
4392 }
4393 }
4394
4395 return null;
4396 };
4397
4398 /**
4399 * Get items by their data.
4400 *
4401 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4402 *
4403 * @param {Object} data Item data to search for
4404 * @return {OO.ui.Element[]} Items with equivalent data
4405 */
4406 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4407 var i, len, item,
4408 hash = OO.getHash( data ),
4409 items = [];
4410
4411 for ( i = 0, len = this.items.length; i < len; i++ ) {
4412 item = this.items[ i ];
4413 if ( hash === OO.getHash( item.getData() ) ) {
4414 items.push( item );
4415 }
4416 }
4417
4418 return items;
4419 };
4420
4421 /**
4422 * Aggregate the events emitted by the group.
4423 *
4424 * When events are aggregated, the group will listen to all contained items for the event,
4425 * and then emit the event under a new name. The new event will contain an additional leading
4426 * parameter containing the item that emitted the original event. Other arguments emitted from
4427 * the original event are passed through.
4428 *
4429 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4430 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4431 * A `null` value will remove aggregated events.
4432
4433 * @throws {Error} An error is thrown if aggregation already exists.
4434 */
4435 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4436 var i, len, item, add, remove, itemEvent, groupEvent;
4437
4438 for ( itemEvent in events ) {
4439 groupEvent = events[ itemEvent ];
4440
4441 // Remove existing aggregated event
4442 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4443 // Don't allow duplicate aggregations
4444 if ( groupEvent ) {
4445 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4446 }
4447 // Remove event aggregation from existing items
4448 for ( i = 0, len = this.items.length; i < len; i++ ) {
4449 item = this.items[ i ];
4450 if ( item.connect && item.disconnect ) {
4451 remove = {};
4452 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4453 item.disconnect( this, remove );
4454 }
4455 }
4456 // Prevent future items from aggregating event
4457 delete this.aggregateItemEvents[ itemEvent ];
4458 }
4459
4460 // Add new aggregate event
4461 if ( groupEvent ) {
4462 // Make future items aggregate event
4463 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4464 // Add event aggregation to existing items
4465 for ( i = 0, len = this.items.length; i < len; i++ ) {
4466 item = this.items[ i ];
4467 if ( item.connect && item.disconnect ) {
4468 add = {};
4469 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4470 item.connect( this, add );
4471 }
4472 }
4473 }
4474 }
4475 };
4476
4477 /**
4478 * Add items to the group.
4479 *
4480 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4481 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4482 *
4483 * @param {OO.ui.Element[]} items An array of items to add to the group
4484 * @param {number} [index] Index of the insertion point
4485 * @chainable
4486 */
4487 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4488 var i, len, item, event, events, currentIndex,
4489 itemElements = [];
4490
4491 for ( i = 0, len = items.length; i < len; i++ ) {
4492 item = items[ i ];
4493
4494 // Check if item exists then remove it first, effectively "moving" it
4495 currentIndex = $.inArray( item, this.items );
4496 if ( currentIndex >= 0 ) {
4497 this.removeItems( [ item ] );
4498 // Adjust index to compensate for removal
4499 if ( currentIndex < index ) {
4500 index--;
4501 }
4502 }
4503 // Add the item
4504 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4505 events = {};
4506 for ( event in this.aggregateItemEvents ) {
4507 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4508 }
4509 item.connect( this, events );
4510 }
4511 item.setElementGroup( this );
4512 itemElements.push( item.$element.get( 0 ) );
4513 }
4514
4515 if ( index === undefined || index < 0 || index >= this.items.length ) {
4516 this.$group.append( itemElements );
4517 this.items.push.apply( this.items, items );
4518 } else if ( index === 0 ) {
4519 this.$group.prepend( itemElements );
4520 this.items.unshift.apply( this.items, items );
4521 } else {
4522 this.items[ index ].$element.before( itemElements );
4523 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4524 }
4525
4526 return this;
4527 };
4528
4529 /**
4530 * Remove the specified items from a group.
4531 *
4532 * Removed items are detached (not removed) from the DOM so that they may be reused.
4533 * To remove all items from a group, you may wish to use the #clearItems method instead.
4534 *
4535 * @param {OO.ui.Element[]} items An array of items to remove
4536 * @chainable
4537 */
4538 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4539 var i, len, item, index, remove, itemEvent;
4540
4541 // Remove specific items
4542 for ( i = 0, len = items.length; i < len; i++ ) {
4543 item = items[ i ];
4544 index = $.inArray( item, this.items );
4545 if ( index !== -1 ) {
4546 if (
4547 item.connect && item.disconnect &&
4548 !$.isEmptyObject( this.aggregateItemEvents )
4549 ) {
4550 remove = {};
4551 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4552 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4553 }
4554 item.disconnect( this, remove );
4555 }
4556 item.setElementGroup( null );
4557 this.items.splice( index, 1 );
4558 item.$element.detach();
4559 }
4560 }
4561
4562 return this;
4563 };
4564
4565 /**
4566 * Clear all items from the group.
4567 *
4568 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4569 * To remove only a subset of items from a group, use the #removeItems method.
4570 *
4571 * @chainable
4572 */
4573 OO.ui.GroupElement.prototype.clearItems = function () {
4574 var i, len, item, remove, itemEvent;
4575
4576 // Remove all items
4577 for ( i = 0, len = this.items.length; i < len; i++ ) {
4578 item = this.items[ i ];
4579 if (
4580 item.connect && item.disconnect &&
4581 !$.isEmptyObject( this.aggregateItemEvents )
4582 ) {
4583 remove = {};
4584 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4585 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4586 }
4587 item.disconnect( this, remove );
4588 }
4589 item.setElementGroup( null );
4590 item.$element.detach();
4591 }
4592
4593 this.items = [];
4594 return this;
4595 };
4596
4597 /**
4598 * DraggableElement is a mixin class used to create elements that can be clicked
4599 * and dragged by a mouse to a new position within a group. This class must be used
4600 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4601 * the draggable elements.
4602 *
4603 * @abstract
4604 * @class
4605 *
4606 * @constructor
4607 */
4608 OO.ui.DraggableElement = function OoUiDraggableElement() {
4609 // Properties
4610 this.index = null;
4611
4612 // Initialize and events
4613 this.$element
4614 .attr( 'draggable', true )
4615 .addClass( 'oo-ui-draggableElement' )
4616 .on( {
4617 dragstart: this.onDragStart.bind( this ),
4618 dragover: this.onDragOver.bind( this ),
4619 dragend: this.onDragEnd.bind( this ),
4620 drop: this.onDrop.bind( this )
4621 } );
4622 };
4623
4624 OO.initClass( OO.ui.DraggableElement );
4625
4626 /* Events */
4627
4628 /**
4629 * @event dragstart
4630 *
4631 * A dragstart event is emitted when the user clicks and begins dragging an item.
4632 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4633 */
4634
4635 /**
4636 * @event dragend
4637 * A dragend event is emitted when the user drags an item and releases the mouse,
4638 * thus terminating the drag operation.
4639 */
4640
4641 /**
4642 * @event drop
4643 * A drop event is emitted when the user drags an item and then releases the mouse button
4644 * over a valid target.
4645 */
4646
4647 /* Static Properties */
4648
4649 /**
4650 * @inheritdoc OO.ui.ButtonElement
4651 */
4652 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4653
4654 /* Methods */
4655
4656 /**
4657 * Respond to dragstart event.
4658 *
4659 * @private
4660 * @param {jQuery.Event} event jQuery event
4661 * @fires dragstart
4662 */
4663 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4664 var dataTransfer = e.originalEvent.dataTransfer;
4665 // Define drop effect
4666 dataTransfer.dropEffect = 'none';
4667 dataTransfer.effectAllowed = 'move';
4668 // We must set up a dataTransfer data property or Firefox seems to
4669 // ignore the fact the element is draggable.
4670 try {
4671 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4672 } catch ( err ) {
4673 // The above is only for firefox. No need to set a catch clause
4674 // if it fails, move on.
4675 }
4676 // Add dragging class
4677 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4678 // Emit event
4679 this.emit( 'dragstart', this );
4680 return true;
4681 };
4682
4683 /**
4684 * Respond to dragend event.
4685 *
4686 * @private
4687 * @fires dragend
4688 */
4689 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4690 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4691 this.emit( 'dragend' );
4692 };
4693
4694 /**
4695 * Handle drop event.
4696 *
4697 * @private
4698 * @param {jQuery.Event} event jQuery event
4699 * @fires drop
4700 */
4701 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4702 e.preventDefault();
4703 this.emit( 'drop', e );
4704 };
4705
4706 /**
4707 * In order for drag/drop to work, the dragover event must
4708 * return false and stop propogation.
4709 *
4710 * @private
4711 */
4712 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4713 e.preventDefault();
4714 };
4715
4716 /**
4717 * Set item index.
4718 * Store it in the DOM so we can access from the widget drag event
4719 *
4720 * @private
4721 * @param {number} Item index
4722 */
4723 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4724 if ( this.index !== index ) {
4725 this.index = index;
4726 this.$element.data( 'index', index );
4727 }
4728 };
4729
4730 /**
4731 * Get item index
4732 *
4733 * @private
4734 * @return {number} Item index
4735 */
4736 OO.ui.DraggableElement.prototype.getIndex = function () {
4737 return this.index;
4738 };
4739
4740 /**
4741 * DraggableGroupElement is a mixin class used to create a group element to
4742 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4743 * The class is used with OO.ui.DraggableElement.
4744 *
4745 * @abstract
4746 * @class
4747 * @mixins OO.ui.GroupElement
4748 *
4749 * @constructor
4750 * @param {Object} [config] Configuration options
4751 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4752 * should match the layout of the items. Items displayed in a single row
4753 * or in several rows should use horizontal orientation. The vertical orientation should only be
4754 * used when the items are displayed in a single column. Defaults to 'vertical'
4755 */
4756 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4757 // Configuration initialization
4758 config = config || {};
4759
4760 // Parent constructor
4761 OO.ui.GroupElement.call( this, config );
4762
4763 // Properties
4764 this.orientation = config.orientation || 'vertical';
4765 this.dragItem = null;
4766 this.itemDragOver = null;
4767 this.itemKeys = {};
4768 this.sideInsertion = '';
4769
4770 // Events
4771 this.aggregate( {
4772 dragstart: 'itemDragStart',
4773 dragend: 'itemDragEnd',
4774 drop: 'itemDrop'
4775 } );
4776 this.connect( this, {
4777 itemDragStart: 'onItemDragStart',
4778 itemDrop: 'onItemDrop',
4779 itemDragEnd: 'onItemDragEnd'
4780 } );
4781 this.$element.on( {
4782 dragover: $.proxy( this.onDragOver, this ),
4783 dragleave: $.proxy( this.onDragLeave, this )
4784 } );
4785
4786 // Initialize
4787 if ( Array.isArray( config.items ) ) {
4788 this.addItems( config.items );
4789 }
4790 this.$placeholder = $( '<div>' )
4791 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4792 this.$element
4793 .addClass( 'oo-ui-draggableGroupElement' )
4794 .append( this.$status )
4795 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4796 .prepend( this.$placeholder );
4797 };
4798
4799 /* Setup */
4800 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4801
4802 /* Events */
4803
4804 /**
4805 * A 'reorder' event is emitted when the order of items in the group changes.
4806 *
4807 * @event reorder
4808 * @param {OO.ui.DraggableElement} item Reordered item
4809 * @param {number} [newIndex] New index for the item
4810 */
4811
4812 /* Methods */
4813
4814 /**
4815 * Respond to item drag start event
4816 *
4817 * @private
4818 * @param {OO.ui.DraggableElement} item Dragged item
4819 */
4820 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4821 var i, len;
4822
4823 // Map the index of each object
4824 for ( i = 0, len = this.items.length; i < len; i++ ) {
4825 this.items[ i ].setIndex( i );
4826 }
4827
4828 if ( this.orientation === 'horizontal' ) {
4829 // Set the height of the indicator
4830 this.$placeholder.css( {
4831 height: item.$element.outerHeight(),
4832 width: 2
4833 } );
4834 } else {
4835 // Set the width of the indicator
4836 this.$placeholder.css( {
4837 height: 2,
4838 width: item.$element.outerWidth()
4839 } );
4840 }
4841 this.setDragItem( item );
4842 };
4843
4844 /**
4845 * Respond to item drag end event
4846 *
4847 * @private
4848 */
4849 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4850 this.unsetDragItem();
4851 return false;
4852 };
4853
4854 /**
4855 * Handle drop event and switch the order of the items accordingly
4856 *
4857 * @private
4858 * @param {OO.ui.DraggableElement} item Dropped item
4859 * @fires reorder
4860 */
4861 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4862 var toIndex = item.getIndex();
4863 // Check if the dropped item is from the current group
4864 // TODO: Figure out a way to configure a list of legally droppable
4865 // elements even if they are not yet in the list
4866 if ( this.getDragItem() ) {
4867 // If the insertion point is 'after', the insertion index
4868 // is shifted to the right (or to the left in RTL, hence 'after')
4869 if ( this.sideInsertion === 'after' ) {
4870 toIndex++;
4871 }
4872 // Emit change event
4873 this.emit( 'reorder', this.getDragItem(), toIndex );
4874 }
4875 this.unsetDragItem();
4876 // Return false to prevent propogation
4877 return false;
4878 };
4879
4880 /**
4881 * Handle dragleave event.
4882 *
4883 * @private
4884 */
4885 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4886 // This means the item was dragged outside the widget
4887 this.$placeholder
4888 .css( 'left', 0 )
4889 .addClass( 'oo-ui-element-hidden' );
4890 };
4891
4892 /**
4893 * Respond to dragover event
4894 *
4895 * @private
4896 * @param {jQuery.Event} event Event details
4897 */
4898 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4899 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4900 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4901 clientX = e.originalEvent.clientX,
4902 clientY = e.originalEvent.clientY;
4903
4904 // Get the OptionWidget item we are dragging over
4905 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4906 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4907 if ( $optionWidget[ 0 ] ) {
4908 itemOffset = $optionWidget.offset();
4909 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4910 itemPosition = $optionWidget.position();
4911 itemIndex = $optionWidget.data( 'index' );
4912 }
4913
4914 if (
4915 itemOffset &&
4916 this.isDragging() &&
4917 itemIndex !== this.getDragItem().getIndex()
4918 ) {
4919 if ( this.orientation === 'horizontal' ) {
4920 // Calculate where the mouse is relative to the item width
4921 itemSize = itemBoundingRect.width;
4922 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4923 dragPosition = clientX;
4924 // Which side of the item we hover over will dictate
4925 // where the placeholder will appear, on the left or
4926 // on the right
4927 cssOutput = {
4928 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4929 top: itemPosition.top
4930 };
4931 } else {
4932 // Calculate where the mouse is relative to the item height
4933 itemSize = itemBoundingRect.height;
4934 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4935 dragPosition = clientY;
4936 // Which side of the item we hover over will dictate
4937 // where the placeholder will appear, on the top or
4938 // on the bottom
4939 cssOutput = {
4940 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4941 left: itemPosition.left
4942 };
4943 }
4944 // Store whether we are before or after an item to rearrange
4945 // For horizontal layout, we need to account for RTL, as this is flipped
4946 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4947 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4948 } else {
4949 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4950 }
4951 // Add drop indicator between objects
4952 this.$placeholder
4953 .css( cssOutput )
4954 .removeClass( 'oo-ui-element-hidden' );
4955 } else {
4956 // This means the item was dragged outside the widget
4957 this.$placeholder
4958 .css( 'left', 0 )
4959 .addClass( 'oo-ui-element-hidden' );
4960 }
4961 // Prevent default
4962 e.preventDefault();
4963 };
4964
4965 /**
4966 * Set a dragged item
4967 *
4968 * @param {OO.ui.DraggableElement} item Dragged item
4969 */
4970 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4971 this.dragItem = item;
4972 };
4973
4974 /**
4975 * Unset the current dragged item
4976 */
4977 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4978 this.dragItem = null;
4979 this.itemDragOver = null;
4980 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4981 this.sideInsertion = '';
4982 };
4983
4984 /**
4985 * Get the item that is currently being dragged.
4986 *
4987 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4988 */
4989 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4990 return this.dragItem;
4991 };
4992
4993 /**
4994 * Check if an item in the group is currently being dragged.
4995 *
4996 * @return {Boolean} Item is being dragged
4997 */
4998 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4999 return this.getDragItem() !== null;
5000 };
5001
5002 /**
5003 * IconElement is often mixed into other classes to generate an icon.
5004 * Icons are graphics, about the size of normal text. They are used to aid the user
5005 * in locating a control or to convey information in a space-efficient way. See the
5006 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5007 * included in the library.
5008 *
5009 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5010 *
5011 * @abstract
5012 * @class
5013 *
5014 * @constructor
5015 * @param {Object} [config] Configuration options
5016 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5017 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5018 * the icon element be set to an existing icon instead of the one generated by this class, set a
5019 * value using a jQuery selection. For example:
5020 *
5021 * // Use a <div> tag instead of a <span>
5022 * $icon: $("<div>")
5023 * // Use an existing icon element instead of the one generated by the class
5024 * $icon: this.$element
5025 * // Use an icon element from a child widget
5026 * $icon: this.childwidget.$element
5027 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5028 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5029 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5030 * by the user's language.
5031 *
5032 * Example of an i18n map:
5033 *
5034 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5035 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5036 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5037 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5038 * text. The icon title is displayed when users move the mouse over the icon.
5039 */
5040 OO.ui.IconElement = function OoUiIconElement( config ) {
5041 // Configuration initialization
5042 config = config || {};
5043
5044 // Properties
5045 this.$icon = null;
5046 this.icon = null;
5047 this.iconTitle = null;
5048
5049 // Initialization
5050 this.setIcon( config.icon || this.constructor.static.icon );
5051 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5052 this.setIconElement( config.$icon || $( '<span>' ) );
5053 };
5054
5055 /* Setup */
5056
5057 OO.initClass( OO.ui.IconElement );
5058
5059 /* Static Properties */
5060
5061 /**
5062 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5063 * for i18n purposes and contains a `default` icon name and additional names keyed by
5064 * language code. The `default` name is used when no icon is keyed by the user's language.
5065 *
5066 * Example of an i18n map:
5067 *
5068 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5069 *
5070 * Note: the static property will be overridden if the #icon configuration is used.
5071 *
5072 * @static
5073 * @inheritable
5074 * @property {Object|string}
5075 */
5076 OO.ui.IconElement.static.icon = null;
5077
5078 /**
5079 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5080 * function that returns title text, or `null` for no title.
5081 *
5082 * The static property will be overridden if the #iconTitle configuration is used.
5083 *
5084 * @static
5085 * @inheritable
5086 * @property {string|Function|null}
5087 */
5088 OO.ui.IconElement.static.iconTitle = null;
5089
5090 /* Methods */
5091
5092 /**
5093 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5094 * applies to the specified icon element instead of the one created by the class. If an icon
5095 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5096 * and mixin methods will no longer affect the element.
5097 *
5098 * @param {jQuery} $icon Element to use as icon
5099 */
5100 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
5101 if ( this.$icon ) {
5102 this.$icon
5103 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5104 .removeAttr( 'title' );
5105 }
5106
5107 this.$icon = $icon
5108 .addClass( 'oo-ui-iconElement-icon' )
5109 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5110 if ( this.iconTitle !== null ) {
5111 this.$icon.attr( 'title', this.iconTitle );
5112 }
5113 };
5114
5115 /**
5116 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5117 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5118 * for an example.
5119 *
5120 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5121 * by language code, or `null` to remove the icon.
5122 * @chainable
5123 */
5124 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5125 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5126 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5127
5128 if ( this.icon !== icon ) {
5129 if ( this.$icon ) {
5130 if ( this.icon !== null ) {
5131 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5132 }
5133 if ( icon !== null ) {
5134 this.$icon.addClass( 'oo-ui-icon-' + icon );
5135 }
5136 }
5137 this.icon = icon;
5138 }
5139
5140 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5141 this.updateThemeClasses();
5142
5143 return this;
5144 };
5145
5146 /**
5147 * Set the icon title. Use `null` to remove the title.
5148 *
5149 * @param {string|Function|null} iconTitle A text string used as the icon title,
5150 * a function that returns title text, or `null` for no title.
5151 * @chainable
5152 */
5153 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5154 iconTitle = typeof iconTitle === 'function' ||
5155 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5156 OO.ui.resolveMsg( iconTitle ) : null;
5157
5158 if ( this.iconTitle !== iconTitle ) {
5159 this.iconTitle = iconTitle;
5160 if ( this.$icon ) {
5161 if ( this.iconTitle !== null ) {
5162 this.$icon.attr( 'title', iconTitle );
5163 } else {
5164 this.$icon.removeAttr( 'title' );
5165 }
5166 }
5167 }
5168
5169 return this;
5170 };
5171
5172 /**
5173 * Get the symbolic name of the icon.
5174 *
5175 * @return {string} Icon name
5176 */
5177 OO.ui.IconElement.prototype.getIcon = function () {
5178 return this.icon;
5179 };
5180
5181 /**
5182 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5183 *
5184 * @return {string} Icon title text
5185 */
5186 OO.ui.IconElement.prototype.getIconTitle = function () {
5187 return this.iconTitle;
5188 };
5189
5190 /**
5191 * IndicatorElement is often mixed into other classes to generate an indicator.
5192 * Indicators are small graphics that are generally used in two ways:
5193 *
5194 * - To draw attention to the status of an item. For example, an indicator might be
5195 * used to show that an item in a list has errors that need to be resolved.
5196 * - To clarify the function of a control that acts in an exceptional way (a button
5197 * that opens a menu instead of performing an action directly, for example).
5198 *
5199 * For a list of indicators included in the library, please see the
5200 * [OOjs UI documentation on MediaWiki] [1].
5201 *
5202 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5203 *
5204 * @abstract
5205 * @class
5206 *
5207 * @constructor
5208 * @param {Object} [config] Configuration options
5209 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5210 * configuration is omitted, the indicator element will use a generated `<span>`.
5211 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5212 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5213 * in the library.
5214 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5215 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5216 * or a function that returns title text. The indicator title is displayed when users move
5217 * the mouse over the indicator.
5218 */
5219 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5220 // Configuration initialization
5221 config = config || {};
5222
5223 // Properties
5224 this.$indicator = null;
5225 this.indicator = null;
5226 this.indicatorTitle = null;
5227
5228 // Initialization
5229 this.setIndicator( config.indicator || this.constructor.static.indicator );
5230 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5231 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5232 };
5233
5234 /* Setup */
5235
5236 OO.initClass( OO.ui.IndicatorElement );
5237
5238 /* Static Properties */
5239
5240 /**
5241 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5242 * The static property will be overridden if the #indicator configuration is used.
5243 *
5244 * @static
5245 * @inheritable
5246 * @property {string|null}
5247 */
5248 OO.ui.IndicatorElement.static.indicator = null;
5249
5250 /**
5251 * A text string used as the indicator title, a function that returns title text, or `null`
5252 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5253 *
5254 * @static
5255 * @inheritable
5256 * @property {string|Function|null}
5257 */
5258 OO.ui.IndicatorElement.static.indicatorTitle = null;
5259
5260 /* Methods */
5261
5262 /**
5263 * Set the indicator element.
5264 *
5265 * If an element is already set, it will be cleaned up before setting up the new element.
5266 *
5267 * @param {jQuery} $indicator Element to use as indicator
5268 */
5269 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5270 if ( this.$indicator ) {
5271 this.$indicator
5272 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5273 .removeAttr( 'title' );
5274 }
5275
5276 this.$indicator = $indicator
5277 .addClass( 'oo-ui-indicatorElement-indicator' )
5278 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5279 if ( this.indicatorTitle !== null ) {
5280 this.$indicator.attr( 'title', this.indicatorTitle );
5281 }
5282 };
5283
5284 /**
5285 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5286 *
5287 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5288 * @chainable
5289 */
5290 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5291 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5292
5293 if ( this.indicator !== indicator ) {
5294 if ( this.$indicator ) {
5295 if ( this.indicator !== null ) {
5296 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5297 }
5298 if ( indicator !== null ) {
5299 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5300 }
5301 }
5302 this.indicator = indicator;
5303 }
5304
5305 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5306 this.updateThemeClasses();
5307
5308 return this;
5309 };
5310
5311 /**
5312 * Set the indicator title.
5313 *
5314 * The title is displayed when a user moves the mouse over the indicator.
5315 *
5316 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5317 * `null` for no indicator title
5318 * @chainable
5319 */
5320 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5321 indicatorTitle = typeof indicatorTitle === 'function' ||
5322 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5323 OO.ui.resolveMsg( indicatorTitle ) : null;
5324
5325 if ( this.indicatorTitle !== indicatorTitle ) {
5326 this.indicatorTitle = indicatorTitle;
5327 if ( this.$indicator ) {
5328 if ( this.indicatorTitle !== null ) {
5329 this.$indicator.attr( 'title', indicatorTitle );
5330 } else {
5331 this.$indicator.removeAttr( 'title' );
5332 }
5333 }
5334 }
5335
5336 return this;
5337 };
5338
5339 /**
5340 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5341 *
5342 * @return {string} Symbolic name of indicator
5343 */
5344 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5345 return this.indicator;
5346 };
5347
5348 /**
5349 * Get the indicator title.
5350 *
5351 * The title is displayed when a user moves the mouse over the indicator.
5352 *
5353 * @return {string} Indicator title text
5354 */
5355 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5356 return this.indicatorTitle;
5357 };
5358
5359 /**
5360 * LabelElement is often mixed into other classes to generate a label, which
5361 * helps identify the function of an interface element.
5362 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5363 *
5364 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5365 *
5366 * @abstract
5367 * @class
5368 *
5369 * @constructor
5370 * @param {Object} [config] Configuration options
5371 * @cfg {jQuery} [$label] The label element created by the class. If this
5372 * configuration is omitted, the label element will use a generated `<span>`.
5373 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5374 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5375 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5376 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5377 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5378 * The label will be truncated to fit if necessary.
5379 */
5380 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5381 // Configuration initialization
5382 config = config || {};
5383
5384 // Properties
5385 this.$label = null;
5386 this.label = null;
5387 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5388
5389 // Initialization
5390 this.setLabel( config.label || this.constructor.static.label );
5391 this.setLabelElement( config.$label || $( '<span>' ) );
5392 };
5393
5394 /* Setup */
5395
5396 OO.initClass( OO.ui.LabelElement );
5397
5398 /* Events */
5399
5400 /**
5401 * @event labelChange
5402 * @param {string} value
5403 */
5404
5405 /* Static Properties */
5406
5407 /**
5408 * The label text. The label can be specified as a plaintext string, a function that will
5409 * produce a string in the future, or `null` for no label. The static value will
5410 * be overridden if a label is specified with the #label config option.
5411 *
5412 * @static
5413 * @inheritable
5414 * @property {string|Function|null}
5415 */
5416 OO.ui.LabelElement.static.label = null;
5417
5418 /* Methods */
5419
5420 /**
5421 * Set the label element.
5422 *
5423 * If an element is already set, it will be cleaned up before setting up the new element.
5424 *
5425 * @param {jQuery} $label Element to use as label
5426 */
5427 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5428 if ( this.$label ) {
5429 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5430 }
5431
5432 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5433 this.setLabelContent( this.label );
5434 };
5435
5436 /**
5437 * Set the label.
5438 *
5439 * An empty string will result in the label being hidden. A string containing only whitespace will
5440 * be converted to a single `&nbsp;`.
5441 *
5442 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5443 * text; or null for no label
5444 * @chainable
5445 */
5446 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5447 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5448 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5449
5450 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5451
5452 if ( this.label !== label ) {
5453 if ( this.$label ) {
5454 this.setLabelContent( label );
5455 }
5456 this.label = label;
5457 this.emit( 'labelChange' );
5458 }
5459
5460 return this;
5461 };
5462
5463 /**
5464 * Get the label.
5465 *
5466 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5467 * text; or null for no label
5468 */
5469 OO.ui.LabelElement.prototype.getLabel = function () {
5470 return this.label;
5471 };
5472
5473 /**
5474 * Fit the label.
5475 *
5476 * @chainable
5477 */
5478 OO.ui.LabelElement.prototype.fitLabel = function () {
5479 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5480 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5481 }
5482
5483 return this;
5484 };
5485
5486 /**
5487 * Set the content of the label.
5488 *
5489 * Do not call this method until after the label element has been set by #setLabelElement.
5490 *
5491 * @private
5492 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5493 * text; or null for no label
5494 */
5495 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5496 if ( typeof label === 'string' ) {
5497 if ( label.match( /^\s*$/ ) ) {
5498 // Convert whitespace only string to a single non-breaking space
5499 this.$label.html( '&nbsp;' );
5500 } else {
5501 this.$label.text( label );
5502 }
5503 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5504 this.$label.html( label.toString() );
5505 } else if ( label instanceof jQuery ) {
5506 this.$label.empty().append( label );
5507 } else {
5508 this.$label.empty();
5509 }
5510 };
5511
5512 /**
5513 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5514 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5515 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5516 * from the lookup menu, that value becomes the value of the input field.
5517 *
5518 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5519 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5520 * re-enable lookups.
5521 *
5522 * See the [OOjs UI demos][1] for an example.
5523 *
5524 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5525 *
5526 * @class
5527 * @abstract
5528 *
5529 * @constructor
5530 * @param {Object} [config] Configuration options
5531 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5532 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5533 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5534 * By default, the lookup menu is not generated and displayed until the user begins to type.
5535 */
5536 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5537 // Configuration initialization
5538 config = config || {};
5539
5540 // Properties
5541 this.$overlay = config.$overlay || this.$element;
5542 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5543 widget: this,
5544 input: this,
5545 $container: config.$container
5546 } );
5547
5548 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5549
5550 this.lookupCache = {};
5551 this.lookupQuery = null;
5552 this.lookupRequest = null;
5553 this.lookupsDisabled = false;
5554 this.lookupInputFocused = false;
5555
5556 // Events
5557 this.$input.on( {
5558 focus: this.onLookupInputFocus.bind( this ),
5559 blur: this.onLookupInputBlur.bind( this ),
5560 mousedown: this.onLookupInputMouseDown.bind( this )
5561 } );
5562 this.connect( this, { change: 'onLookupInputChange' } );
5563 this.lookupMenu.connect( this, {
5564 toggle: 'onLookupMenuToggle',
5565 choose: 'onLookupMenuItemChoose'
5566 } );
5567
5568 // Initialization
5569 this.$element.addClass( 'oo-ui-lookupElement' );
5570 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5571 this.$overlay.append( this.lookupMenu.$element );
5572 };
5573
5574 /* Methods */
5575
5576 /**
5577 * Handle input focus event.
5578 *
5579 * @protected
5580 * @param {jQuery.Event} e Input focus event
5581 */
5582 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5583 this.lookupInputFocused = true;
5584 this.populateLookupMenu();
5585 };
5586
5587 /**
5588 * Handle input blur event.
5589 *
5590 * @protected
5591 * @param {jQuery.Event} e Input blur event
5592 */
5593 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5594 this.closeLookupMenu();
5595 this.lookupInputFocused = false;
5596 };
5597
5598 /**
5599 * Handle input mouse down event.
5600 *
5601 * @protected
5602 * @param {jQuery.Event} e Input mouse down event
5603 */
5604 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5605 // Only open the menu if the input was already focused.
5606 // This way we allow the user to open the menu again after closing it with Esc
5607 // by clicking in the input. Opening (and populating) the menu when initially
5608 // clicking into the input is handled by the focus handler.
5609 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5610 this.populateLookupMenu();
5611 }
5612 };
5613
5614 /**
5615 * Handle input change event.
5616 *
5617 * @protected
5618 * @param {string} value New input value
5619 */
5620 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5621 if ( this.lookupInputFocused ) {
5622 this.populateLookupMenu();
5623 }
5624 };
5625
5626 /**
5627 * Handle the lookup menu being shown/hidden.
5628 *
5629 * @protected
5630 * @param {boolean} visible Whether the lookup menu is now visible.
5631 */
5632 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5633 if ( !visible ) {
5634 // When the menu is hidden, abort any active request and clear the menu.
5635 // This has to be done here in addition to closeLookupMenu(), because
5636 // MenuSelectWidget will close itself when the user presses Esc.
5637 this.abortLookupRequest();
5638 this.lookupMenu.clearItems();
5639 }
5640 };
5641
5642 /**
5643 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5644 *
5645 * @protected
5646 * @param {OO.ui.MenuOptionWidget} item Selected item
5647 */
5648 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5649 this.setValue( item.getData() );
5650 };
5651
5652 /**
5653 * Get lookup menu.
5654 *
5655 * @private
5656 * @return {OO.ui.TextInputMenuSelectWidget}
5657 */
5658 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5659 return this.lookupMenu;
5660 };
5661
5662 /**
5663 * Disable or re-enable lookups.
5664 *
5665 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5666 *
5667 * @param {boolean} disabled Disable lookups
5668 */
5669 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5670 this.lookupsDisabled = !!disabled;
5671 };
5672
5673 /**
5674 * Open the menu. If there are no entries in the menu, this does nothing.
5675 *
5676 * @private
5677 * @chainable
5678 */
5679 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5680 if ( !this.lookupMenu.isEmpty() ) {
5681 this.lookupMenu.toggle( true );
5682 }
5683 return this;
5684 };
5685
5686 /**
5687 * Close the menu, empty it, and abort any pending request.
5688 *
5689 * @private
5690 * @chainable
5691 */
5692 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5693 this.lookupMenu.toggle( false );
5694 this.abortLookupRequest();
5695 this.lookupMenu.clearItems();
5696 return this;
5697 };
5698
5699 /**
5700 * Request menu items based on the input's current value, and when they arrive,
5701 * populate the menu with these items and show the menu.
5702 *
5703 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5704 *
5705 * @private
5706 * @chainable
5707 */
5708 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5709 var widget = this,
5710 value = this.getValue();
5711
5712 if ( this.lookupsDisabled ) {
5713 return;
5714 }
5715
5716 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5717 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5718 this.closeLookupMenu();
5719 // Skip population if there is already a request pending for the current value
5720 } else if ( value !== this.lookupQuery ) {
5721 this.getLookupMenuItems()
5722 .done( function ( items ) {
5723 widget.lookupMenu.clearItems();
5724 if ( items.length ) {
5725 widget.lookupMenu
5726 .addItems( items )
5727 .toggle( true );
5728 widget.initializeLookupMenuSelection();
5729 } else {
5730 widget.lookupMenu.toggle( false );
5731 }
5732 } )
5733 .fail( function () {
5734 widget.lookupMenu.clearItems();
5735 } );
5736 }
5737
5738 return this;
5739 };
5740
5741 /**
5742 * Select and highlight the first selectable item in the menu.
5743 *
5744 * @private
5745 * @chainable
5746 */
5747 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5748 if ( !this.lookupMenu.getSelectedItem() ) {
5749 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5750 }
5751 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5752 };
5753
5754 /**
5755 * Get lookup menu items for the current query.
5756 *
5757 * @private
5758 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5759 * the done event. If the request was aborted to make way for a subsequent request, this promise
5760 * will not be rejected: it will remain pending forever.
5761 */
5762 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5763 var widget = this,
5764 value = this.getValue(),
5765 deferred = $.Deferred(),
5766 ourRequest;
5767
5768 this.abortLookupRequest();
5769 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5770 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5771 } else {
5772 this.pushPending();
5773 this.lookupQuery = value;
5774 ourRequest = this.lookupRequest = this.getLookupRequest();
5775 ourRequest
5776 .always( function () {
5777 // We need to pop pending even if this is an old request, otherwise
5778 // the widget will remain pending forever.
5779 // TODO: this assumes that an aborted request will fail or succeed soon after
5780 // being aborted, or at least eventually. It would be nice if we could popPending()
5781 // at abort time, but only if we knew that we hadn't already called popPending()
5782 // for that request.
5783 widget.popPending();
5784 } )
5785 .done( function ( response ) {
5786 // If this is an old request (and aborting it somehow caused it to still succeed),
5787 // ignore its success completely
5788 if ( ourRequest === widget.lookupRequest ) {
5789 widget.lookupQuery = null;
5790 widget.lookupRequest = null;
5791 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
5792 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5793 }
5794 } )
5795 .fail( function () {
5796 // If this is an old request (or a request failing because it's being aborted),
5797 // ignore its failure completely
5798 if ( ourRequest === widget.lookupRequest ) {
5799 widget.lookupQuery = null;
5800 widget.lookupRequest = null;
5801 deferred.reject();
5802 }
5803 } );
5804 }
5805 return deferred.promise();
5806 };
5807
5808 /**
5809 * Abort the currently pending lookup request, if any.
5810 *
5811 * @private
5812 */
5813 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5814 var oldRequest = this.lookupRequest;
5815 if ( oldRequest ) {
5816 // First unset this.lookupRequest to the fail handler will notice
5817 // that the request is no longer current
5818 this.lookupRequest = null;
5819 this.lookupQuery = null;
5820 oldRequest.abort();
5821 }
5822 };
5823
5824 /**
5825 * Get a new request object of the current lookup query value.
5826 *
5827 * @protected
5828 * @abstract
5829 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5830 */
5831 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5832 // Stub, implemented in subclass
5833 return null;
5834 };
5835
5836 /**
5837 * Pre-process data returned by the request from #getLookupRequest.
5838 *
5839 * The return value of this function will be cached, and any further queries for the given value
5840 * will use the cache rather than doing API requests.
5841 *
5842 * @protected
5843 * @abstract
5844 * @param {Mixed} response Response from server
5845 * @return {Mixed} Cached result data
5846 */
5847 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5848 // Stub, implemented in subclass
5849 return [];
5850 };
5851
5852 /**
5853 * Get a list of menu option widgets from the (possibly cached) data returned by
5854 * #getLookupCacheDataFromResponse.
5855 *
5856 * @protected
5857 * @abstract
5858 * @param {Mixed} data Cached result data, usually an array
5859 * @return {OO.ui.MenuOptionWidget[]} Menu items
5860 */
5861 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5862 // Stub, implemented in subclass
5863 return [];
5864 };
5865
5866 /**
5867 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5868 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5869 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5870 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5871 *
5872 * @abstract
5873 * @class
5874 *
5875 * @constructor
5876 * @param {Object} [config] Configuration options
5877 * @cfg {Object} [popup] Configuration to pass to popup
5878 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5879 */
5880 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5881 // Configuration initialization
5882 config = config || {};
5883
5884 // Properties
5885 this.popup = new OO.ui.PopupWidget( $.extend(
5886 { autoClose: true },
5887 config.popup,
5888 { $autoCloseIgnore: this.$element }
5889 ) );
5890 };
5891
5892 /* Methods */
5893
5894 /**
5895 * Get popup.
5896 *
5897 * @return {OO.ui.PopupWidget} Popup widget
5898 */
5899 OO.ui.PopupElement.prototype.getPopup = function () {
5900 return this.popup;
5901 };
5902
5903 /**
5904 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5905 * additional functionality to an element created by another class. The class provides
5906 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5907 * which are used to customize the look and feel of a widget to better describe its
5908 * importance and functionality.
5909 *
5910 * The library currently contains the following styling flags for general use:
5911 *
5912 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5913 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5914 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5915 *
5916 * The flags affect the appearance of the buttons:
5917 *
5918 * @example
5919 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5920 * var button1 = new OO.ui.ButtonWidget( {
5921 * label: 'Constructive',
5922 * flags: 'constructive'
5923 * } );
5924 * var button2 = new OO.ui.ButtonWidget( {
5925 * label: 'Destructive',
5926 * flags: 'destructive'
5927 * } );
5928 * var button3 = new OO.ui.ButtonWidget( {
5929 * label: 'Progressive',
5930 * flags: 'progressive'
5931 * } );
5932 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5933 *
5934 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5935 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5936 *
5937 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5938 *
5939 * @abstract
5940 * @class
5941 *
5942 * @constructor
5943 * @param {Object} [config] Configuration options
5944 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5945 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5946 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5947 * @cfg {jQuery} [$flagged] The flagged element. By default,
5948 * the flagged functionality is applied to the element created by the class ($element).
5949 * If a different element is specified, the flagged functionality will be applied to it instead.
5950 */
5951 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5952 // Configuration initialization
5953 config = config || {};
5954
5955 // Properties
5956 this.flags = {};
5957 this.$flagged = null;
5958
5959 // Initialization
5960 this.setFlags( config.flags );
5961 this.setFlaggedElement( config.$flagged || this.$element );
5962 };
5963
5964 /* Events */
5965
5966 /**
5967 * @event flag
5968 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5969 * parameter contains the name of each modified flag and indicates whether it was
5970 * added or removed.
5971 *
5972 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5973 * that the flag was added, `false` that the flag was removed.
5974 */
5975
5976 /* Methods */
5977
5978 /**
5979 * Set the flagged element.
5980 *
5981 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5982 * If an element is already set, the method will remove the mixin’s effect on that element.
5983 *
5984 * @param {jQuery} $flagged Element that should be flagged
5985 */
5986 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5987 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5988 return 'oo-ui-flaggedElement-' + flag;
5989 } ).join( ' ' );
5990
5991 if ( this.$flagged ) {
5992 this.$flagged.removeClass( classNames );
5993 }
5994
5995 this.$flagged = $flagged.addClass( classNames );
5996 };
5997
5998 /**
5999 * Check if the specified flag is set.
6000 *
6001 * @param {string} flag Name of flag
6002 * @return {boolean} The flag is set
6003 */
6004 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
6005 return flag in this.flags;
6006 };
6007
6008 /**
6009 * Get the names of all flags set.
6010 *
6011 * @return {string[]} Flag names
6012 */
6013 OO.ui.FlaggedElement.prototype.getFlags = function () {
6014 return Object.keys( this.flags );
6015 };
6016
6017 /**
6018 * Clear all flags.
6019 *
6020 * @chainable
6021 * @fires flag
6022 */
6023 OO.ui.FlaggedElement.prototype.clearFlags = function () {
6024 var flag, className,
6025 changes = {},
6026 remove = [],
6027 classPrefix = 'oo-ui-flaggedElement-';
6028
6029 for ( flag in this.flags ) {
6030 className = classPrefix + flag;
6031 changes[ flag ] = false;
6032 delete this.flags[ flag ];
6033 remove.push( className );
6034 }
6035
6036 if ( this.$flagged ) {
6037 this.$flagged.removeClass( remove.join( ' ' ) );
6038 }
6039
6040 this.updateThemeClasses();
6041 this.emit( 'flag', changes );
6042
6043 return this;
6044 };
6045
6046 /**
6047 * Add one or more flags.
6048 *
6049 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6050 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6051 * be added (`true`) or removed (`false`).
6052 * @chainable
6053 * @fires flag
6054 */
6055 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
6056 var i, len, flag, className,
6057 changes = {},
6058 add = [],
6059 remove = [],
6060 classPrefix = 'oo-ui-flaggedElement-';
6061
6062 if ( typeof flags === 'string' ) {
6063 className = classPrefix + flags;
6064 // Set
6065 if ( !this.flags[ flags ] ) {
6066 this.flags[ flags ] = true;
6067 add.push( className );
6068 }
6069 } else if ( Array.isArray( flags ) ) {
6070 for ( i = 0, len = flags.length; i < len; i++ ) {
6071 flag = flags[ i ];
6072 className = classPrefix + flag;
6073 // Set
6074 if ( !this.flags[ flag ] ) {
6075 changes[ flag ] = true;
6076 this.flags[ flag ] = true;
6077 add.push( className );
6078 }
6079 }
6080 } else if ( OO.isPlainObject( flags ) ) {
6081 for ( flag in flags ) {
6082 className = classPrefix + flag;
6083 if ( flags[ flag ] ) {
6084 // Set
6085 if ( !this.flags[ flag ] ) {
6086 changes[ flag ] = true;
6087 this.flags[ flag ] = true;
6088 add.push( className );
6089 }
6090 } else {
6091 // Remove
6092 if ( this.flags[ flag ] ) {
6093 changes[ flag ] = false;
6094 delete this.flags[ flag ];
6095 remove.push( className );
6096 }
6097 }
6098 }
6099 }
6100
6101 if ( this.$flagged ) {
6102 this.$flagged
6103 .addClass( add.join( ' ' ) )
6104 .removeClass( remove.join( ' ' ) );
6105 }
6106
6107 this.updateThemeClasses();
6108 this.emit( 'flag', changes );
6109
6110 return this;
6111 };
6112
6113 /**
6114 * TitledElement is mixed into other classes to provide a `title` attribute.
6115 * Titles are rendered by the browser and are made visible when the user moves
6116 * the mouse over the element. Titles are not visible on touch devices.
6117 *
6118 * @example
6119 * // TitledElement provides a 'title' attribute to the
6120 * // ButtonWidget class
6121 * var button = new OO.ui.ButtonWidget( {
6122 * label: 'Button with Title',
6123 * title: 'I am a button'
6124 * } );
6125 * $( 'body' ).append( button.$element );
6126 *
6127 * @abstract
6128 * @class
6129 *
6130 * @constructor
6131 * @param {Object} [config] Configuration options
6132 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6133 * If this config is omitted, the title functionality is applied to $element, the
6134 * element created by the class.
6135 * @cfg {string|Function} [title] The title text or a function that returns text. If
6136 * this config is omitted, the value of the {@link #static-title static title} property is used.
6137 */
6138 OO.ui.TitledElement = function OoUiTitledElement( config ) {
6139 // Configuration initialization
6140 config = config || {};
6141
6142 // Properties
6143 this.$titled = null;
6144 this.title = null;
6145
6146 // Initialization
6147 this.setTitle( config.title || this.constructor.static.title );
6148 this.setTitledElement( config.$titled || this.$element );
6149 };
6150
6151 /* Setup */
6152
6153 OO.initClass( OO.ui.TitledElement );
6154
6155 /* Static Properties */
6156
6157 /**
6158 * The title text, a function that returns text, or `null` for no title. The value of the static property
6159 * is overridden if the #title config option is used.
6160 *
6161 * @static
6162 * @inheritable
6163 * @property {string|Function|null}
6164 */
6165 OO.ui.TitledElement.static.title = null;
6166
6167 /* Methods */
6168
6169 /**
6170 * Set the titled element.
6171 *
6172 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6173 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6174 *
6175 * @param {jQuery} $titled Element that should use the 'titled' functionality
6176 */
6177 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6178 if ( this.$titled ) {
6179 this.$titled.removeAttr( 'title' );
6180 }
6181
6182 this.$titled = $titled;
6183 if ( this.title ) {
6184 this.$titled.attr( 'title', this.title );
6185 }
6186 };
6187
6188 /**
6189 * Set title.
6190 *
6191 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6192 * @chainable
6193 */
6194 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6195 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6196
6197 if ( this.title !== title ) {
6198 if ( this.$titled ) {
6199 if ( title !== null ) {
6200 this.$titled.attr( 'title', title );
6201 } else {
6202 this.$titled.removeAttr( 'title' );
6203 }
6204 }
6205 this.title = title;
6206 }
6207
6208 return this;
6209 };
6210
6211 /**
6212 * Get title.
6213 *
6214 * @return {string} Title string
6215 */
6216 OO.ui.TitledElement.prototype.getTitle = function () {
6217 return this.title;
6218 };
6219
6220 /**
6221 * Element that can be automatically clipped to visible boundaries.
6222 *
6223 * Whenever the element's natural height changes, you have to call
6224 * #clip to make sure it's still clipping correctly.
6225 *
6226 * @abstract
6227 * @class
6228 *
6229 * @constructor
6230 * @param {Object} [config] Configuration options
6231 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6232 */
6233 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6234 // Configuration initialization
6235 config = config || {};
6236
6237 // Properties
6238 this.$clippable = null;
6239 this.clipping = false;
6240 this.clippedHorizontally = false;
6241 this.clippedVertically = false;
6242 this.$clippableContainer = null;
6243 this.$clippableScroller = null;
6244 this.$clippableWindow = null;
6245 this.idealWidth = null;
6246 this.idealHeight = null;
6247 this.onClippableContainerScrollHandler = this.clip.bind( this );
6248 this.onClippableWindowResizeHandler = this.clip.bind( this );
6249
6250 // Initialization
6251 this.setClippableElement( config.$clippable || this.$element );
6252 };
6253
6254 /* Methods */
6255
6256 /**
6257 * Set clippable element.
6258 *
6259 * If an element is already set, it will be cleaned up before setting up the new element.
6260 *
6261 * @param {jQuery} $clippable Element to make clippable
6262 */
6263 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6264 if ( this.$clippable ) {
6265 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6266 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6267 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6268 }
6269
6270 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6271 this.clip();
6272 };
6273
6274 /**
6275 * Toggle clipping.
6276 *
6277 * Do not turn clipping on until after the element is attached to the DOM and visible.
6278 *
6279 * @param {boolean} [clipping] Enable clipping, omit to toggle
6280 * @chainable
6281 */
6282 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6283 clipping = clipping === undefined ? !this.clipping : !!clipping;
6284
6285 if ( this.clipping !== clipping ) {
6286 this.clipping = clipping;
6287 if ( clipping ) {
6288 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6289 // If the clippable container is the root, we have to listen to scroll events and check
6290 // jQuery.scrollTop on the window because of browser inconsistencies
6291 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6292 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6293 this.$clippableContainer;
6294 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6295 this.$clippableWindow = $( this.getElementWindow() )
6296 .on( 'resize', this.onClippableWindowResizeHandler );
6297 // Initial clip after visible
6298 this.clip();
6299 } else {
6300 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6301 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6302
6303 this.$clippableContainer = null;
6304 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6305 this.$clippableScroller = null;
6306 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6307 this.$clippableWindow = null;
6308 }
6309 }
6310
6311 return this;
6312 };
6313
6314 /**
6315 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6316 *
6317 * @return {boolean} Element will be clipped to the visible area
6318 */
6319 OO.ui.ClippableElement.prototype.isClipping = function () {
6320 return this.clipping;
6321 };
6322
6323 /**
6324 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6325 *
6326 * @return {boolean} Part of the element is being clipped
6327 */
6328 OO.ui.ClippableElement.prototype.isClipped = function () {
6329 return this.clippedHorizontally || this.clippedVertically;
6330 };
6331
6332 /**
6333 * Check if the right of the element is being clipped by the nearest scrollable container.
6334 *
6335 * @return {boolean} Part of the element is being clipped
6336 */
6337 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6338 return this.clippedHorizontally;
6339 };
6340
6341 /**
6342 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6343 *
6344 * @return {boolean} Part of the element is being clipped
6345 */
6346 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6347 return this.clippedVertically;
6348 };
6349
6350 /**
6351 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6352 *
6353 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6354 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6355 */
6356 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6357 this.idealWidth = width;
6358 this.idealHeight = height;
6359
6360 if ( !this.clipping ) {
6361 // Update dimensions
6362 this.$clippable.css( { width: width, height: height } );
6363 }
6364 // While clipping, idealWidth and idealHeight are not considered
6365 };
6366
6367 /**
6368 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6369 * the element's natural height changes.
6370 *
6371 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6372 * overlapped by, the visible area of the nearest scrollable container.
6373 *
6374 * @chainable
6375 */
6376 OO.ui.ClippableElement.prototype.clip = function () {
6377 if ( !this.clipping ) {
6378 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6379 return this;
6380 }
6381
6382 var buffer = 7, // Chosen by fair dice roll
6383 cOffset = this.$clippable.offset(),
6384 $container = this.$clippableContainer.is( 'html, body' ) ?
6385 this.$clippableWindow : this.$clippableContainer,
6386 ccOffset = $container.offset() || { top: 0, left: 0 },
6387 ccHeight = $container.innerHeight() - buffer,
6388 ccWidth = $container.innerWidth() - buffer,
6389 cHeight = this.$clippable.outerHeight() + buffer,
6390 cWidth = this.$clippable.outerWidth() + buffer,
6391 scrollTop = this.$clippableScroller.scrollTop(),
6392 scrollLeft = this.$clippableScroller.scrollLeft(),
6393 desiredWidth = cOffset.left < 0 ?
6394 cWidth + cOffset.left :
6395 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6396 desiredHeight = cOffset.top < 0 ?
6397 cHeight + cOffset.top :
6398 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6399 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6400 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6401 clipWidth = desiredWidth < naturalWidth,
6402 clipHeight = desiredHeight < naturalHeight;
6403
6404 if ( clipWidth ) {
6405 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6406 } else {
6407 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6408 }
6409 if ( clipHeight ) {
6410 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6411 } else {
6412 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6413 }
6414
6415 // If we stopped clipping in at least one of the dimensions
6416 if ( !clipWidth || !clipHeight ) {
6417 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6418 }
6419
6420 this.clippedHorizontally = clipWidth;
6421 this.clippedVertically = clipHeight;
6422
6423 return this;
6424 };
6425
6426 /**
6427 * Generic toolbar tool.
6428 *
6429 * @abstract
6430 * @class
6431 * @extends OO.ui.Widget
6432 * @mixins OO.ui.IconElement
6433 * @mixins OO.ui.FlaggedElement
6434 * @mixins OO.ui.TabIndexedElement
6435 *
6436 * @constructor
6437 * @param {OO.ui.ToolGroup} toolGroup
6438 * @param {Object} [config] Configuration options
6439 * @cfg {string|Function} [title] Title text or a function that returns text
6440 */
6441 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6442 // Allow passing positional parameters inside the config object
6443 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6444 config = toolGroup;
6445 toolGroup = config.toolGroup;
6446 }
6447
6448 // Configuration initialization
6449 config = config || {};
6450
6451 // Parent constructor
6452 OO.ui.Tool.super.call( this, config );
6453
6454 // Properties
6455 this.toolGroup = toolGroup;
6456 this.toolbar = this.toolGroup.getToolbar();
6457 this.active = false;
6458 this.$title = $( '<span>' );
6459 this.$accel = $( '<span>' );
6460 this.$link = $( '<a>' );
6461 this.title = null;
6462
6463 // Mixin constructors
6464 OO.ui.IconElement.call( this, config );
6465 OO.ui.FlaggedElement.call( this, config );
6466 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
6467
6468 // Events
6469 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6470
6471 // Initialization
6472 this.$title.addClass( 'oo-ui-tool-title' );
6473 this.$accel
6474 .addClass( 'oo-ui-tool-accel' )
6475 .prop( {
6476 // This may need to be changed if the key names are ever localized,
6477 // but for now they are essentially written in English
6478 dir: 'ltr',
6479 lang: 'en'
6480 } );
6481 this.$link
6482 .addClass( 'oo-ui-tool-link' )
6483 .append( this.$icon, this.$title, this.$accel )
6484 .attr( 'role', 'button' );
6485 this.$element
6486 .data( 'oo-ui-tool', this )
6487 .addClass(
6488 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6489 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6490 )
6491 .append( this.$link );
6492 this.setTitle( config.title || this.constructor.static.title );
6493 };
6494
6495 /* Setup */
6496
6497 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6498 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6499 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6500 OO.mixinClass( OO.ui.Tool, OO.ui.TabIndexedElement );
6501
6502 /* Events */
6503
6504 /**
6505 * @event select
6506 */
6507
6508 /* Static Properties */
6509
6510 /**
6511 * @static
6512 * @inheritdoc
6513 */
6514 OO.ui.Tool.static.tagName = 'span';
6515
6516 /**
6517 * Symbolic name of tool.
6518 *
6519 * @abstract
6520 * @static
6521 * @inheritable
6522 * @property {string}
6523 */
6524 OO.ui.Tool.static.name = '';
6525
6526 /**
6527 * Tool group.
6528 *
6529 * @abstract
6530 * @static
6531 * @inheritable
6532 * @property {string}
6533 */
6534 OO.ui.Tool.static.group = '';
6535
6536 /**
6537 * Tool title.
6538 *
6539 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6540 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6541 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6542 * appended to the title if the tool is part of a bar tool group.
6543 *
6544 * @abstract
6545 * @static
6546 * @inheritable
6547 * @property {string|Function} Title text or a function that returns text
6548 */
6549 OO.ui.Tool.static.title = '';
6550
6551 /**
6552 * Tool can be automatically added to catch-all groups.
6553 *
6554 * @static
6555 * @inheritable
6556 * @property {boolean}
6557 */
6558 OO.ui.Tool.static.autoAddToCatchall = true;
6559
6560 /**
6561 * Tool can be automatically added to named groups.
6562 *
6563 * @static
6564 * @property {boolean}
6565 * @inheritable
6566 */
6567 OO.ui.Tool.static.autoAddToGroup = true;
6568
6569 /**
6570 * Check if this tool is compatible with given data.
6571 *
6572 * @static
6573 * @inheritable
6574 * @param {Mixed} data Data to check
6575 * @return {boolean} Tool can be used with data
6576 */
6577 OO.ui.Tool.static.isCompatibleWith = function () {
6578 return false;
6579 };
6580
6581 /* Methods */
6582
6583 /**
6584 * Handle the toolbar state being updated.
6585 *
6586 * This is an abstract method that must be overridden in a concrete subclass.
6587 *
6588 * @abstract
6589 */
6590 OO.ui.Tool.prototype.onUpdateState = function () {
6591 throw new Error(
6592 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6593 );
6594 };
6595
6596 /**
6597 * Handle the tool being selected.
6598 *
6599 * This is an abstract method that must be overridden in a concrete subclass.
6600 *
6601 * @abstract
6602 */
6603 OO.ui.Tool.prototype.onSelect = function () {
6604 throw new Error(
6605 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6606 );
6607 };
6608
6609 /**
6610 * Check if the button is active.
6611 *
6612 * @return {boolean} Button is active
6613 */
6614 OO.ui.Tool.prototype.isActive = function () {
6615 return this.active;
6616 };
6617
6618 /**
6619 * Make the button appear active or inactive.
6620 *
6621 * @param {boolean} state Make button appear active
6622 */
6623 OO.ui.Tool.prototype.setActive = function ( state ) {
6624 this.active = !!state;
6625 if ( this.active ) {
6626 this.$element.addClass( 'oo-ui-tool-active' );
6627 } else {
6628 this.$element.removeClass( 'oo-ui-tool-active' );
6629 }
6630 };
6631
6632 /**
6633 * Get the tool title.
6634 *
6635 * @param {string|Function} title Title text or a function that returns text
6636 * @chainable
6637 */
6638 OO.ui.Tool.prototype.setTitle = function ( title ) {
6639 this.title = OO.ui.resolveMsg( title );
6640 this.updateTitle();
6641 return this;
6642 };
6643
6644 /**
6645 * Get the tool title.
6646 *
6647 * @return {string} Title text
6648 */
6649 OO.ui.Tool.prototype.getTitle = function () {
6650 return this.title;
6651 };
6652
6653 /**
6654 * Get the tool's symbolic name.
6655 *
6656 * @return {string} Symbolic name of tool
6657 */
6658 OO.ui.Tool.prototype.getName = function () {
6659 return this.constructor.static.name;
6660 };
6661
6662 /**
6663 * Update the title.
6664 */
6665 OO.ui.Tool.prototype.updateTitle = function () {
6666 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6667 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6668 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6669 tooltipParts = [];
6670
6671 this.$title.text( this.title );
6672 this.$accel.text( accel );
6673
6674 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6675 tooltipParts.push( this.title );
6676 }
6677 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6678 tooltipParts.push( accel );
6679 }
6680 if ( tooltipParts.length ) {
6681 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6682 } else {
6683 this.$link.removeAttr( 'title' );
6684 }
6685 };
6686
6687 /**
6688 * Destroy tool.
6689 */
6690 OO.ui.Tool.prototype.destroy = function () {
6691 this.toolbar.disconnect( this );
6692 this.$element.remove();
6693 };
6694
6695 /**
6696 * Collection of tool groups.
6697 *
6698 * @example
6699 * // Basic OOjs UI toolbar example
6700 *
6701 * // Create the toolbar
6702 * var toolFactory = new OO.ui.ToolFactory();
6703 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6704 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6705 *
6706 * // We will be placing status text in this element when tools are used
6707 * var $area = $( '<p>' ).text( 'Toolbar example' );
6708 *
6709 * // Define the tools that we're going to place in our toolbar
6710 *
6711 * // Create a class inheriting from OO.ui.Tool
6712 * function PictureTool() {
6713 * PictureTool.super.apply( this, arguments );
6714 * };
6715 * OO.inheritClass( PictureTool, OO.ui.Tool );
6716 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6717 * // of 'icon' and 'title' (displayed icon and text).
6718 * PictureTool.static.name = 'picture';
6719 * PictureTool.static.icon = 'picture';
6720 * PictureTool.static.title = 'Insert picture';
6721 * // Defines the action that will happen when this tool is selected (clicked).
6722 * PictureTool.prototype.onSelect = function () {
6723 * $area.text( 'Picture tool clicked!' );
6724 * this.setActive( false );
6725 * };
6726 * // The toolbar can be synchronized with the state of some external stuff, like a text
6727 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
6728 * // when the text cursor was inside bolded text). Here we simply disable this feature.
6729 * PictureTool.prototype.onUpdateState = function () {
6730 * this.setActive( false );
6731 * };
6732 * // Make this tool available in our toolFactory and thus our toolbar
6733 * toolFactory.register( PictureTool );
6734 *
6735 * // Register two more tools, nothing interesting here
6736 * function SettingsTool() {
6737 * SettingsTool.super.apply( this, arguments );
6738 * };
6739 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6740 * SettingsTool.static.name = 'settings';
6741 * SettingsTool.static.icon = 'settings';
6742 * SettingsTool.static.title = 'Change settings';
6743 * SettingsTool.prototype.onSelect = function () {
6744 * $area.text( 'Settings tool clicked!' );
6745 * this.setActive( false );
6746 * };
6747 * SettingsTool.prototype.onUpdateState = function () {
6748 * this.setActive( false );
6749 * };
6750 * toolFactory.register( SettingsTool );
6751 *
6752 * // Register two more tools, nothing interesting here
6753 * function StuffTool() {
6754 * StuffTool.super.apply( this, arguments );
6755 * };
6756 * OO.inheritClass( StuffTool, OO.ui.Tool );
6757 * StuffTool.static.name = 'stuff';
6758 * StuffTool.static.icon = 'ellipsis';
6759 * StuffTool.static.title = 'More stuff';
6760 * StuffTool.prototype.onSelect = function () {
6761 * $area.text( 'More stuff tool clicked!' );
6762 * this.setActive( false );
6763 * };
6764 * StuffTool.prototype.onUpdateState = function () {
6765 * this.setActive( false );
6766 * };
6767 * toolFactory.register( StuffTool );
6768 *
6769 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6770 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
6771 * function HelpTool( toolGroup, config ) {
6772 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6773 * padded: true,
6774 * label: 'Help',
6775 * head: true
6776 * } }, config ) );
6777 * this.popup.$body.append( '<p>I am helpful!</p>' );
6778 * };
6779 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6780 * HelpTool.static.name = 'help';
6781 * HelpTool.static.icon = 'help';
6782 * HelpTool.static.title = 'Help';
6783 * toolFactory.register( HelpTool );
6784 *
6785 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6786 * // used once (but not all defined tools must be used).
6787 * toolbar.setup( [
6788 * {
6789 * // 'bar' tool groups display tools' icons only, side-by-side.
6790 * type: 'bar',
6791 * include: [ 'picture', 'help' ]
6792 * },
6793 * {
6794 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6795 * type: 'list',
6796 * indicator: 'down',
6797 * label: 'More',
6798 * include: [ 'settings', 'stuff' ]
6799 * }
6800 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6801 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here.
6802 * ] );
6803 *
6804 * // Create some UI around the toolbar and place it in the document
6805 * var frame = new OO.ui.PanelLayout( {
6806 * expanded: false,
6807 * framed: true
6808 * } );
6809 * var contentFrame = new OO.ui.PanelLayout( {
6810 * expanded: false,
6811 * padded: true
6812 * } );
6813 * frame.$element.append(
6814 * toolbar.$element,
6815 * contentFrame.$element.append( $area )
6816 * );
6817 * $( 'body' ).append( frame.$element );
6818 *
6819 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6820 * // document.
6821 * toolbar.initialize();
6822 * toolbar.emit( 'updateState' );
6823 *
6824 * @class
6825 * @extends OO.ui.Element
6826 * @mixins OO.EventEmitter
6827 * @mixins OO.ui.GroupElement
6828 *
6829 * @constructor
6830 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6831 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6832 * @param {Object} [config] Configuration options
6833 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6834 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6835 */
6836 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6837 // Allow passing positional parameters inside the config object
6838 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6839 config = toolFactory;
6840 toolFactory = config.toolFactory;
6841 toolGroupFactory = config.toolGroupFactory;
6842 }
6843
6844 // Configuration initialization
6845 config = config || {};
6846
6847 // Parent constructor
6848 OO.ui.Toolbar.super.call( this, config );
6849
6850 // Mixin constructors
6851 OO.EventEmitter.call( this );
6852 OO.ui.GroupElement.call( this, config );
6853
6854 // Properties
6855 this.toolFactory = toolFactory;
6856 this.toolGroupFactory = toolGroupFactory;
6857 this.groups = [];
6858 this.tools = {};
6859 this.$bar = $( '<div>' );
6860 this.$actions = $( '<div>' );
6861 this.initialized = false;
6862 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6863
6864 // Events
6865 this.$element
6866 .add( this.$bar ).add( this.$group ).add( this.$actions )
6867 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
6868
6869 // Initialization
6870 this.$group.addClass( 'oo-ui-toolbar-tools' );
6871 if ( config.actions ) {
6872 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6873 }
6874 this.$bar
6875 .addClass( 'oo-ui-toolbar-bar' )
6876 .append( this.$group, '<div style="clear:both"></div>' );
6877 if ( config.shadow ) {
6878 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6879 }
6880 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6881 };
6882
6883 /* Setup */
6884
6885 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6886 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6887 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6888
6889 /* Methods */
6890
6891 /**
6892 * Get the tool factory.
6893 *
6894 * @return {OO.ui.ToolFactory} Tool factory
6895 */
6896 OO.ui.Toolbar.prototype.getToolFactory = function () {
6897 return this.toolFactory;
6898 };
6899
6900 /**
6901 * Get the tool group factory.
6902 *
6903 * @return {OO.Factory} Tool group factory
6904 */
6905 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6906 return this.toolGroupFactory;
6907 };
6908
6909 /**
6910 * Handles mouse down events.
6911 *
6912 * @param {jQuery.Event} e Mouse down event
6913 */
6914 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6915 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6916 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6917 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6918 return false;
6919 }
6920 };
6921
6922 /**
6923 * Handle window resize event.
6924 *
6925 * @private
6926 * @param {jQuery.Event} e Window resize event
6927 */
6928 OO.ui.Toolbar.prototype.onWindowResize = function () {
6929 this.$element.toggleClass(
6930 'oo-ui-toolbar-narrow',
6931 this.$bar.width() <= this.narrowThreshold
6932 );
6933 };
6934
6935 /**
6936 * Sets up handles and preloads required information for the toolbar to work.
6937 * This must be called after it is attached to a visible document and before doing anything else.
6938 */
6939 OO.ui.Toolbar.prototype.initialize = function () {
6940 this.initialized = true;
6941 this.narrowThreshold = this.$group.width() + this.$actions.width();
6942 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
6943 this.onWindowResize();
6944 };
6945
6946 /**
6947 * Setup toolbar.
6948 *
6949 * Tools can be specified in the following ways:
6950 *
6951 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6952 * - All tools in a group: `{ group: 'group-name' }`
6953 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6954 *
6955 * @param {Object.<string,Array>} groups List of tool group configurations
6956 * @param {Array|string} [groups.include] Tools to include
6957 * @param {Array|string} [groups.exclude] Tools to exclude
6958 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6959 * @param {Array|string} [groups.demote] Tools to demote to the end
6960 */
6961 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6962 var i, len, type, group,
6963 items = [],
6964 defaultType = 'bar';
6965
6966 // Cleanup previous groups
6967 this.reset();
6968
6969 // Build out new groups
6970 for ( i = 0, len = groups.length; i < len; i++ ) {
6971 group = groups[ i ];
6972 if ( group.include === '*' ) {
6973 // Apply defaults to catch-all groups
6974 if ( group.type === undefined ) {
6975 group.type = 'list';
6976 }
6977 if ( group.label === undefined ) {
6978 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6979 }
6980 }
6981 // Check type has been registered
6982 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6983 items.push(
6984 this.getToolGroupFactory().create( type, this, group )
6985 );
6986 }
6987 this.addItems( items );
6988 };
6989
6990 /**
6991 * Remove all tools and groups from the toolbar.
6992 */
6993 OO.ui.Toolbar.prototype.reset = function () {
6994 var i, len;
6995
6996 this.groups = [];
6997 this.tools = {};
6998 for ( i = 0, len = this.items.length; i < len; i++ ) {
6999 this.items[ i ].destroy();
7000 }
7001 this.clearItems();
7002 };
7003
7004 /**
7005 * Destroys toolbar, removing event handlers and DOM elements.
7006 *
7007 * Call this whenever you are done using a toolbar.
7008 */
7009 OO.ui.Toolbar.prototype.destroy = function () {
7010 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7011 this.reset();
7012 this.$element.remove();
7013 };
7014
7015 /**
7016 * Check if tool has not been used yet.
7017 *
7018 * @param {string} name Symbolic name of tool
7019 * @return {boolean} Tool is available
7020 */
7021 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7022 return !this.tools[ name ];
7023 };
7024
7025 /**
7026 * Prevent tool from being used again.
7027 *
7028 * @param {OO.ui.Tool} tool Tool to reserve
7029 */
7030 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7031 this.tools[ tool.getName() ] = tool;
7032 };
7033
7034 /**
7035 * Allow tool to be used again.
7036 *
7037 * @param {OO.ui.Tool} tool Tool to release
7038 */
7039 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7040 delete this.tools[ tool.getName() ];
7041 };
7042
7043 /**
7044 * Get accelerator label for tool.
7045 *
7046 * This is a stub that should be overridden to provide access to accelerator information.
7047 *
7048 * @param {string} name Symbolic name of tool
7049 * @return {string|undefined} Tool accelerator label if available
7050 */
7051 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7052 return undefined;
7053 };
7054
7055 /**
7056 * Collection of tools.
7057 *
7058 * Tools can be specified in the following ways:
7059 *
7060 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7061 * - All tools in a group: `{ group: 'group-name' }`
7062 * - All tools: `'*'`
7063 *
7064 * @abstract
7065 * @class
7066 * @extends OO.ui.Widget
7067 * @mixins OO.ui.GroupElement
7068 *
7069 * @constructor
7070 * @param {OO.ui.Toolbar} toolbar
7071 * @param {Object} [config] Configuration options
7072 * @cfg {Array|string} [include=[]] List of tools to include
7073 * @cfg {Array|string} [exclude=[]] List of tools to exclude
7074 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
7075 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
7076 */
7077 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7078 // Allow passing positional parameters inside the config object
7079 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7080 config = toolbar;
7081 toolbar = config.toolbar;
7082 }
7083
7084 // Configuration initialization
7085 config = config || {};
7086
7087 // Parent constructor
7088 OO.ui.ToolGroup.super.call( this, config );
7089
7090 // Mixin constructors
7091 OO.ui.GroupElement.call( this, config );
7092
7093 // Properties
7094 this.toolbar = toolbar;
7095 this.tools = {};
7096 this.pressed = null;
7097 this.autoDisabled = false;
7098 this.include = config.include || [];
7099 this.exclude = config.exclude || [];
7100 this.promote = config.promote || [];
7101 this.demote = config.demote || [];
7102 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7103
7104 // Events
7105 this.$element.on( {
7106 mousedown: this.onMouseKeyDown.bind( this ),
7107 mouseup: this.onMouseKeyUp.bind( this ),
7108 keydown: this.onMouseKeyDown.bind( this ),
7109 keyup: this.onMouseKeyUp.bind( this ),
7110 focus: this.onMouseOverFocus.bind( this ),
7111 blur: this.onMouseOutBlur.bind( this ),
7112 mouseover: this.onMouseOverFocus.bind( this ),
7113 mouseout: this.onMouseOutBlur.bind( this )
7114 } );
7115 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7116 this.aggregate( { disable: 'itemDisable' } );
7117 this.connect( this, { itemDisable: 'updateDisabled' } );
7118
7119 // Initialization
7120 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7121 this.$element
7122 .addClass( 'oo-ui-toolGroup' )
7123 .append( this.$group );
7124 this.populate();
7125 };
7126
7127 /* Setup */
7128
7129 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7130 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
7131
7132 /* Events */
7133
7134 /**
7135 * @event update
7136 */
7137
7138 /* Static Properties */
7139
7140 /**
7141 * Show labels in tooltips.
7142 *
7143 * @static
7144 * @inheritable
7145 * @property {boolean}
7146 */
7147 OO.ui.ToolGroup.static.titleTooltips = false;
7148
7149 /**
7150 * Show acceleration labels in tooltips.
7151 *
7152 * @static
7153 * @inheritable
7154 * @property {boolean}
7155 */
7156 OO.ui.ToolGroup.static.accelTooltips = false;
7157
7158 /**
7159 * Automatically disable the toolgroup when all tools are disabled
7160 *
7161 * @static
7162 * @inheritable
7163 * @property {boolean}
7164 */
7165 OO.ui.ToolGroup.static.autoDisable = true;
7166
7167 /* Methods */
7168
7169 /**
7170 * @inheritdoc
7171 */
7172 OO.ui.ToolGroup.prototype.isDisabled = function () {
7173 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
7174 };
7175
7176 /**
7177 * @inheritdoc
7178 */
7179 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7180 var i, item, allDisabled = true;
7181
7182 if ( this.constructor.static.autoDisable ) {
7183 for ( i = this.items.length - 1; i >= 0; i-- ) {
7184 item = this.items[ i ];
7185 if ( !item.isDisabled() ) {
7186 allDisabled = false;
7187 break;
7188 }
7189 }
7190 this.autoDisabled = allDisabled;
7191 }
7192 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
7193 };
7194
7195 /**
7196 * Handle mouse down and key down events.
7197 *
7198 * @param {jQuery.Event} e Mouse down or key down event
7199 */
7200 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7201 if (
7202 !this.isDisabled() &&
7203 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7204 ) {
7205 this.pressed = this.getTargetTool( e );
7206 if ( this.pressed ) {
7207 this.pressed.setActive( true );
7208 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
7209 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
7210 }
7211 return false;
7212 }
7213 };
7214
7215 /**
7216 * Handle captured mouse up and key up events.
7217 *
7218 * @param {Event} e Mouse up or key up event
7219 */
7220 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7221 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
7222 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
7223 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7224 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7225 this.onMouseKeyUp( e );
7226 };
7227
7228 /**
7229 * Handle mouse up and key up events.
7230 *
7231 * @param {jQuery.Event} e Mouse up or key up event
7232 */
7233 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7234 var tool = this.getTargetTool( e );
7235
7236 if (
7237 !this.isDisabled() && this.pressed && this.pressed === tool &&
7238 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7239 ) {
7240 this.pressed.onSelect();
7241 this.pressed = null;
7242 return false;
7243 }
7244
7245 this.pressed = null;
7246 };
7247
7248 /**
7249 * Handle mouse over and focus events.
7250 *
7251 * @param {jQuery.Event} e Mouse over or focus event
7252 */
7253 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7254 var tool = this.getTargetTool( e );
7255
7256 if ( this.pressed && this.pressed === tool ) {
7257 this.pressed.setActive( true );
7258 }
7259 };
7260
7261 /**
7262 * Handle mouse out and blur events.
7263 *
7264 * @param {jQuery.Event} e Mouse out or blur event
7265 */
7266 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7267 var tool = this.getTargetTool( e );
7268
7269 if ( this.pressed && this.pressed === tool ) {
7270 this.pressed.setActive( false );
7271 }
7272 };
7273
7274 /**
7275 * Get the closest tool to a jQuery.Event.
7276 *
7277 * Only tool links are considered, which prevents other elements in the tool such as popups from
7278 * triggering tool group interactions.
7279 *
7280 * @private
7281 * @param {jQuery.Event} e
7282 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7283 */
7284 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7285 var tool,
7286 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7287
7288 if ( $item.length ) {
7289 tool = $item.parent().data( 'oo-ui-tool' );
7290 }
7291
7292 return tool && !tool.isDisabled() ? tool : null;
7293 };
7294
7295 /**
7296 * Handle tool registry register events.
7297 *
7298 * If a tool is registered after the group is created, we must repopulate the list to account for:
7299 *
7300 * - a tool being added that may be included
7301 * - a tool already included being overridden
7302 *
7303 * @param {string} name Symbolic name of tool
7304 */
7305 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7306 this.populate();
7307 };
7308
7309 /**
7310 * Get the toolbar this group is in.
7311 *
7312 * @return {OO.ui.Toolbar} Toolbar of group
7313 */
7314 OO.ui.ToolGroup.prototype.getToolbar = function () {
7315 return this.toolbar;
7316 };
7317
7318 /**
7319 * Add and remove tools based on configuration.
7320 */
7321 OO.ui.ToolGroup.prototype.populate = function () {
7322 var i, len, name, tool,
7323 toolFactory = this.toolbar.getToolFactory(),
7324 names = {},
7325 add = [],
7326 remove = [],
7327 list = this.toolbar.getToolFactory().getTools(
7328 this.include, this.exclude, this.promote, this.demote
7329 );
7330
7331 // Build a list of needed tools
7332 for ( i = 0, len = list.length; i < len; i++ ) {
7333 name = list[ i ];
7334 if (
7335 // Tool exists
7336 toolFactory.lookup( name ) &&
7337 // Tool is available or is already in this group
7338 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7339 ) {
7340 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7341 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7342 this.toolbar.tools[ name ] = true;
7343 tool = this.tools[ name ];
7344 if ( !tool ) {
7345 // Auto-initialize tools on first use
7346 this.tools[ name ] = tool = toolFactory.create( name, this );
7347 tool.updateTitle();
7348 }
7349 this.toolbar.reserveTool( tool );
7350 add.push( tool );
7351 names[ name ] = true;
7352 }
7353 }
7354 // Remove tools that are no longer needed
7355 for ( name in this.tools ) {
7356 if ( !names[ name ] ) {
7357 this.tools[ name ].destroy();
7358 this.toolbar.releaseTool( this.tools[ name ] );
7359 remove.push( this.tools[ name ] );
7360 delete this.tools[ name ];
7361 }
7362 }
7363 if ( remove.length ) {
7364 this.removeItems( remove );
7365 }
7366 // Update emptiness state
7367 if ( add.length ) {
7368 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7369 } else {
7370 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7371 }
7372 // Re-add tools (moving existing ones to new locations)
7373 this.addItems( add );
7374 // Disabled state may depend on items
7375 this.updateDisabled();
7376 };
7377
7378 /**
7379 * Destroy tool group.
7380 */
7381 OO.ui.ToolGroup.prototype.destroy = function () {
7382 var name;
7383
7384 this.clearItems();
7385 this.toolbar.getToolFactory().disconnect( this );
7386 for ( name in this.tools ) {
7387 this.toolbar.releaseTool( this.tools[ name ] );
7388 this.tools[ name ].disconnect( this ).destroy();
7389 delete this.tools[ name ];
7390 }
7391 this.$element.remove();
7392 };
7393
7394 /**
7395 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7396 * consists of a header that contains the dialog title, a body with the message, and a footer that
7397 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7398 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7399 *
7400 * There are two basic types of message dialogs, confirmation and alert:
7401 *
7402 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7403 * more details about the consequences.
7404 * - **alert**: the dialog title describes which event occurred and the message provides more information
7405 * about why the event occurred.
7406 *
7407 * The MessageDialog class specifies two actions: ‘accept’, the primary
7408 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7409 * passing along the selected action.
7410 *
7411 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7412 *
7413 * @example
7414 * // Example: Creating and opening a message dialog window.
7415 * var messageDialog = new OO.ui.MessageDialog();
7416 *
7417 * // Create and append a window manager.
7418 * var windowManager = new OO.ui.WindowManager();
7419 * $( 'body' ).append( windowManager.$element );
7420 * windowManager.addWindows( [ messageDialog ] );
7421 * // Open the window.
7422 * windowManager.openWindow( messageDialog, {
7423 * title: 'Basic message dialog',
7424 * message: 'This is the message'
7425 * } );
7426 *
7427 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7428 *
7429 * @class
7430 * @extends OO.ui.Dialog
7431 *
7432 * @constructor
7433 * @param {Object} [config] Configuration options
7434 */
7435 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7436 // Parent constructor
7437 OO.ui.MessageDialog.super.call( this, config );
7438
7439 // Properties
7440 this.verticalActionLayout = null;
7441
7442 // Initialization
7443 this.$element.addClass( 'oo-ui-messageDialog' );
7444 };
7445
7446 /* Inheritance */
7447
7448 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7449
7450 /* Static Properties */
7451
7452 OO.ui.MessageDialog.static.name = 'message';
7453
7454 OO.ui.MessageDialog.static.size = 'small';
7455
7456 OO.ui.MessageDialog.static.verbose = false;
7457
7458 /**
7459 * Dialog title.
7460 *
7461 * The title of a confirmation dialog describes what a progressive action will do. The
7462 * title of an alert dialog describes which event occurred.
7463 *
7464 * @static
7465 * @inheritable
7466 * @property {jQuery|string|Function|null}
7467 */
7468 OO.ui.MessageDialog.static.title = null;
7469
7470 /**
7471 * The message displayed in the dialog body.
7472 *
7473 * A confirmation message describes the consequences of a progressive action. An alert
7474 * message describes why an event occurred.
7475 *
7476 * @static
7477 * @inheritable
7478 * @property {jQuery|string|Function|null}
7479 */
7480 OO.ui.MessageDialog.static.message = null;
7481
7482 OO.ui.MessageDialog.static.actions = [
7483 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7484 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7485 ];
7486
7487 /* Methods */
7488
7489 /**
7490 * @inheritdoc
7491 */
7492 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7493 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7494
7495 // Events
7496 this.manager.connect( this, {
7497 resize: 'onResize'
7498 } );
7499
7500 return this;
7501 };
7502
7503 /**
7504 * @inheritdoc
7505 */
7506 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7507 this.fitActions();
7508 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7509 };
7510
7511 /**
7512 * Handle window resized events.
7513 *
7514 * @private
7515 */
7516 OO.ui.MessageDialog.prototype.onResize = function () {
7517 var dialog = this;
7518 dialog.fitActions();
7519 // Wait for CSS transition to finish and do it again :(
7520 setTimeout( function () {
7521 dialog.fitActions();
7522 }, 300 );
7523 };
7524
7525 /**
7526 * Toggle action layout between vertical and horizontal.
7527 *
7528 *
7529 * @private
7530 * @param {boolean} [value] Layout actions vertically, omit to toggle
7531 * @chainable
7532 */
7533 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7534 value = value === undefined ? !this.verticalActionLayout : !!value;
7535
7536 if ( value !== this.verticalActionLayout ) {
7537 this.verticalActionLayout = value;
7538 this.$actions
7539 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7540 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7541 }
7542
7543 return this;
7544 };
7545
7546 /**
7547 * @inheritdoc
7548 */
7549 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7550 if ( action ) {
7551 return new OO.ui.Process( function () {
7552 this.close( { action: action } );
7553 }, this );
7554 }
7555 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7556 };
7557
7558 /**
7559 * @inheritdoc
7560 *
7561 * @param {Object} [data] Dialog opening data
7562 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7563 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7564 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7565 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7566 * action item
7567 */
7568 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7569 data = data || {};
7570
7571 // Parent method
7572 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7573 .next( function () {
7574 this.title.setLabel(
7575 data.title !== undefined ? data.title : this.constructor.static.title
7576 );
7577 this.message.setLabel(
7578 data.message !== undefined ? data.message : this.constructor.static.message
7579 );
7580 this.message.$element.toggleClass(
7581 'oo-ui-messageDialog-message-verbose',
7582 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7583 );
7584 }, this );
7585 };
7586
7587 /**
7588 * @inheritdoc
7589 */
7590 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7591 var bodyHeight, oldOverflow,
7592 $scrollable = this.container.$element;
7593
7594 oldOverflow = $scrollable[ 0 ].style.overflow;
7595 $scrollable[ 0 ].style.overflow = 'hidden';
7596
7597 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7598
7599 bodyHeight = this.text.$element.outerHeight( true );
7600 $scrollable[ 0 ].style.overflow = oldOverflow;
7601
7602 return bodyHeight;
7603 };
7604
7605 /**
7606 * @inheritdoc
7607 */
7608 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7609 var $scrollable = this.container.$element;
7610 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7611
7612 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7613 // Need to do it after transition completes (250ms), add 50ms just in case.
7614 setTimeout( function () {
7615 var oldOverflow = $scrollable[ 0 ].style.overflow;
7616 $scrollable[ 0 ].style.overflow = 'hidden';
7617
7618 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7619
7620 $scrollable[ 0 ].style.overflow = oldOverflow;
7621 }, 300 );
7622
7623 return this;
7624 };
7625
7626 /**
7627 * @inheritdoc
7628 */
7629 OO.ui.MessageDialog.prototype.initialize = function () {
7630 // Parent method
7631 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7632
7633 // Properties
7634 this.$actions = $( '<div>' );
7635 this.container = new OO.ui.PanelLayout( {
7636 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7637 } );
7638 this.text = new OO.ui.PanelLayout( {
7639 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7640 } );
7641 this.message = new OO.ui.LabelWidget( {
7642 classes: [ 'oo-ui-messageDialog-message' ]
7643 } );
7644
7645 // Initialization
7646 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7647 this.$content.addClass( 'oo-ui-messageDialog-content' );
7648 this.container.$element.append( this.text.$element );
7649 this.text.$element.append( this.title.$element, this.message.$element );
7650 this.$body.append( this.container.$element );
7651 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7652 this.$foot.append( this.$actions );
7653 };
7654
7655 /**
7656 * @inheritdoc
7657 */
7658 OO.ui.MessageDialog.prototype.attachActions = function () {
7659 var i, len, other, special, others;
7660
7661 // Parent method
7662 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7663
7664 special = this.actions.getSpecial();
7665 others = this.actions.getOthers();
7666 if ( special.safe ) {
7667 this.$actions.append( special.safe.$element );
7668 special.safe.toggleFramed( false );
7669 }
7670 if ( others.length ) {
7671 for ( i = 0, len = others.length; i < len; i++ ) {
7672 other = others[ i ];
7673 this.$actions.append( other.$element );
7674 other.toggleFramed( false );
7675 }
7676 }
7677 if ( special.primary ) {
7678 this.$actions.append( special.primary.$element );
7679 special.primary.toggleFramed( false );
7680 }
7681
7682 if ( !this.isOpening() ) {
7683 // If the dialog is currently opening, this will be called automatically soon.
7684 // This also calls #fitActions.
7685 this.updateSize();
7686 }
7687 };
7688
7689 /**
7690 * Fit action actions into columns or rows.
7691 *
7692 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7693 *
7694 * @private
7695 */
7696 OO.ui.MessageDialog.prototype.fitActions = function () {
7697 var i, len, action,
7698 previous = this.verticalActionLayout,
7699 actions = this.actions.get();
7700
7701 // Detect clipping
7702 this.toggleVerticalActionLayout( false );
7703 for ( i = 0, len = actions.length; i < len; i++ ) {
7704 action = actions[ i ];
7705 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7706 this.toggleVerticalActionLayout( true );
7707 break;
7708 }
7709 }
7710
7711 // Move the body out of the way of the foot
7712 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7713
7714 if ( this.verticalActionLayout !== previous ) {
7715 // We changed the layout, window height might need to be updated.
7716 this.updateSize();
7717 }
7718 };
7719
7720 /**
7721 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7722 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7723 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7724 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7725 * required for each process.
7726 *
7727 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7728 * processes with an animation. The header contains the dialog title as well as
7729 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7730 * a ‘primary’ action on the right (e.g., ‘Done’).
7731 *
7732 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7733 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7734 *
7735 * @example
7736 * // Example: Creating and opening a process dialog window.
7737 * function MyProcessDialog( config ) {
7738 * MyProcessDialog.super.call( this, config );
7739 * }
7740 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7741 *
7742 * MyProcessDialog.static.title = 'Process dialog';
7743 * MyProcessDialog.static.actions = [
7744 * { action: 'save', label: 'Done', flags: 'primary' },
7745 * { label: 'Cancel', flags: 'safe' }
7746 * ];
7747 *
7748 * MyProcessDialog.prototype.initialize = function () {
7749 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7750 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7751 * 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>' );
7752 * this.$body.append( this.content.$element );
7753 * };
7754 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7755 * var dialog = this;
7756 * if ( action ) {
7757 * return new OO.ui.Process( function () {
7758 * dialog.close( { action: action } );
7759 * } );
7760 * }
7761 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7762 * };
7763 *
7764 * var windowManager = new OO.ui.WindowManager();
7765 * $( 'body' ).append( windowManager.$element );
7766 *
7767 * var dialog = new MyProcessDialog();
7768 * windowManager.addWindows( [ dialog ] );
7769 * windowManager.openWindow( dialog );
7770 *
7771 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7772 *
7773 * @abstract
7774 * @class
7775 * @extends OO.ui.Dialog
7776 *
7777 * @constructor
7778 * @param {Object} [config] Configuration options
7779 */
7780 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7781 // Parent constructor
7782 OO.ui.ProcessDialog.super.call( this, config );
7783
7784 // Initialization
7785 this.$element.addClass( 'oo-ui-processDialog' );
7786 };
7787
7788 /* Setup */
7789
7790 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7791
7792 /* Methods */
7793
7794 /**
7795 * Handle dismiss button click events.
7796 *
7797 * Hides errors.
7798 *
7799 * @private
7800 */
7801 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7802 this.hideErrors();
7803 };
7804
7805 /**
7806 * Handle retry button click events.
7807 *
7808 * Hides errors and then tries again.
7809 *
7810 * @private
7811 */
7812 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7813 this.hideErrors();
7814 this.executeAction( this.currentAction );
7815 };
7816
7817 /**
7818 * @inheritdoc
7819 */
7820 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7821 if ( this.actions.isSpecial( action ) ) {
7822 this.fitLabel();
7823 }
7824 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7825 };
7826
7827 /**
7828 * @inheritdoc
7829 */
7830 OO.ui.ProcessDialog.prototype.initialize = function () {
7831 // Parent method
7832 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7833
7834 // Properties
7835 this.$navigation = $( '<div>' );
7836 this.$location = $( '<div>' );
7837 this.$safeActions = $( '<div>' );
7838 this.$primaryActions = $( '<div>' );
7839 this.$otherActions = $( '<div>' );
7840 this.dismissButton = new OO.ui.ButtonWidget( {
7841 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7842 } );
7843 this.retryButton = new OO.ui.ButtonWidget();
7844 this.$errors = $( '<div>' );
7845 this.$errorsTitle = $( '<div>' );
7846
7847 // Events
7848 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7849 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7850
7851 // Initialization
7852 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7853 this.$location
7854 .append( this.title.$element )
7855 .addClass( 'oo-ui-processDialog-location' );
7856 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7857 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7858 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7859 this.$errorsTitle
7860 .addClass( 'oo-ui-processDialog-errors-title' )
7861 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7862 this.$errors
7863 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7864 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7865 this.$content
7866 .addClass( 'oo-ui-processDialog-content' )
7867 .append( this.$errors );
7868 this.$navigation
7869 .addClass( 'oo-ui-processDialog-navigation' )
7870 .append( this.$safeActions, this.$location, this.$primaryActions );
7871 this.$head.append( this.$navigation );
7872 this.$foot.append( this.$otherActions );
7873 };
7874
7875 /**
7876 * @inheritdoc
7877 */
7878 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
7879 var i, len, widgets = [];
7880 for ( i = 0, len = actions.length; i < len; i++ ) {
7881 widgets.push(
7882 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
7883 );
7884 }
7885 return widgets;
7886 };
7887
7888 /**
7889 * @inheritdoc
7890 */
7891 OO.ui.ProcessDialog.prototype.attachActions = function () {
7892 var i, len, other, special, others;
7893
7894 // Parent method
7895 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7896
7897 special = this.actions.getSpecial();
7898 others = this.actions.getOthers();
7899 if ( special.primary ) {
7900 this.$primaryActions.append( special.primary.$element );
7901 }
7902 for ( i = 0, len = others.length; i < len; i++ ) {
7903 other = others[ i ];
7904 this.$otherActions.append( other.$element );
7905 }
7906 if ( special.safe ) {
7907 this.$safeActions.append( special.safe.$element );
7908 }
7909
7910 this.fitLabel();
7911 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7912 };
7913
7914 /**
7915 * @inheritdoc
7916 */
7917 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7918 var process = this;
7919 return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7920 .fail( function ( errors ) {
7921 process.showErrors( errors || [] );
7922 } );
7923 };
7924
7925 /**
7926 * Fit label between actions.
7927 *
7928 * @private
7929 * @chainable
7930 */
7931 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7932 var width = Math.max(
7933 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7934 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7935 );
7936 this.$location.css( { paddingLeft: width, paddingRight: width } );
7937
7938 return this;
7939 };
7940
7941 /**
7942 * Handle errors that occurred during accept or reject processes.
7943 *
7944 * @private
7945 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7946 */
7947 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7948 var i, len, $item, actions,
7949 items = [],
7950 abilities = {},
7951 recoverable = true,
7952 warning = false;
7953
7954 if ( errors instanceof OO.ui.Error ) {
7955 errors = [ errors ];
7956 }
7957
7958 for ( i = 0, len = errors.length; i < len; i++ ) {
7959 if ( !errors[ i ].isRecoverable() ) {
7960 recoverable = false;
7961 }
7962 if ( errors[ i ].isWarning() ) {
7963 warning = true;
7964 }
7965 $item = $( '<div>' )
7966 .addClass( 'oo-ui-processDialog-error' )
7967 .append( errors[ i ].getMessage() );
7968 items.push( $item[ 0 ] );
7969 }
7970 this.$errorItems = $( items );
7971 if ( recoverable ) {
7972 abilities[this.currentAction] = true;
7973 // Copy the flags from the first matching action
7974 actions = this.actions.get( { actions: this.currentAction } );
7975 if ( actions.length ) {
7976 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
7977 }
7978 } else {
7979 abilities[this.currentAction] = false;
7980 this.actions.setAbilities( abilities );
7981 }
7982 if ( warning ) {
7983 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7984 } else {
7985 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7986 }
7987 this.retryButton.toggle( recoverable );
7988 this.$errorsTitle.after( this.$errorItems );
7989 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7990 };
7991
7992 /**
7993 * Hide errors.
7994 *
7995 * @private
7996 */
7997 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7998 this.$errors.addClass( 'oo-ui-element-hidden' );
7999 if ( this.$errorItems ) {
8000 this.$errorItems.remove();
8001 this.$errorItems = null;
8002 }
8003 };
8004
8005 /**
8006 * @inheritdoc
8007 */
8008 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8009 // Parent method
8010 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
8011 .first( function () {
8012 // Make sure to hide errors
8013 this.hideErrors();
8014 }, this );
8015 };
8016
8017 /**
8018 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8019 * which is a widget that is specified by reference before any optional configuration settings.
8020 *
8021 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8022 *
8023 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8024 * A left-alignment is used for forms with many fields.
8025 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8026 * A right-alignment is used for long but familiar forms which users tab through,
8027 * verifying the current field with a quick glance at the label.
8028 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8029 * that users fill out from top to bottom.
8030 * - **inline**: The label is placed after the field-widget and aligned to the left.
8031 * An inline-alignment is best used with checkboxes or radio buttons.
8032 *
8033 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8034 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8035 *
8036 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8037 * @class
8038 * @extends OO.ui.Layout
8039 * @mixins OO.ui.LabelElement
8040 *
8041 * @constructor
8042 * @param {OO.ui.Widget} fieldWidget Field widget
8043 * @param {Object} [config] Configuration options
8044 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8045 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8046 * in the upper-right corner of the rendered field.
8047 */
8048 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8049 // Allow passing positional parameters inside the config object
8050 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8051 config = fieldWidget;
8052 fieldWidget = config.fieldWidget;
8053 }
8054
8055 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
8056
8057 // Configuration initialization
8058 config = $.extend( { align: 'left' }, config );
8059
8060 // Parent constructor
8061 OO.ui.FieldLayout.super.call( this, config );
8062
8063 // Mixin constructors
8064 OO.ui.LabelElement.call( this, config );
8065
8066 // Properties
8067 this.fieldWidget = fieldWidget;
8068 this.$field = $( '<div>' );
8069 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8070 this.align = null;
8071 if ( config.help ) {
8072 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8073 classes: [ 'oo-ui-fieldLayout-help' ],
8074 framed: false,
8075 icon: 'info'
8076 } );
8077
8078 this.popupButtonWidget.getPopup().$body.append(
8079 $( '<div>' )
8080 .text( config.help )
8081 .addClass( 'oo-ui-fieldLayout-help-content' )
8082 );
8083 this.$help = this.popupButtonWidget.$element;
8084 } else {
8085 this.$help = $( [] );
8086 }
8087
8088 // Events
8089 if ( hasInputWidget ) {
8090 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8091 }
8092 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8093
8094 // Initialization
8095 this.$element
8096 .addClass( 'oo-ui-fieldLayout' )
8097 .append( this.$help, this.$body );
8098 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8099 this.$field
8100 .addClass( 'oo-ui-fieldLayout-field' )
8101 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8102 .append( this.fieldWidget.$element );
8103
8104 this.setAlignment( config.align );
8105 };
8106
8107 /* Setup */
8108
8109 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8110 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
8111
8112 /* Methods */
8113
8114 /**
8115 * Handle field disable events.
8116 *
8117 * @private
8118 * @param {boolean} value Field is disabled
8119 */
8120 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8121 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8122 };
8123
8124 /**
8125 * Handle label mouse click events.
8126 *
8127 * @private
8128 * @param {jQuery.Event} e Mouse click event
8129 */
8130 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8131 this.fieldWidget.simulateLabelClick();
8132 return false;
8133 };
8134
8135 /**
8136 * Get the widget contained by the field.
8137 *
8138 * @return {OO.ui.Widget} Field widget
8139 */
8140 OO.ui.FieldLayout.prototype.getField = function () {
8141 return this.fieldWidget;
8142 };
8143
8144 /**
8145 * Set the field alignment mode.
8146 *
8147 * @private
8148 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8149 * @chainable
8150 */
8151 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8152 if ( value !== this.align ) {
8153 // Default to 'left'
8154 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8155 value = 'left';
8156 }
8157 // Reorder elements
8158 if ( value === 'inline' ) {
8159 this.$body.append( this.$field, this.$label );
8160 } else {
8161 this.$body.append( this.$label, this.$field );
8162 }
8163 // Set classes. The following classes can be used here:
8164 // * oo-ui-fieldLayout-align-left
8165 // * oo-ui-fieldLayout-align-right
8166 // * oo-ui-fieldLayout-align-top
8167 // * oo-ui-fieldLayout-align-inline
8168 if ( this.align ) {
8169 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8170 }
8171 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8172 this.align = value;
8173 }
8174
8175 return this;
8176 };
8177
8178 /**
8179 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8180 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8181 * is required and is specified before any optional configuration settings.
8182 *
8183 * Labels can be aligned in one of four ways:
8184 *
8185 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8186 * A left-alignment is used for forms with many fields.
8187 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8188 * A right-alignment is used for long but familiar forms which users tab through,
8189 * verifying the current field with a quick glance at the label.
8190 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8191 * that users fill out from top to bottom.
8192 * - **inline**: The label is placed after the field-widget and aligned to the left.
8193 * An inline-alignment is best used with checkboxes or radio buttons.
8194 *
8195 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8196 * text is specified.
8197 *
8198 * @example
8199 * // Example of an ActionFieldLayout
8200 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8201 * new OO.ui.TextInputWidget( {
8202 * placeholder: 'Field widget'
8203 * } ),
8204 * new OO.ui.ButtonWidget( {
8205 * label: 'Button'
8206 * } ),
8207 * {
8208 * label: 'An ActionFieldLayout. This label is aligned top',
8209 * align: 'top',
8210 * help: 'This is help text'
8211 * }
8212 * );
8213 *
8214 * $( 'body' ).append( actionFieldLayout.$element );
8215 *
8216 *
8217 * @class
8218 * @extends OO.ui.FieldLayout
8219 *
8220 * @constructor
8221 * @param {OO.ui.Widget} fieldWidget Field widget
8222 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8223 * @param {Object} [config] Configuration options
8224 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8225 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8226 * upper-right corner of the rendered field.
8227 */
8228 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8229 // Allow passing positional parameters inside the config object
8230 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8231 config = fieldWidget;
8232 fieldWidget = config.fieldWidget;
8233 buttonWidget = config.buttonWidget;
8234 }
8235
8236 // Configuration initialization
8237 config = $.extend( { align: 'left' }, config );
8238
8239 // Parent constructor
8240 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
8241
8242 // Properties
8243 this.fieldWidget = fieldWidget;
8244 this.buttonWidget = buttonWidget;
8245 this.$button = $( '<div>' )
8246 .addClass( 'oo-ui-actionFieldLayout-button' )
8247 .append( this.buttonWidget.$element );
8248 this.$input = $( '<div>' )
8249 .addClass( 'oo-ui-actionFieldLayout-input' )
8250 .append( this.fieldWidget.$element );
8251 this.$field
8252 .addClass( 'oo-ui-actionFieldLayout' )
8253 .append( this.$input, this.$button );
8254 };
8255
8256 /* Setup */
8257
8258 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8259
8260 /**
8261 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8262 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8263 * configured with a label as well. For more information and examples,
8264 * please see the [OOjs UI documentation on MediaWiki][1].
8265 *
8266 * @example
8267 * // Example of a fieldset layout
8268 * var input1 = new OO.ui.TextInputWidget( {
8269 * placeholder: 'A text input field'
8270 * } );
8271 *
8272 * var input2 = new OO.ui.TextInputWidget( {
8273 * placeholder: 'A text input field'
8274 * } );
8275 *
8276 * var fieldset = new OO.ui.FieldsetLayout( {
8277 * label: 'Example of a fieldset layout'
8278 * } );
8279 *
8280 * fieldset.addItems( [
8281 * new OO.ui.FieldLayout( input1, {
8282 * label: 'Field One'
8283 * } ),
8284 * new OO.ui.FieldLayout( input2, {
8285 * label: 'Field Two'
8286 * } )
8287 * ] );
8288 * $( 'body' ).append( fieldset.$element );
8289 *
8290 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8291 *
8292 * @class
8293 * @extends OO.ui.Layout
8294 * @mixins OO.ui.IconElement
8295 * @mixins OO.ui.LabelElement
8296 * @mixins OO.ui.GroupElement
8297 *
8298 * @constructor
8299 * @param {Object} [config] Configuration options
8300 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8301 */
8302 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8303 // Configuration initialization
8304 config = config || {};
8305
8306 // Parent constructor
8307 OO.ui.FieldsetLayout.super.call( this, config );
8308
8309 // Mixin constructors
8310 OO.ui.IconElement.call( this, config );
8311 OO.ui.LabelElement.call( this, config );
8312 OO.ui.GroupElement.call( this, config );
8313
8314 if ( config.help ) {
8315 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8316 classes: [ 'oo-ui-fieldsetLayout-help' ],
8317 framed: false,
8318 icon: 'info'
8319 } );
8320
8321 this.popupButtonWidget.getPopup().$body.append(
8322 $( '<div>' )
8323 .text( config.help )
8324 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8325 );
8326 this.$help = this.popupButtonWidget.$element;
8327 } else {
8328 this.$help = $( [] );
8329 }
8330
8331 // Initialization
8332 this.$element
8333 .addClass( 'oo-ui-fieldsetLayout' )
8334 .prepend( this.$help, this.$icon, this.$label, this.$group );
8335 if ( Array.isArray( config.items ) ) {
8336 this.addItems( config.items );
8337 }
8338 };
8339
8340 /* Setup */
8341
8342 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8343 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
8344 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
8345 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
8346
8347 /**
8348 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8349 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8350 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8351 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8352 *
8353 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8354 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8355 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8356 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8357 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8358 * often have simplified APIs to match the capabilities of HTML forms.
8359 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8360 *
8361 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8362 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8363 *
8364 * @example
8365 * // Example of a form layout that wraps a fieldset layout
8366 * var input1 = new OO.ui.TextInputWidget( {
8367 * placeholder: 'Username'
8368 * } );
8369 * var input2 = new OO.ui.TextInputWidget( {
8370 * placeholder: 'Password',
8371 * type: 'password'
8372 * } );
8373 * var submit = new OO.ui.ButtonInputWidget( {
8374 * label: 'Submit'
8375 * } );
8376 *
8377 * var fieldset = new OO.ui.FieldsetLayout( {
8378 * label: 'A form layout'
8379 * } );
8380 * fieldset.addItems( [
8381 * new OO.ui.FieldLayout( input1, {
8382 * label: 'Username',
8383 * align: 'top'
8384 * } ),
8385 * new OO.ui.FieldLayout( input2, {
8386 * label: 'Password',
8387 * align: 'top'
8388 * } ),
8389 * new OO.ui.FieldLayout( submit )
8390 * ] );
8391 * var form = new OO.ui.FormLayout( {
8392 * items: [ fieldset ],
8393 * action: '/api/formhandler',
8394 * method: 'get'
8395 * } )
8396 * $( 'body' ).append( form.$element );
8397 *
8398 * @class
8399 * @extends OO.ui.Layout
8400 * @mixins OO.ui.GroupElement
8401 *
8402 * @constructor
8403 * @param {Object} [config] Configuration options
8404 * @cfg {string} [method] HTML form `method` attribute
8405 * @cfg {string} [action] HTML form `action` attribute
8406 * @cfg {string} [enctype] HTML form `enctype` attribute
8407 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8408 */
8409 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8410 // Configuration initialization
8411 config = config || {};
8412
8413 // Parent constructor
8414 OO.ui.FormLayout.super.call( this, config );
8415
8416 // Mixin constructors
8417 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8418
8419 // Events
8420 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8421
8422 // Initialization
8423 this.$element
8424 .addClass( 'oo-ui-formLayout' )
8425 .attr( {
8426 method: config.method,
8427 action: config.action,
8428 enctype: config.enctype
8429 } );
8430 if ( Array.isArray( config.items ) ) {
8431 this.addItems( config.items );
8432 }
8433 };
8434
8435 /* Setup */
8436
8437 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8438 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8439
8440 /* Events */
8441
8442 /**
8443 * A 'submit' event is emitted when the form is submitted.
8444 *
8445 * @event submit
8446 */
8447
8448 /* Static Properties */
8449
8450 OO.ui.FormLayout.static.tagName = 'form';
8451
8452 /* Methods */
8453
8454 /**
8455 * Handle form submit events.
8456 *
8457 * @private
8458 * @param {jQuery.Event} e Submit event
8459 * @fires submit
8460 */
8461 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8462 this.emit( 'submit' );
8463 return false;
8464 };
8465
8466 /**
8467 * 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)
8468 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8469 *
8470 * @example
8471 * var menuLayout = new OO.ui.MenuLayout( {
8472 * position: 'top'
8473 * } ),
8474 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8475 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8476 * select = new OO.ui.SelectWidget( {
8477 * items: [
8478 * new OO.ui.OptionWidget( {
8479 * data: 'before',
8480 * label: 'Before',
8481 * } ),
8482 * new OO.ui.OptionWidget( {
8483 * data: 'after',
8484 * label: 'After',
8485 * } ),
8486 * new OO.ui.OptionWidget( {
8487 * data: 'top',
8488 * label: 'Top',
8489 * } ),
8490 * new OO.ui.OptionWidget( {
8491 * data: 'bottom',
8492 * label: 'Bottom',
8493 * } )
8494 * ]
8495 * } ).on( 'select', function ( item ) {
8496 * menuLayout.setMenuPosition( item.getData() );
8497 * } );
8498 *
8499 * menuLayout.$menu.append(
8500 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8501 * );
8502 * menuLayout.$content.append(
8503 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8504 * );
8505 * $( 'body' ).append( menuLayout.$element );
8506 *
8507 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8508 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8509 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8510 * may be omitted.
8511 *
8512 * .oo-ui-menuLayout-menu {
8513 * height: 200px;
8514 * width: 200px;
8515 * }
8516 * .oo-ui-menuLayout-content {
8517 * top: 200px;
8518 * left: 200px;
8519 * right: 200px;
8520 * bottom: 200px;
8521 * }
8522 *
8523 * @class
8524 * @extends OO.ui.Layout
8525 *
8526 * @constructor
8527 * @param {Object} [config] Configuration options
8528 * @cfg {boolean} [showMenu=true] Show menu
8529 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8530 */
8531 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8532 // Configuration initialization
8533 config = $.extend( {
8534 showMenu: true,
8535 menuPosition: 'before'
8536 }, config );
8537
8538 // Parent constructor
8539 OO.ui.MenuLayout.super.call( this, config );
8540
8541 /**
8542 * Menu DOM node
8543 *
8544 * @property {jQuery}
8545 */
8546 this.$menu = $( '<div>' );
8547 /**
8548 * Content DOM node
8549 *
8550 * @property {jQuery}
8551 */
8552 this.$content = $( '<div>' );
8553
8554 // Initialization
8555 this.$menu
8556 .addClass( 'oo-ui-menuLayout-menu' );
8557 this.$content.addClass( 'oo-ui-menuLayout-content' );
8558 this.$element
8559 .addClass( 'oo-ui-menuLayout' )
8560 .append( this.$content, this.$menu );
8561 this.setMenuPosition( config.menuPosition );
8562 this.toggleMenu( config.showMenu );
8563 };
8564
8565 /* Setup */
8566
8567 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8568
8569 /* Methods */
8570
8571 /**
8572 * Toggle menu.
8573 *
8574 * @param {boolean} showMenu Show menu, omit to toggle
8575 * @chainable
8576 */
8577 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8578 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8579
8580 if ( this.showMenu !== showMenu ) {
8581 this.showMenu = showMenu;
8582 this.$element
8583 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
8584 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
8585 }
8586
8587 return this;
8588 };
8589
8590 /**
8591 * Check if menu is visible
8592 *
8593 * @return {boolean} Menu is visible
8594 */
8595 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8596 return this.showMenu;
8597 };
8598
8599 /**
8600 * Set menu position.
8601 *
8602 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8603 * @throws {Error} If position value is not supported
8604 * @chainable
8605 */
8606 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8607 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
8608 this.menuPosition = position;
8609 this.$element.addClass( 'oo-ui-menuLayout-' + position );
8610
8611 return this;
8612 };
8613
8614 /**
8615 * Get menu position.
8616 *
8617 * @return {string} Menu position
8618 */
8619 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8620 return this.menuPosition;
8621 };
8622
8623 /**
8624 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8625 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8626 * through the pages and select which one to display. By default, only one page is
8627 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8628 * the booklet layout automatically focuses on the first focusable element, unless the
8629 * default setting is changed. Optionally, booklets can be configured to show
8630 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8631 *
8632 * @example
8633 * // Example of a BookletLayout that contains two PageLayouts.
8634 *
8635 * function PageOneLayout( name, config ) {
8636 * PageOneLayout.super.call( this, name, config );
8637 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8638 * }
8639 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8640 * PageOneLayout.prototype.setupOutlineItem = function () {
8641 * this.outlineItem.setLabel( 'Page One' );
8642 * };
8643 *
8644 * function PageTwoLayout( name, config ) {
8645 * PageTwoLayout.super.call( this, name, config );
8646 * this.$element.append( '<p>Second page</p>' );
8647 * }
8648 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8649 * PageTwoLayout.prototype.setupOutlineItem = function () {
8650 * this.outlineItem.setLabel( 'Page Two' );
8651 * };
8652 *
8653 * var page1 = new PageOneLayout( 'one' ),
8654 * page2 = new PageTwoLayout( 'two' );
8655 *
8656 * var booklet = new OO.ui.BookletLayout( {
8657 * outlined: true
8658 * } );
8659 *
8660 * booklet.addPages ( [ page1, page2 ] );
8661 * $( 'body' ).append( booklet.$element );
8662 *
8663 * @class
8664 * @extends OO.ui.MenuLayout
8665 *
8666 * @constructor
8667 * @param {Object} [config] Configuration options
8668 * @cfg {boolean} [continuous=false] Show all pages, one after another
8669 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8670 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8671 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8672 */
8673 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8674 // Configuration initialization
8675 config = config || {};
8676
8677 // Parent constructor
8678 OO.ui.BookletLayout.super.call( this, config );
8679
8680 // Properties
8681 this.currentPageName = null;
8682 this.pages = {};
8683 this.ignoreFocus = false;
8684 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8685 this.$content.append( this.stackLayout.$element );
8686 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8687 this.outlineVisible = false;
8688 this.outlined = !!config.outlined;
8689 if ( this.outlined ) {
8690 this.editable = !!config.editable;
8691 this.outlineControlsWidget = null;
8692 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8693 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8694 this.$menu.append( this.outlinePanel.$element );
8695 this.outlineVisible = true;
8696 if ( this.editable ) {
8697 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8698 this.outlineSelectWidget
8699 );
8700 }
8701 }
8702 this.toggleMenu( this.outlined );
8703
8704 // Events
8705 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8706 if ( this.outlined ) {
8707 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8708 }
8709 if ( this.autoFocus ) {
8710 // Event 'focus' does not bubble, but 'focusin' does
8711 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8712 }
8713
8714 // Initialization
8715 this.$element.addClass( 'oo-ui-bookletLayout' );
8716 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8717 if ( this.outlined ) {
8718 this.outlinePanel.$element
8719 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8720 .append( this.outlineSelectWidget.$element );
8721 if ( this.editable ) {
8722 this.outlinePanel.$element
8723 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8724 .append( this.outlineControlsWidget.$element );
8725 }
8726 }
8727 };
8728
8729 /* Setup */
8730
8731 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8732
8733 /* Events */
8734
8735 /**
8736 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8737 * @event set
8738 * @param {OO.ui.PageLayout} page Current page
8739 */
8740
8741 /**
8742 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8743 *
8744 * @event add
8745 * @param {OO.ui.PageLayout[]} page Added pages
8746 * @param {number} index Index pages were added at
8747 */
8748
8749 /**
8750 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8751 * {@link #removePages removed} from the booklet.
8752 *
8753 * @event remove
8754 * @param {OO.ui.PageLayout[]} pages Removed pages
8755 */
8756
8757 /* Methods */
8758
8759 /**
8760 * Handle stack layout focus.
8761 *
8762 * @private
8763 * @param {jQuery.Event} e Focusin event
8764 */
8765 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8766 var name, $target;
8767
8768 // Find the page that an element was focused within
8769 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8770 for ( name in this.pages ) {
8771 // Check for page match, exclude current page to find only page changes
8772 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8773 this.setPage( name );
8774 break;
8775 }
8776 }
8777 };
8778
8779 /**
8780 * Handle stack layout set events.
8781 *
8782 * @private
8783 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8784 */
8785 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8786 var layout = this;
8787 if ( page ) {
8788 page.scrollElementIntoView( { complete: function () {
8789 if ( layout.autoFocus ) {
8790 layout.focus();
8791 }
8792 } } );
8793 }
8794 };
8795
8796 /**
8797 * Focus the first input in the current page.
8798 *
8799 * If no page is selected, the first selectable page will be selected.
8800 * If the focus is already in an element on the current page, nothing will happen.
8801 * @param {number} [itemIndex] A specific item to focus on
8802 */
8803 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
8804 var $input, page,
8805 items = this.stackLayout.getItems();
8806
8807 if ( itemIndex !== undefined && items[ itemIndex ] ) {
8808 page = items[ itemIndex ];
8809 } else {
8810 page = this.stackLayout.getCurrentItem();
8811 }
8812
8813 if ( !page && this.outlined ) {
8814 this.selectFirstSelectablePage();
8815 page = this.stackLayout.getCurrentItem();
8816 }
8817 if ( !page ) {
8818 return;
8819 }
8820 // Only change the focus if is not already in the current page
8821 if ( !page.$element.find( ':focus' ).length ) {
8822 $input = page.$element.find( ':input:first' );
8823 if ( $input.length ) {
8824 $input[ 0 ].focus();
8825 }
8826 }
8827 };
8828
8829 /**
8830 * Find the first focusable input in the booklet layout and focus
8831 * on it.
8832 */
8833 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
8834 var i, len,
8835 found = false,
8836 items = this.stackLayout.getItems(),
8837 checkAndFocus = function () {
8838 if ( OO.ui.isFocusableElement( $( this ) ) ) {
8839 $( this ).focus();
8840 found = true;
8841 return false;
8842 }
8843 };
8844
8845 for ( i = 0, len = items.length; i < len; i++ ) {
8846 if ( found ) {
8847 break;
8848 }
8849 // Find all potentially focusable elements in the item
8850 // and check if they are focusable
8851 items[i].$element
8852 .find( 'input, select, textarea, button, object' )
8853 /* jshint loopfunc:true */
8854 .each( checkAndFocus );
8855 }
8856 };
8857
8858 /**
8859 * Handle outline widget select events.
8860 *
8861 * @private
8862 * @param {OO.ui.OptionWidget|null} item Selected item
8863 */
8864 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8865 if ( item ) {
8866 this.setPage( item.getData() );
8867 }
8868 };
8869
8870 /**
8871 * Check if booklet has an outline.
8872 *
8873 * @return {boolean} Booklet has an outline
8874 */
8875 OO.ui.BookletLayout.prototype.isOutlined = function () {
8876 return this.outlined;
8877 };
8878
8879 /**
8880 * Check if booklet has editing controls.
8881 *
8882 * @return {boolean} Booklet is editable
8883 */
8884 OO.ui.BookletLayout.prototype.isEditable = function () {
8885 return this.editable;
8886 };
8887
8888 /**
8889 * Check if booklet has a visible outline.
8890 *
8891 * @return {boolean} Outline is visible
8892 */
8893 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8894 return this.outlined && this.outlineVisible;
8895 };
8896
8897 /**
8898 * Hide or show the outline.
8899 *
8900 * @param {boolean} [show] Show outline, omit to invert current state
8901 * @chainable
8902 */
8903 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8904 if ( this.outlined ) {
8905 show = show === undefined ? !this.outlineVisible : !!show;
8906 this.outlineVisible = show;
8907 this.toggleMenu( show );
8908 }
8909
8910 return this;
8911 };
8912
8913 /**
8914 * Get the page closest to the specified page.
8915 *
8916 * @param {OO.ui.PageLayout} page Page to use as a reference point
8917 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8918 */
8919 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8920 var next, prev, level,
8921 pages = this.stackLayout.getItems(),
8922 index = $.inArray( page, pages );
8923
8924 if ( index !== -1 ) {
8925 next = pages[ index + 1 ];
8926 prev = pages[ index - 1 ];
8927 // Prefer adjacent pages at the same level
8928 if ( this.outlined ) {
8929 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8930 if (
8931 prev &&
8932 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8933 ) {
8934 return prev;
8935 }
8936 if (
8937 next &&
8938 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8939 ) {
8940 return next;
8941 }
8942 }
8943 }
8944 return prev || next || null;
8945 };
8946
8947 /**
8948 * Get the outline widget.
8949 *
8950 * If the booklet is not outlined, the method will return `null`.
8951 *
8952 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8953 */
8954 OO.ui.BookletLayout.prototype.getOutline = function () {
8955 return this.outlineSelectWidget;
8956 };
8957
8958 /**
8959 * Get the outline controls widget.
8960 *
8961 * If the outline is not editable, the method will return `null`.
8962 *
8963 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8964 */
8965 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8966 return this.outlineControlsWidget;
8967 };
8968
8969 /**
8970 * Get a page by its symbolic name.
8971 *
8972 * @param {string} name Symbolic name of page
8973 * @return {OO.ui.PageLayout|undefined} Page, if found
8974 */
8975 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8976 return this.pages[ name ];
8977 };
8978
8979 /**
8980 * Get the current page.
8981 *
8982 * @return {OO.ui.PageLayout|undefined} Current page, if found
8983 */
8984 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8985 var name = this.getCurrentPageName();
8986 return name ? this.getPage( name ) : undefined;
8987 };
8988
8989 /**
8990 * Get the symbolic name of the current page.
8991 *
8992 * @return {string|null} Symbolic name of the current page
8993 */
8994 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8995 return this.currentPageName;
8996 };
8997
8998 /**
8999 * Add pages to the booklet layout
9000 *
9001 * When pages are added with the same names as existing pages, the existing pages will be
9002 * automatically removed before the new pages are added.
9003 *
9004 * @param {OO.ui.PageLayout[]} pages Pages to add
9005 * @param {number} index Index of the insertion point
9006 * @fires add
9007 * @chainable
9008 */
9009 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9010 var i, len, name, page, item, currentIndex,
9011 stackLayoutPages = this.stackLayout.getItems(),
9012 remove = [],
9013 items = [];
9014
9015 // Remove pages with same names
9016 for ( i = 0, len = pages.length; i < len; i++ ) {
9017 page = pages[ i ];
9018 name = page.getName();
9019
9020 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9021 // Correct the insertion index
9022 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
9023 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9024 index--;
9025 }
9026 remove.push( this.pages[ name ] );
9027 }
9028 }
9029 if ( remove.length ) {
9030 this.removePages( remove );
9031 }
9032
9033 // Add new pages
9034 for ( i = 0, len = pages.length; i < len; i++ ) {
9035 page = pages[ i ];
9036 name = page.getName();
9037 this.pages[ page.getName() ] = page;
9038 if ( this.outlined ) {
9039 item = new OO.ui.OutlineOptionWidget( { data: name } );
9040 page.setOutlineItem( item );
9041 items.push( item );
9042 }
9043 }
9044
9045 if ( this.outlined && items.length ) {
9046 this.outlineSelectWidget.addItems( items, index );
9047 this.selectFirstSelectablePage();
9048 }
9049 this.stackLayout.addItems( pages, index );
9050 this.emit( 'add', pages, index );
9051
9052 return this;
9053 };
9054
9055 /**
9056 * Remove the specified pages from the booklet layout.
9057 *
9058 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9059 *
9060 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9061 * @fires remove
9062 * @chainable
9063 */
9064 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9065 var i, len, name, page,
9066 items = [];
9067
9068 for ( i = 0, len = pages.length; i < len; i++ ) {
9069 page = pages[ i ];
9070 name = page.getName();
9071 delete this.pages[ name ];
9072 if ( this.outlined ) {
9073 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9074 page.setOutlineItem( null );
9075 }
9076 }
9077 if ( this.outlined && items.length ) {
9078 this.outlineSelectWidget.removeItems( items );
9079 this.selectFirstSelectablePage();
9080 }
9081 this.stackLayout.removeItems( pages );
9082 this.emit( 'remove', pages );
9083
9084 return this;
9085 };
9086
9087 /**
9088 * Clear all pages from the booklet layout.
9089 *
9090 * To remove only a subset of pages from the booklet, use the #removePages method.
9091 *
9092 * @fires remove
9093 * @chainable
9094 */
9095 OO.ui.BookletLayout.prototype.clearPages = function () {
9096 var i, len,
9097 pages = this.stackLayout.getItems();
9098
9099 this.pages = {};
9100 this.currentPageName = null;
9101 if ( this.outlined ) {
9102 this.outlineSelectWidget.clearItems();
9103 for ( i = 0, len = pages.length; i < len; i++ ) {
9104 pages[ i ].setOutlineItem( null );
9105 }
9106 }
9107 this.stackLayout.clearItems();
9108
9109 this.emit( 'remove', pages );
9110
9111 return this;
9112 };
9113
9114 /**
9115 * Set the current page by symbolic name.
9116 *
9117 * @fires set
9118 * @param {string} name Symbolic name of page
9119 */
9120 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9121 var selectedItem,
9122 $focused,
9123 page = this.pages[ name ];
9124
9125 if ( name !== this.currentPageName ) {
9126 if ( this.outlined ) {
9127 selectedItem = this.outlineSelectWidget.getSelectedItem();
9128 if ( selectedItem && selectedItem.getData() !== name ) {
9129 this.outlineSelectWidget.selectItemByData( name );
9130 }
9131 }
9132 if ( page ) {
9133 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9134 this.pages[ this.currentPageName ].setActive( false );
9135 // Blur anything focused if the next page doesn't have anything focusable - this
9136 // is not needed if the next page has something focusable because once it is focused
9137 // this blur happens automatically
9138 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9139 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9140 if ( $focused.length ) {
9141 $focused[ 0 ].blur();
9142 }
9143 }
9144 }
9145 this.currentPageName = name;
9146 this.stackLayout.setItem( page );
9147 page.setActive( true );
9148 this.emit( 'set', page );
9149 }
9150 }
9151 };
9152
9153 /**
9154 * Select the first selectable page.
9155 *
9156 * @chainable
9157 */
9158 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9159 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9160 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9161 }
9162
9163 return this;
9164 };
9165
9166 /**
9167 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9168 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9169 * select which one to display. By default, only one card is displayed at a time. When a user
9170 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9171 * unless the default setting is changed.
9172 *
9173 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9174 *
9175 * @example
9176 * // Example of a IndexLayout that contains two CardLayouts.
9177 *
9178 * function CardOneLayout( name, config ) {
9179 * CardOneLayout.super.call( this, name, config );
9180 * this.$element.append( '<p>First card</p>' );
9181 * }
9182 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9183 * CardOneLayout.prototype.setupTabItem = function () {
9184 * this.tabItem.setLabel( 'Card One' );
9185 * };
9186 *
9187 * function CardTwoLayout( name, config ) {
9188 * CardTwoLayout.super.call( this, name, config );
9189 * this.$element.append( '<p>Second card</p>' );
9190 * }
9191 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9192 * CardTwoLayout.prototype.setupTabItem = function () {
9193 * this.tabItem.setLabel( 'Card Two' );
9194 * };
9195 *
9196 * var card1 = new CardOneLayout( 'one' ),
9197 * card2 = new CardTwoLayout( 'two' );
9198 *
9199 * var index = new OO.ui.IndexLayout();
9200 *
9201 * index.addCards ( [ card1, card2 ] );
9202 * $( 'body' ).append( index.$element );
9203 *
9204 * @class
9205 * @extends OO.ui.MenuLayout
9206 *
9207 * @constructor
9208 * @param {Object} [config] Configuration options
9209 * @cfg {boolean} [continuous=false] Show all cards, one after another
9210 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9211 */
9212 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
9213 // Configuration initialization
9214 config = $.extend( {}, config, { menuPosition: 'top' } );
9215
9216 // Parent constructor
9217 OO.ui.IndexLayout.super.call( this, config );
9218
9219 // Properties
9220 this.currentCardName = null;
9221 this.cards = {};
9222 this.ignoreFocus = false;
9223 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9224 this.$content.append( this.stackLayout.$element );
9225 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9226
9227 this.tabSelectWidget = new OO.ui.TabSelectWidget();
9228 this.tabPanel = new OO.ui.PanelLayout();
9229 this.$menu.append( this.tabPanel.$element );
9230
9231 this.toggleMenu( true );
9232
9233 // Events
9234 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9235 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
9236 if ( this.autoFocus ) {
9237 // Event 'focus' does not bubble, but 'focusin' does
9238 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9239 }
9240
9241 // Initialization
9242 this.$element.addClass( 'oo-ui-indexLayout' );
9243 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
9244 this.tabPanel.$element
9245 .addClass( 'oo-ui-indexLayout-tabPanel' )
9246 .append( this.tabSelectWidget.$element );
9247 };
9248
9249 /* Setup */
9250
9251 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
9252
9253 /* Events */
9254
9255 /**
9256 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9257 * @event set
9258 * @param {OO.ui.CardLayout} card Current card
9259 */
9260
9261 /**
9262 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9263 *
9264 * @event add
9265 * @param {OO.ui.CardLayout[]} card Added cards
9266 * @param {number} index Index cards were added at
9267 */
9268
9269 /**
9270 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9271 * {@link #removeCards removed} from the index.
9272 *
9273 * @event remove
9274 * @param {OO.ui.CardLayout[]} cards Removed cards
9275 */
9276
9277 /* Methods */
9278
9279 /**
9280 * Handle stack layout focus.
9281 *
9282 * @private
9283 * @param {jQuery.Event} e Focusin event
9284 */
9285 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
9286 var name, $target;
9287
9288 // Find the card that an element was focused within
9289 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
9290 for ( name in this.cards ) {
9291 // Check for card match, exclude current card to find only card changes
9292 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
9293 this.setCard( name );
9294 break;
9295 }
9296 }
9297 };
9298
9299 /**
9300 * Handle stack layout set events.
9301 *
9302 * @private
9303 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9304 */
9305 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
9306 var layout = this;
9307 if ( card ) {
9308 card.scrollElementIntoView( { complete: function () {
9309 if ( layout.autoFocus ) {
9310 layout.focus();
9311 }
9312 } } );
9313 }
9314 };
9315
9316 /**
9317 * Focus the first input in the current card.
9318 *
9319 * If no card is selected, the first selectable card will be selected.
9320 * If the focus is already in an element on the current card, nothing will happen.
9321 * @param {number} [itemIndex] A specific item to focus on
9322 */
9323 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
9324 var $input, card,
9325 items = this.stackLayout.getItems();
9326
9327 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9328 card = items[ itemIndex ];
9329 } else {
9330 card = this.stackLayout.getCurrentItem();
9331 }
9332
9333 if ( !card ) {
9334 this.selectFirstSelectableCard();
9335 card = this.stackLayout.getCurrentItem();
9336 }
9337 if ( !card ) {
9338 return;
9339 }
9340 // Only change the focus if is not already in the current card
9341 if ( !card.$element.find( ':focus' ).length ) {
9342 $input = card.$element.find( ':input:first' );
9343 if ( $input.length ) {
9344 $input[ 0 ].focus();
9345 }
9346 }
9347 };
9348
9349 /**
9350 * Find the first focusable input in the index layout and focus
9351 * on it.
9352 */
9353 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
9354 var i, len,
9355 found = false,
9356 items = this.stackLayout.getItems(),
9357 checkAndFocus = function () {
9358 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9359 $( this ).focus();
9360 found = true;
9361 return false;
9362 }
9363 };
9364
9365 for ( i = 0, len = items.length; i < len; i++ ) {
9366 if ( found ) {
9367 break;
9368 }
9369 // Find all potentially focusable elements in the item
9370 // and check if they are focusable
9371 items[i].$element
9372 .find( 'input, select, textarea, button, object' )
9373 .each( checkAndFocus );
9374 }
9375 };
9376
9377 /**
9378 * Handle tab widget select events.
9379 *
9380 * @private
9381 * @param {OO.ui.OptionWidget|null} item Selected item
9382 */
9383 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
9384 if ( item ) {
9385 this.setCard( item.getData() );
9386 }
9387 };
9388
9389 /**
9390 * Get the card closest to the specified card.
9391 *
9392 * @param {OO.ui.CardLayout} card Card to use as a reference point
9393 * @return {OO.ui.CardLayout|null} Card closest to the specified card
9394 */
9395 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
9396 var next, prev, level,
9397 cards = this.stackLayout.getItems(),
9398 index = $.inArray( card, cards );
9399
9400 if ( index !== -1 ) {
9401 next = cards[ index + 1 ];
9402 prev = cards[ index - 1 ];
9403 // Prefer adjacent cards at the same level
9404 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
9405 if (
9406 prev &&
9407 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
9408 ) {
9409 return prev;
9410 }
9411 if (
9412 next &&
9413 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
9414 ) {
9415 return next;
9416 }
9417 }
9418 return prev || next || null;
9419 };
9420
9421 /**
9422 * Get the tabs widget.
9423 *
9424 * @return {OO.ui.TabSelectWidget} Tabs widget
9425 */
9426 OO.ui.IndexLayout.prototype.getTabs = function () {
9427 return this.tabSelectWidget;
9428 };
9429
9430 /**
9431 * Get a card by its symbolic name.
9432 *
9433 * @param {string} name Symbolic name of card
9434 * @return {OO.ui.CardLayout|undefined} Card, if found
9435 */
9436 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
9437 return this.cards[ name ];
9438 };
9439
9440 /**
9441 * Get the current card.
9442 *
9443 * @return {OO.ui.CardLayout|undefined} Current card, if found
9444 */
9445 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
9446 var name = this.getCurrentCardName();
9447 return name ? this.getCard( name ) : undefined;
9448 };
9449
9450 /**
9451 * Get the symbolic name of the current card.
9452 *
9453 * @return {string|null} Symbolic name of the current card
9454 */
9455 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
9456 return this.currentCardName;
9457 };
9458
9459 /**
9460 * Add cards to the index layout
9461 *
9462 * When cards are added with the same names as existing cards, the existing cards will be
9463 * automatically removed before the new cards are added.
9464 *
9465 * @param {OO.ui.CardLayout[]} cards Cards to add
9466 * @param {number} index Index of the insertion point
9467 * @fires add
9468 * @chainable
9469 */
9470 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
9471 var i, len, name, card, item, currentIndex,
9472 stackLayoutCards = this.stackLayout.getItems(),
9473 remove = [],
9474 items = [];
9475
9476 // Remove cards with same names
9477 for ( i = 0, len = cards.length; i < len; i++ ) {
9478 card = cards[ i ];
9479 name = card.getName();
9480
9481 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
9482 // Correct the insertion index
9483 currentIndex = $.inArray( this.cards[ name ], stackLayoutCards );
9484 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9485 index--;
9486 }
9487 remove.push( this.cards[ name ] );
9488 }
9489 }
9490 if ( remove.length ) {
9491 this.removeCards( remove );
9492 }
9493
9494 // Add new cards
9495 for ( i = 0, len = cards.length; i < len; i++ ) {
9496 card = cards[ i ];
9497 name = card.getName();
9498 this.cards[ card.getName() ] = card;
9499 item = new OO.ui.TabOptionWidget( { data: name } );
9500 card.setTabItem( item );
9501 items.push( item );
9502 }
9503
9504 if ( items.length ) {
9505 this.tabSelectWidget.addItems( items, index );
9506 this.selectFirstSelectableCard();
9507 }
9508 this.stackLayout.addItems( cards, index );
9509 this.emit( 'add', cards, index );
9510
9511 return this;
9512 };
9513
9514 /**
9515 * Remove the specified cards from the index layout.
9516 *
9517 * To remove all cards from the index, you may wish to use the #clearCards method instead.
9518 *
9519 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
9520 * @fires remove
9521 * @chainable
9522 */
9523 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
9524 var i, len, name, card,
9525 items = [];
9526
9527 for ( i = 0, len = cards.length; i < len; i++ ) {
9528 card = cards[ i ];
9529 name = card.getName();
9530 delete this.cards[ name ];
9531 items.push( this.tabSelectWidget.getItemFromData( name ) );
9532 card.setTabItem( null );
9533 }
9534 if ( items.length ) {
9535 this.tabSelectWidget.removeItems( items );
9536 this.selectFirstSelectableCard();
9537 }
9538 this.stackLayout.removeItems( cards );
9539 this.emit( 'remove', cards );
9540
9541 return this;
9542 };
9543
9544 /**
9545 * Clear all cards from the index layout.
9546 *
9547 * To remove only a subset of cards from the index, use the #removeCards method.
9548 *
9549 * @fires remove
9550 * @chainable
9551 */
9552 OO.ui.IndexLayout.prototype.clearCards = function () {
9553 var i, len,
9554 cards = this.stackLayout.getItems();
9555
9556 this.cards = {};
9557 this.currentCardName = null;
9558 this.tabSelectWidget.clearItems();
9559 for ( i = 0, len = cards.length; i < len; i++ ) {
9560 cards[ i ].setTabItem( null );
9561 }
9562 this.stackLayout.clearItems();
9563
9564 this.emit( 'remove', cards );
9565
9566 return this;
9567 };
9568
9569 /**
9570 * Set the current card by symbolic name.
9571 *
9572 * @fires set
9573 * @param {string} name Symbolic name of card
9574 */
9575 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
9576 var selectedItem,
9577 $focused,
9578 card = this.cards[ name ];
9579
9580 if ( name !== this.currentCardName ) {
9581 selectedItem = this.tabSelectWidget.getSelectedItem();
9582 if ( selectedItem && selectedItem.getData() !== name ) {
9583 this.tabSelectWidget.selectItemByData( name );
9584 }
9585 if ( card ) {
9586 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
9587 this.cards[ this.currentCardName ].setActive( false );
9588 // Blur anything focused if the next card doesn't have anything focusable - this
9589 // is not needed if the next card has something focusable because once it is focused
9590 // this blur happens automatically
9591 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
9592 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
9593 if ( $focused.length ) {
9594 $focused[ 0 ].blur();
9595 }
9596 }
9597 }
9598 this.currentCardName = name;
9599 this.stackLayout.setItem( card );
9600 card.setActive( true );
9601 this.emit( 'set', card );
9602 }
9603 }
9604 };
9605
9606 /**
9607 * Select the first selectable card.
9608 *
9609 * @chainable
9610 */
9611 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
9612 if ( !this.tabSelectWidget.getSelectedItem() ) {
9613 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
9614 }
9615
9616 return this;
9617 };
9618
9619 /**
9620 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9621 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9622 *
9623 * @example
9624 * // Example of a panel layout
9625 * var panel = new OO.ui.PanelLayout( {
9626 * expanded: false,
9627 * framed: true,
9628 * padded: true,
9629 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9630 * } );
9631 * $( 'body' ).append( panel.$element );
9632 *
9633 * @class
9634 * @extends OO.ui.Layout
9635 *
9636 * @constructor
9637 * @param {Object} [config] Configuration options
9638 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9639 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9640 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9641 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9642 */
9643 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
9644 // Configuration initialization
9645 config = $.extend( {
9646 scrollable: false,
9647 padded: false,
9648 expanded: true,
9649 framed: false
9650 }, config );
9651
9652 // Parent constructor
9653 OO.ui.PanelLayout.super.call( this, config );
9654
9655 // Initialization
9656 this.$element.addClass( 'oo-ui-panelLayout' );
9657 if ( config.scrollable ) {
9658 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
9659 }
9660 if ( config.padded ) {
9661 this.$element.addClass( 'oo-ui-panelLayout-padded' );
9662 }
9663 if ( config.expanded ) {
9664 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
9665 }
9666 if ( config.framed ) {
9667 this.$element.addClass( 'oo-ui-panelLayout-framed' );
9668 }
9669 };
9670
9671 /* Setup */
9672
9673 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
9674
9675 /**
9676 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
9677 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
9678 * rather extended to include the required content and functionality.
9679 *
9680 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
9681 * item is customized (with a label) using the #setupTabItem method. See
9682 * {@link OO.ui.IndexLayout IndexLayout} for an example.
9683 *
9684 * @class
9685 * @extends OO.ui.PanelLayout
9686 *
9687 * @constructor
9688 * @param {string} name Unique symbolic name of card
9689 * @param {Object} [config] Configuration options
9690 */
9691 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
9692 // Allow passing positional parameters inside the config object
9693 if ( OO.isPlainObject( name ) && config === undefined ) {
9694 config = name;
9695 name = config.name;
9696 }
9697
9698 // Configuration initialization
9699 config = $.extend( { scrollable: true }, config );
9700
9701 // Parent constructor
9702 OO.ui.CardLayout.super.call( this, config );
9703
9704 // Properties
9705 this.name = name;
9706 this.tabItem = null;
9707 this.active = false;
9708
9709 // Initialization
9710 this.$element.addClass( 'oo-ui-cardLayout' );
9711 };
9712
9713 /* Setup */
9714
9715 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
9716
9717 /* Events */
9718
9719 /**
9720 * An 'active' event is emitted when the card becomes active. Cards become active when they are
9721 * shown in a index layout that is configured to display only one card at a time.
9722 *
9723 * @event active
9724 * @param {boolean} active Card is active
9725 */
9726
9727 /* Methods */
9728
9729 /**
9730 * Get the symbolic name of the card.
9731 *
9732 * @return {string} Symbolic name of card
9733 */
9734 OO.ui.CardLayout.prototype.getName = function () {
9735 return this.name;
9736 };
9737
9738 /**
9739 * Check if card is active.
9740 *
9741 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
9742 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
9743 *
9744 * @return {boolean} Card is active
9745 */
9746 OO.ui.CardLayout.prototype.isActive = function () {
9747 return this.active;
9748 };
9749
9750 /**
9751 * Get tab item.
9752 *
9753 * The tab item allows users to access the card from the index's tab
9754 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
9755 *
9756 * @return {OO.ui.TabOptionWidget|null} Tab option widget
9757 */
9758 OO.ui.CardLayout.prototype.getTabItem = function () {
9759 return this.tabItem;
9760 };
9761
9762 /**
9763 * Set or unset the tab item.
9764 *
9765 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
9766 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
9767 * level), use #setupTabItem instead of this method.
9768 *
9769 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
9770 * @chainable
9771 */
9772 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
9773 this.tabItem = tabItem || null;
9774 if ( tabItem ) {
9775 this.setupTabItem();
9776 }
9777 return this;
9778 };
9779
9780 /**
9781 * Set up the tab item.
9782 *
9783 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
9784 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
9785 * the #setTabItem method instead.
9786 *
9787 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
9788 * @chainable
9789 */
9790 OO.ui.CardLayout.prototype.setupTabItem = function () {
9791 return this;
9792 };
9793
9794 /**
9795 * Set the card to its 'active' state.
9796 *
9797 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
9798 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
9799 * context, setting the active state on a card does nothing.
9800 *
9801 * @param {boolean} value Card is active
9802 * @fires active
9803 */
9804 OO.ui.CardLayout.prototype.setActive = function ( active ) {
9805 active = !!active;
9806
9807 if ( active !== this.active ) {
9808 this.active = active;
9809 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
9810 this.emit( 'active', this.active );
9811 }
9812 };
9813
9814 /**
9815 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9816 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9817 * rather extended to include the required content and functionality.
9818 *
9819 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9820 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9821 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9822 *
9823 * @class
9824 * @extends OO.ui.PanelLayout
9825 *
9826 * @constructor
9827 * @param {string} name Unique symbolic name of page
9828 * @param {Object} [config] Configuration options
9829 */
9830 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
9831 // Allow passing positional parameters inside the config object
9832 if ( OO.isPlainObject( name ) && config === undefined ) {
9833 config = name;
9834 name = config.name;
9835 }
9836
9837 // Configuration initialization
9838 config = $.extend( { scrollable: true }, config );
9839
9840 // Parent constructor
9841 OO.ui.PageLayout.super.call( this, config );
9842
9843 // Properties
9844 this.name = name;
9845 this.outlineItem = null;
9846 this.active = false;
9847
9848 // Initialization
9849 this.$element.addClass( 'oo-ui-pageLayout' );
9850 };
9851
9852 /* Setup */
9853
9854 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
9855
9856 /* Events */
9857
9858 /**
9859 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9860 * shown in a booklet layout that is configured to display only one page at a time.
9861 *
9862 * @event active
9863 * @param {boolean} active Page is active
9864 */
9865
9866 /* Methods */
9867
9868 /**
9869 * Get the symbolic name of the page.
9870 *
9871 * @return {string} Symbolic name of page
9872 */
9873 OO.ui.PageLayout.prototype.getName = function () {
9874 return this.name;
9875 };
9876
9877 /**
9878 * Check if page is active.
9879 *
9880 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9881 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9882 *
9883 * @return {boolean} Page is active
9884 */
9885 OO.ui.PageLayout.prototype.isActive = function () {
9886 return this.active;
9887 };
9888
9889 /**
9890 * Get outline item.
9891 *
9892 * The outline item allows users to access the page from the booklet's outline
9893 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9894 *
9895 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9896 */
9897 OO.ui.PageLayout.prototype.getOutlineItem = function () {
9898 return this.outlineItem;
9899 };
9900
9901 /**
9902 * Set or unset the outline item.
9903 *
9904 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9905 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9906 * level), use #setupOutlineItem instead of this method.
9907 *
9908 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9909 * @chainable
9910 */
9911 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
9912 this.outlineItem = outlineItem || null;
9913 if ( outlineItem ) {
9914 this.setupOutlineItem();
9915 }
9916 return this;
9917 };
9918
9919 /**
9920 * Set up the outline item.
9921 *
9922 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9923 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9924 * the #setOutlineItem method instead.
9925 *
9926 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9927 * @chainable
9928 */
9929 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
9930 return this;
9931 };
9932
9933 /**
9934 * Set the page to its 'active' state.
9935 *
9936 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9937 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9938 * context, setting the active state on a page does nothing.
9939 *
9940 * @param {boolean} value Page is active
9941 * @fires active
9942 */
9943 OO.ui.PageLayout.prototype.setActive = function ( active ) {
9944 active = !!active;
9945
9946 if ( active !== this.active ) {
9947 this.active = active;
9948 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
9949 this.emit( 'active', this.active );
9950 }
9951 };
9952
9953 /**
9954 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9955 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9956 * by setting the #continuous option to 'true'.
9957 *
9958 * @example
9959 * // A stack layout with two panels, configured to be displayed continously
9960 * var myStack = new OO.ui.StackLayout( {
9961 * items: [
9962 * new OO.ui.PanelLayout( {
9963 * $content: $( '<p>Panel One</p>' ),
9964 * padded: true,
9965 * framed: true
9966 * } ),
9967 * new OO.ui.PanelLayout( {
9968 * $content: $( '<p>Panel Two</p>' ),
9969 * padded: true,
9970 * framed: true
9971 * } )
9972 * ],
9973 * continuous: true
9974 * } );
9975 * $( 'body' ).append( myStack.$element );
9976 *
9977 * @class
9978 * @extends OO.ui.PanelLayout
9979 * @mixins OO.ui.GroupElement
9980 *
9981 * @constructor
9982 * @param {Object} [config] Configuration options
9983 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9984 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9985 */
9986 OO.ui.StackLayout = function OoUiStackLayout( config ) {
9987 // Configuration initialization
9988 config = $.extend( { scrollable: true }, config );
9989
9990 // Parent constructor
9991 OO.ui.StackLayout.super.call( this, config );
9992
9993 // Mixin constructors
9994 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9995
9996 // Properties
9997 this.currentItem = null;
9998 this.continuous = !!config.continuous;
9999
10000 // Initialization
10001 this.$element.addClass( 'oo-ui-stackLayout' );
10002 if ( this.continuous ) {
10003 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10004 }
10005 if ( Array.isArray( config.items ) ) {
10006 this.addItems( config.items );
10007 }
10008 };
10009
10010 /* Setup */
10011
10012 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10013 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
10014
10015 /* Events */
10016
10017 /**
10018 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10019 * {@link #clearItems cleared} or {@link #setItem displayed}.
10020 *
10021 * @event set
10022 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10023 */
10024
10025 /* Methods */
10026
10027 /**
10028 * Get the current panel.
10029 *
10030 * @return {OO.ui.Layout|null}
10031 */
10032 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10033 return this.currentItem;
10034 };
10035
10036 /**
10037 * Unset the current item.
10038 *
10039 * @private
10040 * @param {OO.ui.StackLayout} layout
10041 * @fires set
10042 */
10043 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10044 var prevItem = this.currentItem;
10045 if ( prevItem === null ) {
10046 return;
10047 }
10048
10049 this.currentItem = null;
10050 this.emit( 'set', null );
10051 };
10052
10053 /**
10054 * Add panel layouts to the stack layout.
10055 *
10056 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10057 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10058 * by the index.
10059 *
10060 * @param {OO.ui.Layout[]} items Panels to add
10061 * @param {number} [index] Index of the insertion point
10062 * @chainable
10063 */
10064 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10065 // Update the visibility
10066 this.updateHiddenState( items, this.currentItem );
10067
10068 // Mixin method
10069 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
10070
10071 if ( !this.currentItem && items.length ) {
10072 this.setItem( items[ 0 ] );
10073 }
10074
10075 return this;
10076 };
10077
10078 /**
10079 * Remove the specified panels from the stack layout.
10080 *
10081 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10082 * you may wish to use the #clearItems method instead.
10083 *
10084 * @param {OO.ui.Layout[]} items Panels to remove
10085 * @chainable
10086 * @fires set
10087 */
10088 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10089 // Mixin method
10090 OO.ui.GroupElement.prototype.removeItems.call( this, items );
10091
10092 if ( $.inArray( this.currentItem, items ) !== -1 ) {
10093 if ( this.items.length ) {
10094 this.setItem( this.items[ 0 ] );
10095 } else {
10096 this.unsetCurrentItem();
10097 }
10098 }
10099
10100 return this;
10101 };
10102
10103 /**
10104 * Clear all panels from the stack layout.
10105 *
10106 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10107 * a subset of panels, use the #removeItems method.
10108 *
10109 * @chainable
10110 * @fires set
10111 */
10112 OO.ui.StackLayout.prototype.clearItems = function () {
10113 this.unsetCurrentItem();
10114 OO.ui.GroupElement.prototype.clearItems.call( this );
10115
10116 return this;
10117 };
10118
10119 /**
10120 * Show the specified panel.
10121 *
10122 * If another panel is currently displayed, it will be hidden.
10123 *
10124 * @param {OO.ui.Layout} item Panel to show
10125 * @chainable
10126 * @fires set
10127 */
10128 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10129 if ( item !== this.currentItem ) {
10130 this.updateHiddenState( this.items, item );
10131
10132 if ( $.inArray( item, this.items ) !== -1 ) {
10133 this.currentItem = item;
10134 this.emit( 'set', item );
10135 } else {
10136 this.unsetCurrentItem();
10137 }
10138 }
10139
10140 return this;
10141 };
10142
10143 /**
10144 * Update the visibility of all items in case of non-continuous view.
10145 *
10146 * Ensure all items are hidden except for the selected one.
10147 * This method does nothing when the stack is continuous.
10148 *
10149 * @private
10150 * @param {OO.ui.Layout[]} items Item list iterate over
10151 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10152 */
10153 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10154 var i, len;
10155
10156 if ( !this.continuous ) {
10157 for ( i = 0, len = items.length; i < len; i++ ) {
10158 if ( !selectedItem || selectedItem !== items[ i ] ) {
10159 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10160 }
10161 }
10162 if ( selectedItem ) {
10163 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10164 }
10165 }
10166 };
10167
10168 /**
10169 * Horizontal bar layout of tools as icon buttons.
10170 *
10171 * @class
10172 * @extends OO.ui.ToolGroup
10173 *
10174 * @constructor
10175 * @param {OO.ui.Toolbar} toolbar
10176 * @param {Object} [config] Configuration options
10177 */
10178 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
10179 // Allow passing positional parameters inside the config object
10180 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10181 config = toolbar;
10182 toolbar = config.toolbar;
10183 }
10184
10185 // Parent constructor
10186 OO.ui.BarToolGroup.super.call( this, toolbar, config );
10187
10188 // Initialization
10189 this.$element.addClass( 'oo-ui-barToolGroup' );
10190 };
10191
10192 /* Setup */
10193
10194 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
10195
10196 /* Static Properties */
10197
10198 OO.ui.BarToolGroup.static.titleTooltips = true;
10199
10200 OO.ui.BarToolGroup.static.accelTooltips = true;
10201
10202 OO.ui.BarToolGroup.static.name = 'bar';
10203
10204 /**
10205 * Popup list of tools with an icon and optional label.
10206 *
10207 * @abstract
10208 * @class
10209 * @extends OO.ui.ToolGroup
10210 * @mixins OO.ui.IconElement
10211 * @mixins OO.ui.IndicatorElement
10212 * @mixins OO.ui.LabelElement
10213 * @mixins OO.ui.TitledElement
10214 * @mixins OO.ui.ClippableElement
10215 * @mixins OO.ui.TabIndexedElement
10216 *
10217 * @constructor
10218 * @param {OO.ui.Toolbar} toolbar
10219 * @param {Object} [config] Configuration options
10220 * @cfg {string} [header] Text to display at the top of the pop-up
10221 */
10222 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
10223 // Allow passing positional parameters inside the config object
10224 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10225 config = toolbar;
10226 toolbar = config.toolbar;
10227 }
10228
10229 // Configuration initialization
10230 config = config || {};
10231
10232 // Parent constructor
10233 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
10234
10235 // Properties
10236 this.active = false;
10237 this.dragging = false;
10238 this.onBlurHandler = this.onBlur.bind( this );
10239 this.$handle = $( '<span>' );
10240
10241 // Mixin constructors
10242 OO.ui.IconElement.call( this, config );
10243 OO.ui.IndicatorElement.call( this, config );
10244 OO.ui.LabelElement.call( this, config );
10245 OO.ui.TitledElement.call( this, config );
10246 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
10247 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10248
10249 // Events
10250 this.$handle.on( {
10251 keydown: this.onHandleMouseKeyDown.bind( this ),
10252 keyup: this.onHandleMouseKeyUp.bind( this ),
10253 mousedown: this.onHandleMouseKeyDown.bind( this ),
10254 mouseup: this.onHandleMouseKeyUp.bind( this )
10255 } );
10256
10257 // Initialization
10258 this.$handle
10259 .addClass( 'oo-ui-popupToolGroup-handle' )
10260 .append( this.$icon, this.$label, this.$indicator );
10261 // If the pop-up should have a header, add it to the top of the toolGroup.
10262 // Note: If this feature is useful for other widgets, we could abstract it into an
10263 // OO.ui.HeaderedElement mixin constructor.
10264 if ( config.header !== undefined ) {
10265 this.$group
10266 .prepend( $( '<span>' )
10267 .addClass( 'oo-ui-popupToolGroup-header' )
10268 .text( config.header )
10269 );
10270 }
10271 this.$element
10272 .addClass( 'oo-ui-popupToolGroup' )
10273 .prepend( this.$handle );
10274 };
10275
10276 /* Setup */
10277
10278 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
10279 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
10280 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
10281 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
10282 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
10283 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
10284 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TabIndexedElement );
10285
10286 /* Static Properties */
10287
10288 /* Methods */
10289
10290 /**
10291 * @inheritdoc
10292 */
10293 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
10294 // Parent method
10295 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
10296
10297 if ( this.isDisabled() && this.isElementAttached() ) {
10298 this.setActive( false );
10299 }
10300 };
10301
10302 /**
10303 * Handle focus being lost.
10304 *
10305 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
10306 *
10307 * @param {jQuery.Event} e Mouse up or key up event
10308 */
10309 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
10310 // Only deactivate when clicking outside the dropdown element
10311 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
10312 this.setActive( false );
10313 }
10314 };
10315
10316 /**
10317 * @inheritdoc
10318 */
10319 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
10320 // Only close toolgroup when a tool was actually selected
10321 if (
10322 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
10323 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10324 ) {
10325 this.setActive( false );
10326 }
10327 return OO.ui.PopupToolGroup.super.prototype.onMouseKeyUp.call( this, e );
10328 };
10329
10330 /**
10331 * Handle mouse up and key up events.
10332 *
10333 * @param {jQuery.Event} e Mouse up or key up event
10334 */
10335 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
10336 if (
10337 !this.isDisabled() &&
10338 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10339 ) {
10340 return false;
10341 }
10342 };
10343
10344 /**
10345 * Handle mouse down and key down events.
10346 *
10347 * @param {jQuery.Event} e Mouse down or key down event
10348 */
10349 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
10350 if (
10351 !this.isDisabled() &&
10352 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10353 ) {
10354 this.setActive( !this.active );
10355 return false;
10356 }
10357 };
10358
10359 /**
10360 * Switch into active mode.
10361 *
10362 * When active, mouseup events anywhere in the document will trigger deactivation.
10363 */
10364 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
10365 value = !!value;
10366 if ( this.active !== value ) {
10367 this.active = value;
10368 if ( value ) {
10369 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
10370 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true );
10371
10372 // Try anchoring the popup to the left first
10373 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
10374 this.toggleClipping( true );
10375 if ( this.isClippedHorizontally() ) {
10376 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
10377 this.toggleClipping( false );
10378 this.$element
10379 .removeClass( 'oo-ui-popupToolGroup-left' )
10380 .addClass( 'oo-ui-popupToolGroup-right' );
10381 this.toggleClipping( true );
10382 }
10383 } else {
10384 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
10385 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true );
10386 this.$element.removeClass(
10387 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
10388 );
10389 this.toggleClipping( false );
10390 }
10391 }
10392 };
10393
10394 /**
10395 * Drop down list layout of tools as labeled icon buttons.
10396 *
10397 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
10398 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
10399 * may want to use the 'promote' and 'demote' configuration options to achieve this.
10400 *
10401 * @class
10402 * @extends OO.ui.PopupToolGroup
10403 *
10404 * @constructor
10405 * @param {OO.ui.Toolbar} toolbar
10406 * @param {Object} [config] Configuration options
10407 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
10408 * shown.
10409 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
10410 * allowed to be collapsed.
10411 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
10412 */
10413 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
10414 // Allow passing positional parameters inside the config object
10415 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10416 config = toolbar;
10417 toolbar = config.toolbar;
10418 }
10419
10420 // Configuration initialization
10421 config = config || {};
10422
10423 // Properties (must be set before parent constructor, which calls #populate)
10424 this.allowCollapse = config.allowCollapse;
10425 this.forceExpand = config.forceExpand;
10426 this.expanded = config.expanded !== undefined ? config.expanded : false;
10427 this.collapsibleTools = [];
10428
10429 // Parent constructor
10430 OO.ui.ListToolGroup.super.call( this, toolbar, config );
10431
10432 // Initialization
10433 this.$element.addClass( 'oo-ui-listToolGroup' );
10434 };
10435
10436 /* Setup */
10437
10438 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
10439
10440 /* Static Properties */
10441
10442 OO.ui.ListToolGroup.static.accelTooltips = true;
10443
10444 OO.ui.ListToolGroup.static.name = 'list';
10445
10446 /* Methods */
10447
10448 /**
10449 * @inheritdoc
10450 */
10451 OO.ui.ListToolGroup.prototype.populate = function () {
10452 var i, len, allowCollapse = [];
10453
10454 OO.ui.ListToolGroup.super.prototype.populate.call( this );
10455
10456 // Update the list of collapsible tools
10457 if ( this.allowCollapse !== undefined ) {
10458 allowCollapse = this.allowCollapse;
10459 } else if ( this.forceExpand !== undefined ) {
10460 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
10461 }
10462
10463 this.collapsibleTools = [];
10464 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
10465 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
10466 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
10467 }
10468 }
10469
10470 // Keep at the end, even when tools are added
10471 this.$group.append( this.getExpandCollapseTool().$element );
10472
10473 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
10474 this.updateCollapsibleState();
10475 };
10476
10477 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
10478 if ( this.expandCollapseTool === undefined ) {
10479 var ExpandCollapseTool = function () {
10480 ExpandCollapseTool.super.apply( this, arguments );
10481 };
10482
10483 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
10484
10485 ExpandCollapseTool.prototype.onSelect = function () {
10486 this.toolGroup.expanded = !this.toolGroup.expanded;
10487 this.toolGroup.updateCollapsibleState();
10488 this.setActive( false );
10489 };
10490 ExpandCollapseTool.prototype.onUpdateState = function () {
10491 // Do nothing. Tool interface requires an implementation of this function.
10492 };
10493
10494 ExpandCollapseTool.static.name = 'more-fewer';
10495
10496 this.expandCollapseTool = new ExpandCollapseTool( this );
10497 }
10498 return this.expandCollapseTool;
10499 };
10500
10501 /**
10502 * @inheritdoc
10503 */
10504 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
10505 // Do not close the popup when the user wants to show more/fewer tools
10506 if (
10507 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
10508 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10509 ) {
10510 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
10511 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
10512 return OO.ui.ListToolGroup.super.super.prototype.onMouseKeyUp.call( this, e );
10513 } else {
10514 return OO.ui.ListToolGroup.super.prototype.onMouseKeyUp.call( this, e );
10515 }
10516 };
10517
10518 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
10519 var i, len;
10520
10521 this.getExpandCollapseTool()
10522 .setIcon( this.expanded ? 'collapse' : 'expand' )
10523 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
10524
10525 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
10526 this.collapsibleTools[ i ].toggle( this.expanded );
10527 }
10528 };
10529
10530 /**
10531 * Drop down menu layout of tools as selectable menu items.
10532 *
10533 * @class
10534 * @extends OO.ui.PopupToolGroup
10535 *
10536 * @constructor
10537 * @param {OO.ui.Toolbar} toolbar
10538 * @param {Object} [config] Configuration options
10539 */
10540 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
10541 // Allow passing positional parameters inside the config object
10542 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10543 config = toolbar;
10544 toolbar = config.toolbar;
10545 }
10546
10547 // Configuration initialization
10548 config = config || {};
10549
10550 // Parent constructor
10551 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
10552
10553 // Events
10554 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
10555
10556 // Initialization
10557 this.$element.addClass( 'oo-ui-menuToolGroup' );
10558 };
10559
10560 /* Setup */
10561
10562 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
10563
10564 /* Static Properties */
10565
10566 OO.ui.MenuToolGroup.static.accelTooltips = true;
10567
10568 OO.ui.MenuToolGroup.static.name = 'menu';
10569
10570 /* Methods */
10571
10572 /**
10573 * Handle the toolbar state being updated.
10574 *
10575 * When the state changes, the title of each active item in the menu will be joined together and
10576 * used as a label for the group. The label will be empty if none of the items are active.
10577 */
10578 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
10579 var name,
10580 labelTexts = [];
10581
10582 for ( name in this.tools ) {
10583 if ( this.tools[ name ].isActive() ) {
10584 labelTexts.push( this.tools[ name ].getTitle() );
10585 }
10586 }
10587
10588 this.setLabel( labelTexts.join( ', ' ) || ' ' );
10589 };
10590
10591 /**
10592 * Tool that shows a popup when selected.
10593 *
10594 * @abstract
10595 * @class
10596 * @extends OO.ui.Tool
10597 * @mixins OO.ui.PopupElement
10598 *
10599 * @constructor
10600 * @param {OO.ui.ToolGroup} toolGroup
10601 * @param {Object} [config] Configuration options
10602 */
10603 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
10604 // Allow passing positional parameters inside the config object
10605 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
10606 config = toolGroup;
10607 toolGroup = config.toolGroup;
10608 }
10609
10610 // Parent constructor
10611 OO.ui.PopupTool.super.call( this, toolGroup, config );
10612
10613 // Mixin constructors
10614 OO.ui.PopupElement.call( this, config );
10615
10616 // Initialization
10617 this.$element
10618 .addClass( 'oo-ui-popupTool' )
10619 .append( this.popup.$element );
10620 };
10621
10622 /* Setup */
10623
10624 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
10625 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
10626
10627 /* Methods */
10628
10629 /**
10630 * Handle the tool being selected.
10631 *
10632 * @inheritdoc
10633 */
10634 OO.ui.PopupTool.prototype.onSelect = function () {
10635 if ( !this.isDisabled() ) {
10636 this.popup.toggle();
10637 }
10638 this.setActive( false );
10639 return false;
10640 };
10641
10642 /**
10643 * Handle the toolbar state being updated.
10644 *
10645 * @inheritdoc
10646 */
10647 OO.ui.PopupTool.prototype.onUpdateState = function () {
10648 this.setActive( false );
10649 };
10650
10651 /**
10652 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
10653 * menus in toolbars (T74159).
10654 *
10655 * @abstract
10656 * @class
10657 * @extends OO.ui.Tool
10658 *
10659 * @constructor
10660 * @param {OO.ui.ToolGroup} toolGroup
10661 * @param {Object} [config] Configuration options
10662 */
10663 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
10664 // Allow passing positional parameters inside the config object
10665 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
10666 config = toolGroup;
10667 toolGroup = config.toolGroup;
10668 }
10669
10670 // Parent constructor
10671 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
10672
10673 // Properties
10674 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
10675
10676 // Initialization
10677 this.$link.remove();
10678 this.$element
10679 .addClass( 'oo-ui-toolGroupTool' )
10680 .append( this.innerToolGroup.$element );
10681 };
10682
10683 /* Setup */
10684
10685 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
10686
10687 /* Static Properties */
10688
10689 /**
10690 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
10691 *
10692 * @property {Object.<string,Array>}
10693 */
10694 OO.ui.ToolGroupTool.static.groupConfig = {};
10695
10696 /* Methods */
10697
10698 /**
10699 * Handle the tool being selected.
10700 *
10701 * @inheritdoc
10702 */
10703 OO.ui.ToolGroupTool.prototype.onSelect = function () {
10704 this.innerToolGroup.setActive( !this.innerToolGroup.active );
10705 return false;
10706 };
10707
10708 /**
10709 * Handle the toolbar state being updated.
10710 *
10711 * @inheritdoc
10712 */
10713 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
10714 this.setActive( false );
10715 };
10716
10717 /**
10718 * Build a OO.ui.ToolGroup from the configuration.
10719 *
10720 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
10721 * accepted values.
10722 * @return {OO.ui.ListToolGroup}
10723 */
10724 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
10725 if ( group.include === '*' ) {
10726 // Apply defaults to catch-all groups
10727 if ( group.label === undefined ) {
10728 group.label = OO.ui.msg( 'ooui-toolbar-more' );
10729 }
10730 }
10731
10732 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
10733 };
10734
10735 /**
10736 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
10737 *
10738 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
10739 *
10740 * @private
10741 * @abstract
10742 * @class
10743 * @extends OO.ui.GroupElement
10744 *
10745 * @constructor
10746 * @param {Object} [config] Configuration options
10747 */
10748 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
10749 // Parent constructor
10750 OO.ui.GroupWidget.super.call( this, config );
10751 };
10752
10753 /* Setup */
10754
10755 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
10756
10757 /* Methods */
10758
10759 /**
10760 * Set the disabled state of the widget.
10761 *
10762 * This will also update the disabled state of child widgets.
10763 *
10764 * @param {boolean} disabled Disable widget
10765 * @chainable
10766 */
10767 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
10768 var i, len;
10769
10770 // Parent method
10771 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
10772 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
10773
10774 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
10775 if ( this.items ) {
10776 for ( i = 0, len = this.items.length; i < len; i++ ) {
10777 this.items[ i ].updateDisabled();
10778 }
10779 }
10780
10781 return this;
10782 };
10783
10784 /**
10785 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
10786 *
10787 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
10788 * allows bidirectional communication.
10789 *
10790 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
10791 *
10792 * @private
10793 * @abstract
10794 * @class
10795 *
10796 * @constructor
10797 */
10798 OO.ui.ItemWidget = function OoUiItemWidget() {
10799 //
10800 };
10801
10802 /* Methods */
10803
10804 /**
10805 * Check if widget is disabled.
10806 *
10807 * Checks parent if present, making disabled state inheritable.
10808 *
10809 * @return {boolean} Widget is disabled
10810 */
10811 OO.ui.ItemWidget.prototype.isDisabled = function () {
10812 return this.disabled ||
10813 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
10814 };
10815
10816 /**
10817 * Set group element is in.
10818 *
10819 * @param {OO.ui.GroupElement|null} group Group element, null if none
10820 * @chainable
10821 */
10822 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
10823 // Parent method
10824 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10825 OO.ui.Element.prototype.setElementGroup.call( this, group );
10826
10827 // Initialize item disabled states
10828 this.updateDisabled();
10829
10830 return this;
10831 };
10832
10833 /**
10834 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10835 * Controls include moving items up and down, removing items, and adding different kinds of items.
10836 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
10837 *
10838 * @class
10839 * @extends OO.ui.Widget
10840 * @mixins OO.ui.GroupElement
10841 * @mixins OO.ui.IconElement
10842 *
10843 * @constructor
10844 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10845 * @param {Object} [config] Configuration options
10846 * @cfg {Object} [abilities] List of abilties
10847 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10848 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10849 */
10850 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
10851 // Allow passing positional parameters inside the config object
10852 if ( OO.isPlainObject( outline ) && config === undefined ) {
10853 config = outline;
10854 outline = config.outline;
10855 }
10856
10857 // Configuration initialization
10858 config = $.extend( { icon: 'add' }, config );
10859
10860 // Parent constructor
10861 OO.ui.OutlineControlsWidget.super.call( this, config );
10862
10863 // Mixin constructors
10864 OO.ui.GroupElement.call( this, config );
10865 OO.ui.IconElement.call( this, config );
10866
10867 // Properties
10868 this.outline = outline;
10869 this.$movers = $( '<div>' );
10870 this.upButton = new OO.ui.ButtonWidget( {
10871 framed: false,
10872 icon: 'collapse',
10873 title: OO.ui.msg( 'ooui-outline-control-move-up' )
10874 } );
10875 this.downButton = new OO.ui.ButtonWidget( {
10876 framed: false,
10877 icon: 'expand',
10878 title: OO.ui.msg( 'ooui-outline-control-move-down' )
10879 } );
10880 this.removeButton = new OO.ui.ButtonWidget( {
10881 framed: false,
10882 icon: 'remove',
10883 title: OO.ui.msg( 'ooui-outline-control-remove' )
10884 } );
10885 this.abilities = { move: true, remove: true };
10886
10887 // Events
10888 outline.connect( this, {
10889 select: 'onOutlineChange',
10890 add: 'onOutlineChange',
10891 remove: 'onOutlineChange'
10892 } );
10893 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
10894 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
10895 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
10896
10897 // Initialization
10898 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
10899 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
10900 this.$movers
10901 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10902 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
10903 this.$element.append( this.$icon, this.$group, this.$movers );
10904 this.setAbilities( config.abilities || {} );
10905 };
10906
10907 /* Setup */
10908
10909 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
10910 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
10911 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
10912
10913 /* Events */
10914
10915 /**
10916 * @event move
10917 * @param {number} places Number of places to move
10918 */
10919
10920 /**
10921 * @event remove
10922 */
10923
10924 /* Methods */
10925
10926 /**
10927 * Set abilities.
10928 *
10929 * @param {Object} abilities List of abilties
10930 * @param {boolean} [abilities.move] Allow moving movable items
10931 * @param {boolean} [abilities.remove] Allow removing removable items
10932 */
10933 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
10934 var ability;
10935
10936 for ( ability in this.abilities ) {
10937 if ( abilities[ability] !== undefined ) {
10938 this.abilities[ability] = !!abilities[ability];
10939 }
10940 }
10941
10942 this.onOutlineChange();
10943 };
10944
10945 /**
10946 *
10947 * @private
10948 * Handle outline change events.
10949 */
10950 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
10951 var i, len, firstMovable, lastMovable,
10952 items = this.outline.getItems(),
10953 selectedItem = this.outline.getSelectedItem(),
10954 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
10955 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
10956
10957 if ( movable ) {
10958 i = -1;
10959 len = items.length;
10960 while ( ++i < len ) {
10961 if ( items[ i ].isMovable() ) {
10962 firstMovable = items[ i ];
10963 break;
10964 }
10965 }
10966 i = len;
10967 while ( i-- ) {
10968 if ( items[ i ].isMovable() ) {
10969 lastMovable = items[ i ];
10970 break;
10971 }
10972 }
10973 }
10974 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
10975 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
10976 this.removeButton.setDisabled( !removable );
10977 };
10978
10979 /**
10980 * ToggleWidget implements basic behavior of widgets with an on/off state.
10981 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10982 *
10983 * @abstract
10984 * @class
10985 * @extends OO.ui.Widget
10986 *
10987 * @constructor
10988 * @param {Object} [config] Configuration options
10989 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10990 * By default, the toggle is in the 'off' state.
10991 */
10992 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
10993 // Configuration initialization
10994 config = config || {};
10995
10996 // Parent constructor
10997 OO.ui.ToggleWidget.super.call( this, config );
10998
10999 // Properties
11000 this.value = null;
11001
11002 // Initialization
11003 this.$element.addClass( 'oo-ui-toggleWidget' );
11004 this.setValue( !!config.value );
11005 };
11006
11007 /* Setup */
11008
11009 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
11010
11011 /* Events */
11012
11013 /**
11014 * @event change
11015 *
11016 * A change event is emitted when the on/off state of the toggle changes.
11017 *
11018 * @param {boolean} value Value representing the new state of the toggle
11019 */
11020
11021 /* Methods */
11022
11023 /**
11024 * Get the value representing the toggle’s state.
11025 *
11026 * @return {boolean} The on/off state of the toggle
11027 */
11028 OO.ui.ToggleWidget.prototype.getValue = function () {
11029 return this.value;
11030 };
11031
11032 /**
11033 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
11034 *
11035 * @param {boolean} value The state of the toggle
11036 * @fires change
11037 * @chainable
11038 */
11039 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
11040 value = !!value;
11041 if ( this.value !== value ) {
11042 this.value = value;
11043 this.emit( 'change', value );
11044 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
11045 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
11046 this.$element.attr( 'aria-checked', value.toString() );
11047 }
11048 return this;
11049 };
11050
11051 /**
11052 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
11053 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
11054 * removed, and cleared from the group.
11055 *
11056 * @example
11057 * // Example: A ButtonGroupWidget with two buttons
11058 * var button1 = new OO.ui.PopupButtonWidget( {
11059 * label: 'Select a category',
11060 * icon: 'menu',
11061 * popup: {
11062 * $content: $( '<p>List of categories...</p>' ),
11063 * padded: true,
11064 * align: 'left'
11065 * }
11066 * } );
11067 * var button2 = new OO.ui.ButtonWidget( {
11068 * label: 'Add item'
11069 * });
11070 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
11071 * items: [button1, button2]
11072 * } );
11073 * $( 'body' ).append( buttonGroup.$element );
11074 *
11075 * @class
11076 * @extends OO.ui.Widget
11077 * @mixins OO.ui.GroupElement
11078 *
11079 * @constructor
11080 * @param {Object} [config] Configuration options
11081 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
11082 */
11083 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
11084 // Configuration initialization
11085 config = config || {};
11086
11087 // Parent constructor
11088 OO.ui.ButtonGroupWidget.super.call( this, config );
11089
11090 // Mixin constructors
11091 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11092
11093 // Initialization
11094 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
11095 if ( Array.isArray( config.items ) ) {
11096 this.addItems( config.items );
11097 }
11098 };
11099
11100 /* Setup */
11101
11102 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
11103 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
11104
11105 /**
11106 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
11107 * feels, and functionality can be customized via the class’s configuration options
11108 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11109 * and examples.
11110 *
11111 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
11112 *
11113 * @example
11114 * // A button widget
11115 * var button = new OO.ui.ButtonWidget( {
11116 * label: 'Button with Icon',
11117 * icon: 'remove',
11118 * iconTitle: 'Remove'
11119 * } );
11120 * $( 'body' ).append( button.$element );
11121 *
11122 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
11123 *
11124 * @class
11125 * @extends OO.ui.Widget
11126 * @mixins OO.ui.ButtonElement
11127 * @mixins OO.ui.IconElement
11128 * @mixins OO.ui.IndicatorElement
11129 * @mixins OO.ui.LabelElement
11130 * @mixins OO.ui.TitledElement
11131 * @mixins OO.ui.FlaggedElement
11132 * @mixins OO.ui.TabIndexedElement
11133 *
11134 * @constructor
11135 * @param {Object} [config] Configuration options
11136 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
11137 * @cfg {string} [target] The frame or window in which to open the hyperlink.
11138 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
11139 */
11140 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
11141 // Configuration initialization
11142 config = config || {};
11143
11144 // Parent constructor
11145 OO.ui.ButtonWidget.super.call( this, config );
11146
11147 // Mixin constructors
11148 OO.ui.ButtonElement.call( this, config );
11149 OO.ui.IconElement.call( this, config );
11150 OO.ui.IndicatorElement.call( this, config );
11151 OO.ui.LabelElement.call( this, config );
11152 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
11153 OO.ui.FlaggedElement.call( this, config );
11154 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
11155
11156 // Properties
11157 this.href = null;
11158 this.target = null;
11159 this.noFollow = false;
11160
11161 // Events
11162 this.connect( this, { disable: 'onDisable' } );
11163
11164 // Initialization
11165 this.$button.append( this.$icon, this.$label, this.$indicator );
11166 this.$element
11167 .addClass( 'oo-ui-buttonWidget' )
11168 .append( this.$button );
11169 this.setHref( config.href );
11170 this.setTarget( config.target );
11171 this.setNoFollow( config.noFollow );
11172 };
11173
11174 /* Setup */
11175
11176 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
11177 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
11178 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
11179 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
11180 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
11181 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
11182 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
11183 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
11184
11185 /* Methods */
11186
11187 /**
11188 * @inheritdoc
11189 */
11190 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
11191 if ( !this.isDisabled() ) {
11192 // Remove the tab-index while the button is down to prevent the button from stealing focus
11193 this.$button.removeAttr( 'tabindex' );
11194 }
11195
11196 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
11197 };
11198
11199 /**
11200 * @inheritdoc
11201 */
11202 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
11203 if ( !this.isDisabled() ) {
11204 // Restore the tab-index after the button is up to restore the button's accessibility
11205 this.$button.attr( 'tabindex', this.tabIndex );
11206 }
11207
11208 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
11209 };
11210
11211 /**
11212 * @inheritdoc
11213 */
11214 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
11215 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
11216 if ( this.href ) {
11217 return true;
11218 }
11219 return ret;
11220 };
11221
11222 /**
11223 * @inheritdoc
11224 */
11225 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
11226 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
11227 if ( this.href ) {
11228 return true;
11229 }
11230 return ret;
11231 };
11232
11233 /**
11234 * Get hyperlink location.
11235 *
11236 * @return {string} Hyperlink location
11237 */
11238 OO.ui.ButtonWidget.prototype.getHref = function () {
11239 return this.href;
11240 };
11241
11242 /**
11243 * Get hyperlink target.
11244 *
11245 * @return {string} Hyperlink target
11246 */
11247 OO.ui.ButtonWidget.prototype.getTarget = function () {
11248 return this.target;
11249 };
11250
11251 /**
11252 * Get search engine traversal hint.
11253 *
11254 * @return {boolean} Whether search engines should avoid traversing this hyperlink
11255 */
11256 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
11257 return this.noFollow;
11258 };
11259
11260 /**
11261 * Set hyperlink location.
11262 *
11263 * @param {string|null} href Hyperlink location, null to remove
11264 */
11265 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
11266 href = typeof href === 'string' ? href : null;
11267
11268 if ( href !== this.href ) {
11269 this.href = href;
11270 this.updateHref();
11271 }
11272
11273 return this;
11274 };
11275
11276 /**
11277 * Update the `href` attribute, in case of changes to href or
11278 * disabled state.
11279 *
11280 * @private
11281 * @chainable
11282 */
11283 OO.ui.ButtonWidget.prototype.updateHref = function () {
11284 if ( this.href !== null && !this.isDisabled() ) {
11285 this.$button.attr( 'href', this.href );
11286 } else {
11287 this.$button.removeAttr( 'href' );
11288 }
11289
11290 return this;
11291 };
11292
11293 /**
11294 * Handle disable events.
11295 *
11296 * @private
11297 * @param {boolean} disabled Element is disabled
11298 */
11299 OO.ui.ButtonWidget.prototype.onDisable = function () {
11300 this.updateHref();
11301 };
11302
11303 /**
11304 * Set hyperlink target.
11305 *
11306 * @param {string|null} target Hyperlink target, null to remove
11307 */
11308 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
11309 target = typeof target === 'string' ? target : null;
11310
11311 if ( target !== this.target ) {
11312 this.target = target;
11313 if ( target !== null ) {
11314 this.$button.attr( 'target', target );
11315 } else {
11316 this.$button.removeAttr( 'target' );
11317 }
11318 }
11319
11320 return this;
11321 };
11322
11323 /**
11324 * Set search engine traversal hint.
11325 *
11326 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
11327 */
11328 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
11329 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
11330
11331 if ( noFollow !== this.noFollow ) {
11332 this.noFollow = noFollow;
11333 if ( noFollow ) {
11334 this.$button.attr( 'rel', 'nofollow' );
11335 } else {
11336 this.$button.removeAttr( 'rel' );
11337 }
11338 }
11339
11340 return this;
11341 };
11342
11343 /**
11344 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
11345 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
11346 * of the actions.
11347 *
11348 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
11349 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11350 * and examples.
11351 *
11352 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
11353 *
11354 * @class
11355 * @extends OO.ui.ButtonWidget
11356 * @mixins OO.ui.PendingElement
11357 *
11358 * @constructor
11359 * @param {Object} [config] Configuration options
11360 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
11361 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
11362 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
11363 * for more information about setting modes.
11364 * @cfg {boolean} [framed=false] Render the action button with a frame
11365 */
11366 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
11367 // Configuration initialization
11368 config = $.extend( { framed: false }, config );
11369
11370 // Parent constructor
11371 OO.ui.ActionWidget.super.call( this, config );
11372
11373 // Mixin constructors
11374 OO.ui.PendingElement.call( this, config );
11375
11376 // Properties
11377 this.action = config.action || '';
11378 this.modes = config.modes || [];
11379 this.width = 0;
11380 this.height = 0;
11381
11382 // Initialization
11383 this.$element.addClass( 'oo-ui-actionWidget' );
11384 };
11385
11386 /* Setup */
11387
11388 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
11389 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
11390
11391 /* Events */
11392
11393 /**
11394 * A resize event is emitted when the size of the widget changes.
11395 *
11396 * @event resize
11397 */
11398
11399 /* Methods */
11400
11401 /**
11402 * Check if the action is configured to be available in the specified `mode`.
11403 *
11404 * @param {string} mode Name of mode
11405 * @return {boolean} The action is configured with the mode
11406 */
11407 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
11408 return this.modes.indexOf( mode ) !== -1;
11409 };
11410
11411 /**
11412 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
11413 *
11414 * @return {string}
11415 */
11416 OO.ui.ActionWidget.prototype.getAction = function () {
11417 return this.action;
11418 };
11419
11420 /**
11421 * Get the symbolic name of the mode or modes for which the action is configured to be available.
11422 *
11423 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
11424 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
11425 * are hidden.
11426 *
11427 * @return {string[]}
11428 */
11429 OO.ui.ActionWidget.prototype.getModes = function () {
11430 return this.modes.slice();
11431 };
11432
11433 /**
11434 * Emit a resize event if the size has changed.
11435 *
11436 * @private
11437 * @chainable
11438 */
11439 OO.ui.ActionWidget.prototype.propagateResize = function () {
11440 var width, height;
11441
11442 if ( this.isElementAttached() ) {
11443 width = this.$element.width();
11444 height = this.$element.height();
11445
11446 if ( width !== this.width || height !== this.height ) {
11447 this.width = width;
11448 this.height = height;
11449 this.emit( 'resize' );
11450 }
11451 }
11452
11453 return this;
11454 };
11455
11456 /**
11457 * @inheritdoc
11458 */
11459 OO.ui.ActionWidget.prototype.setIcon = function () {
11460 // Mixin method
11461 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
11462 this.propagateResize();
11463
11464 return this;
11465 };
11466
11467 /**
11468 * @inheritdoc
11469 */
11470 OO.ui.ActionWidget.prototype.setLabel = function () {
11471 // Mixin method
11472 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
11473 this.propagateResize();
11474
11475 return this;
11476 };
11477
11478 /**
11479 * @inheritdoc
11480 */
11481 OO.ui.ActionWidget.prototype.setFlags = function () {
11482 // Mixin method
11483 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
11484 this.propagateResize();
11485
11486 return this;
11487 };
11488
11489 /**
11490 * @inheritdoc
11491 */
11492 OO.ui.ActionWidget.prototype.clearFlags = function () {
11493 // Mixin method
11494 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
11495 this.propagateResize();
11496
11497 return this;
11498 };
11499
11500 /**
11501 * Toggle the visibility of the action button.
11502 *
11503 * @param {boolean} [show] Show button, omit to toggle visibility
11504 * @chainable
11505 */
11506 OO.ui.ActionWidget.prototype.toggle = function () {
11507 // Parent method
11508 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
11509 this.propagateResize();
11510
11511 return this;
11512 };
11513
11514 /**
11515 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
11516 * which is used to display additional information or options.
11517 *
11518 * @example
11519 * // Example of a popup button.
11520 * var popupButton = new OO.ui.PopupButtonWidget( {
11521 * label: 'Popup button with options',
11522 * icon: 'menu',
11523 * popup: {
11524 * $content: $( '<p>Additional options here.</p>' ),
11525 * padded: true,
11526 * align: 'force-left'
11527 * }
11528 * } );
11529 * // Append the button to the DOM.
11530 * $( 'body' ).append( popupButton.$element );
11531 *
11532 * @class
11533 * @extends OO.ui.ButtonWidget
11534 * @mixins OO.ui.PopupElement
11535 *
11536 * @constructor
11537 * @param {Object} [config] Configuration options
11538 */
11539 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
11540 // Parent constructor
11541 OO.ui.PopupButtonWidget.super.call( this, config );
11542
11543 // Mixin constructors
11544 OO.ui.PopupElement.call( this, config );
11545
11546 // Events
11547 this.connect( this, { click: 'onAction' } );
11548
11549 // Initialization
11550 this.$element
11551 .addClass( 'oo-ui-popupButtonWidget' )
11552 .attr( 'aria-haspopup', 'true' )
11553 .append( this.popup.$element );
11554 };
11555
11556 /* Setup */
11557
11558 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
11559 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
11560
11561 /* Methods */
11562
11563 /**
11564 * Handle the button action being triggered.
11565 *
11566 * @private
11567 */
11568 OO.ui.PopupButtonWidget.prototype.onAction = function () {
11569 this.popup.toggle();
11570 };
11571
11572 /**
11573 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
11574 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
11575 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
11576 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
11577 * and {@link OO.ui.LabelElement labels}. Please see
11578 * the [OOjs UI documentation][1] on MediaWiki for more information.
11579 *
11580 * @example
11581 * // Toggle buttons in the 'off' and 'on' state.
11582 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
11583 * label: 'Toggle Button off'
11584 * } );
11585 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
11586 * label: 'Toggle Button on',
11587 * value: true
11588 * } );
11589 * // Append the buttons to the DOM.
11590 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
11591 *
11592 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
11593 *
11594 * @class
11595 * @extends OO.ui.ToggleWidget
11596 * @mixins OO.ui.ButtonElement
11597 * @mixins OO.ui.IconElement
11598 * @mixins OO.ui.IndicatorElement
11599 * @mixins OO.ui.LabelElement
11600 * @mixins OO.ui.TitledElement
11601 * @mixins OO.ui.FlaggedElement
11602 * @mixins OO.ui.TabIndexedElement
11603 *
11604 * @constructor
11605 * @param {Object} [config] Configuration options
11606 * @cfg {boolean} [value=false] The toggle button’s initial on/off
11607 * state. By default, the button is in the 'off' state.
11608 */
11609 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
11610 // Configuration initialization
11611 config = config || {};
11612
11613 // Parent constructor
11614 OO.ui.ToggleButtonWidget.super.call( this, config );
11615
11616 // Mixin constructors
11617 OO.ui.ButtonElement.call( this, config );
11618 OO.ui.IconElement.call( this, config );
11619 OO.ui.IndicatorElement.call( this, config );
11620 OO.ui.LabelElement.call( this, config );
11621 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
11622 OO.ui.FlaggedElement.call( this, config );
11623 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
11624
11625 // Events
11626 this.connect( this, { click: 'onAction' } );
11627
11628 // Initialization
11629 this.$button.append( this.$icon, this.$label, this.$indicator );
11630 this.$element
11631 .addClass( 'oo-ui-toggleButtonWidget' )
11632 .append( this.$button );
11633 };
11634
11635 /* Setup */
11636
11637 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
11638 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonElement );
11639 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.IconElement );
11640 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.IndicatorElement );
11641 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.LabelElement );
11642 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.TitledElement );
11643 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.FlaggedElement );
11644 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.TabIndexedElement );
11645
11646 /* Methods */
11647
11648 /**
11649 * Handle the button action being triggered.
11650 *
11651 * @private
11652 */
11653 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
11654 this.setValue( !this.value );
11655 };
11656
11657 /**
11658 * @inheritdoc
11659 */
11660 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
11661 value = !!value;
11662 if ( value !== this.value ) {
11663 // Might be called from parent constructor before ButtonElement constructor
11664 if ( this.$button ) {
11665 this.$button.attr( 'aria-pressed', value.toString() );
11666 }
11667 this.setActive( value );
11668 }
11669
11670 // Parent method
11671 OO.ui.ToggleButtonWidget.super.prototype.setValue.call( this, value );
11672
11673 return this;
11674 };
11675
11676 /**
11677 * @inheritdoc
11678 */
11679 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
11680 if ( this.$button ) {
11681 this.$button.removeAttr( 'aria-pressed' );
11682 }
11683 OO.ui.ButtonElement.prototype.setButtonElement.call( this, $button );
11684 this.$button.attr( 'aria-pressed', this.value.toString() );
11685 };
11686
11687 /**
11688 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
11689 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
11690 * users can interact with it.
11691 *
11692 * @example
11693 * // Example: A DropdownWidget with a menu that contains three options
11694 * var dropDown = new OO.ui.DropdownWidget( {
11695 * label: 'Dropdown menu: Select a menu option',
11696 * menu: {
11697 * items: [
11698 * new OO.ui.MenuOptionWidget( {
11699 * data: 'a',
11700 * label: 'First'
11701 * } ),
11702 * new OO.ui.MenuOptionWidget( {
11703 * data: 'b',
11704 * label: 'Second'
11705 * } ),
11706 * new OO.ui.MenuOptionWidget( {
11707 * data: 'c',
11708 * label: 'Third'
11709 * } )
11710 * ]
11711 * }
11712 * } );
11713 *
11714 * $( 'body' ).append( dropDown.$element );
11715 *
11716 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
11717 *
11718 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11719 *
11720 * @class
11721 * @extends OO.ui.Widget
11722 * @mixins OO.ui.IconElement
11723 * @mixins OO.ui.IndicatorElement
11724 * @mixins OO.ui.LabelElement
11725 * @mixins OO.ui.TitledElement
11726 * @mixins OO.ui.TabIndexedElement
11727 *
11728 * @constructor
11729 * @param {Object} [config] Configuration options
11730 * @cfg {Object} [menu] Configuration options to pass to menu widget
11731 */
11732 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
11733 // Configuration initialization
11734 config = $.extend( { indicator: 'down' }, config );
11735
11736 // Parent constructor
11737 OO.ui.DropdownWidget.super.call( this, config );
11738
11739 // Properties (must be set before TabIndexedElement constructor call)
11740 this.$handle = this.$( '<span>' );
11741
11742 // Mixin constructors
11743 OO.ui.IconElement.call( this, config );
11744 OO.ui.IndicatorElement.call( this, config );
11745 OO.ui.LabelElement.call( this, config );
11746 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11747 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11748
11749 // Properties
11750 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
11751
11752 // Events
11753 this.$handle.on( {
11754 click: this.onClick.bind( this ),
11755 keypress: this.onKeyPress.bind( this )
11756 } );
11757 this.menu.connect( this, { select: 'onMenuSelect' } );
11758
11759 // Initialization
11760 this.$handle
11761 .addClass( 'oo-ui-dropdownWidget-handle' )
11762 .append( this.$icon, this.$label, this.$indicator );
11763 this.$element
11764 .addClass( 'oo-ui-dropdownWidget' )
11765 .append( this.$handle, this.menu.$element );
11766 };
11767
11768 /* Setup */
11769
11770 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
11771 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
11772 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
11773 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
11774 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
11775 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
11776
11777 /* Methods */
11778
11779 /**
11780 * Get the menu.
11781 *
11782 * @return {OO.ui.MenuSelectWidget} Menu of widget
11783 */
11784 OO.ui.DropdownWidget.prototype.getMenu = function () {
11785 return this.menu;
11786 };
11787
11788 /**
11789 * Handles menu select events.
11790 *
11791 * @private
11792 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11793 */
11794 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
11795 var selectedLabel;
11796
11797 if ( !item ) {
11798 return;
11799 }
11800
11801 selectedLabel = item.getLabel();
11802
11803 // If the label is a DOM element, clone it, because setLabel will append() it
11804 if ( selectedLabel instanceof jQuery ) {
11805 selectedLabel = selectedLabel.clone();
11806 }
11807
11808 this.setLabel( selectedLabel );
11809 };
11810
11811 /**
11812 * Handle mouse click events.
11813 *
11814 * @private
11815 * @param {jQuery.Event} e Mouse click event
11816 */
11817 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
11818 if ( !this.isDisabled() && e.which === 1 ) {
11819 this.menu.toggle();
11820 }
11821 return false;
11822 };
11823
11824 /**
11825 * Handle key press events.
11826 *
11827 * @private
11828 * @param {jQuery.Event} e Key press event
11829 */
11830 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
11831 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
11832 this.menu.toggle();
11833 return false;
11834 }
11835 };
11836
11837 /**
11838 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
11839 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
11840 * for a list of icons included in the library.
11841 *
11842 * @example
11843 * // An icon widget with a label
11844 * var myIcon = new OO.ui.IconWidget( {
11845 * icon: 'help',
11846 * iconTitle: 'Help'
11847 * } );
11848 * // Create a label.
11849 * var iconLabel = new OO.ui.LabelWidget( {
11850 * label: 'Help'
11851 * } );
11852 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
11853 *
11854 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
11855 *
11856 * @class
11857 * @extends OO.ui.Widget
11858 * @mixins OO.ui.IconElement
11859 * @mixins OO.ui.TitledElement
11860 * @mixins OO.ui.FlaggedElement
11861 *
11862 * @constructor
11863 * @param {Object} [config] Configuration options
11864 */
11865 OO.ui.IconWidget = function OoUiIconWidget( config ) {
11866 // Configuration initialization
11867 config = config || {};
11868
11869 // Parent constructor
11870 OO.ui.IconWidget.super.call( this, config );
11871
11872 // Mixin constructors
11873 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
11874 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11875 OO.ui.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
11876
11877 // Initialization
11878 this.$element.addClass( 'oo-ui-iconWidget' );
11879 };
11880
11881 /* Setup */
11882
11883 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
11884 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
11885 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
11886 OO.mixinClass( OO.ui.IconWidget, OO.ui.FlaggedElement );
11887
11888 /* Static Properties */
11889
11890 OO.ui.IconWidget.static.tagName = 'span';
11891
11892 /**
11893 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11894 * attention to the status of an item or to clarify the function of a control. For a list of
11895 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11896 *
11897 * @example
11898 * // Example of an indicator widget
11899 * var indicator1 = new OO.ui.IndicatorWidget( {
11900 * indicator: 'alert'
11901 * } );
11902 *
11903 * // Create a fieldset layout to add a label
11904 * var fieldset = new OO.ui.FieldsetLayout();
11905 * fieldset.addItems( [
11906 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
11907 * ] );
11908 * $( 'body' ).append( fieldset.$element );
11909 *
11910 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
11911 *
11912 * @class
11913 * @extends OO.ui.Widget
11914 * @mixins OO.ui.IndicatorElement
11915 * @mixins OO.ui.TitledElement
11916 *
11917 * @constructor
11918 * @param {Object} [config] Configuration options
11919 */
11920 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
11921 // Configuration initialization
11922 config = config || {};
11923
11924 // Parent constructor
11925 OO.ui.IndicatorWidget.super.call( this, config );
11926
11927 // Mixin constructors
11928 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
11929 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11930
11931 // Initialization
11932 this.$element.addClass( 'oo-ui-indicatorWidget' );
11933 };
11934
11935 /* Setup */
11936
11937 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
11938 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
11939 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
11940
11941 /* Static Properties */
11942
11943 OO.ui.IndicatorWidget.static.tagName = 'span';
11944
11945 /**
11946 * InputWidget is the base class for all input widgets, which
11947 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11948 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11949 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11950 *
11951 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11952 *
11953 * @abstract
11954 * @class
11955 * @extends OO.ui.Widget
11956 * @mixins OO.ui.FlaggedElement
11957 * @mixins OO.ui.TabIndexedElement
11958 *
11959 * @constructor
11960 * @param {Object} [config] Configuration options
11961 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11962 * @cfg {string} [value=''] The value of the input.
11963 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11964 * before it is accepted.
11965 */
11966 OO.ui.InputWidget = function OoUiInputWidget( config ) {
11967 // Configuration initialization
11968 config = config || {};
11969
11970 // Parent constructor
11971 OO.ui.InputWidget.super.call( this, config );
11972
11973 // Properties
11974 this.$input = this.getInputElement( config );
11975 this.value = '';
11976 this.inputFilter = config.inputFilter;
11977
11978 // Mixin constructors
11979 OO.ui.FlaggedElement.call( this, config );
11980 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
11981
11982 // Events
11983 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
11984
11985 // Initialization
11986 this.$input
11987 .attr( 'name', config.name )
11988 .prop( 'disabled', this.isDisabled() );
11989 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
11990 this.setValue( config.value );
11991 };
11992
11993 /* Setup */
11994
11995 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
11996 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
11997 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
11998
11999 /* Events */
12000
12001 /**
12002 * @event change
12003 *
12004 * A change event is emitted when the value of the input changes.
12005 *
12006 * @param {string} value
12007 */
12008
12009 /* Methods */
12010
12011 /**
12012 * Get input element.
12013 *
12014 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
12015 * different circumstances. The element must have a `value` property (like form elements).
12016 *
12017 * @private
12018 * @param {Object} config Configuration options
12019 * @return {jQuery} Input element
12020 */
12021 OO.ui.InputWidget.prototype.getInputElement = function () {
12022 return $( '<input>' );
12023 };
12024
12025 /**
12026 * Handle potentially value-changing events.
12027 *
12028 * @private
12029 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
12030 */
12031 OO.ui.InputWidget.prototype.onEdit = function () {
12032 var widget = this;
12033 if ( !this.isDisabled() ) {
12034 // Allow the stack to clear so the value will be updated
12035 setTimeout( function () {
12036 widget.setValue( widget.$input.val() );
12037 } );
12038 }
12039 };
12040
12041 /**
12042 * Get the value of the input.
12043 *
12044 * @return {string} Input value
12045 */
12046 OO.ui.InputWidget.prototype.getValue = function () {
12047 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
12048 // it, and we won't know unless they're kind enough to trigger a 'change' event.
12049 var value = this.$input.val();
12050 if ( this.value !== value ) {
12051 this.setValue( value );
12052 }
12053 return this.value;
12054 };
12055
12056 /**
12057 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
12058 *
12059 * @param {boolean} isRTL
12060 * Direction is right-to-left
12061 */
12062 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
12063 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
12064 };
12065
12066 /**
12067 * Set the value of the input.
12068 *
12069 * @param {string} value New value
12070 * @fires change
12071 * @chainable
12072 */
12073 OO.ui.InputWidget.prototype.setValue = function ( value ) {
12074 value = this.cleanUpValue( value );
12075 // Update the DOM if it has changed. Note that with cleanUpValue, it
12076 // is possible for the DOM value to change without this.value changing.
12077 if ( this.$input.val() !== value ) {
12078 this.$input.val( value );
12079 }
12080 if ( this.value !== value ) {
12081 this.value = value;
12082 this.emit( 'change', this.value );
12083 }
12084 return this;
12085 };
12086
12087 /**
12088 * Clean up incoming value.
12089 *
12090 * Ensures value is a string, and converts undefined and null to empty string.
12091 *
12092 * @private
12093 * @param {string} value Original value
12094 * @return {string} Cleaned up value
12095 */
12096 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
12097 if ( value === undefined || value === null ) {
12098 return '';
12099 } else if ( this.inputFilter ) {
12100 return this.inputFilter( String( value ) );
12101 } else {
12102 return String( value );
12103 }
12104 };
12105
12106 /**
12107 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
12108 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
12109 * called directly.
12110 */
12111 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
12112 if ( !this.isDisabled() ) {
12113 if ( this.$input.is( ':checkbox, :radio' ) ) {
12114 this.$input.click();
12115 }
12116 if ( this.$input.is( ':input' ) ) {
12117 this.$input[ 0 ].focus();
12118 }
12119 }
12120 };
12121
12122 /**
12123 * @inheritdoc
12124 */
12125 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
12126 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
12127 if ( this.$input ) {
12128 this.$input.prop( 'disabled', this.isDisabled() );
12129 }
12130 return this;
12131 };
12132
12133 /**
12134 * Focus the input.
12135 *
12136 * @chainable
12137 */
12138 OO.ui.InputWidget.prototype.focus = function () {
12139 this.$input[ 0 ].focus();
12140 return this;
12141 };
12142
12143 /**
12144 * Blur the input.
12145 *
12146 * @chainable
12147 */
12148 OO.ui.InputWidget.prototype.blur = function () {
12149 this.$input[ 0 ].blur();
12150 return this;
12151 };
12152
12153 /**
12154 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
12155 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
12156 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
12157 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
12158 * [OOjs UI documentation on MediaWiki] [1] for more information.
12159 *
12160 * @example
12161 * // A ButtonInputWidget rendered as an HTML button, the default.
12162 * var button = new OO.ui.ButtonInputWidget( {
12163 * label: 'Input button',
12164 * icon: 'check',
12165 * value: 'check'
12166 * } );
12167 * $( 'body' ).append( button.$element );
12168 *
12169 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
12170 *
12171 * @class
12172 * @extends OO.ui.InputWidget
12173 * @mixins OO.ui.ButtonElement
12174 * @mixins OO.ui.IconElement
12175 * @mixins OO.ui.IndicatorElement
12176 * @mixins OO.ui.LabelElement
12177 * @mixins OO.ui.TitledElement
12178 *
12179 * @constructor
12180 * @param {Object} [config] Configuration options
12181 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
12182 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
12183 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
12184 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
12185 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
12186 */
12187 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
12188 // Configuration initialization
12189 config = $.extend( { type: 'button', useInputTag: false }, config );
12190
12191 // Properties (must be set before parent constructor, which calls #setValue)
12192 this.useInputTag = config.useInputTag;
12193
12194 // Parent constructor
12195 OO.ui.ButtonInputWidget.super.call( this, config );
12196
12197 // Mixin constructors
12198 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
12199 OO.ui.IconElement.call( this, config );
12200 OO.ui.IndicatorElement.call( this, config );
12201 OO.ui.LabelElement.call( this, config );
12202 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
12203
12204 // Initialization
12205 if ( !config.useInputTag ) {
12206 this.$input.append( this.$icon, this.$label, this.$indicator );
12207 }
12208 this.$element.addClass( 'oo-ui-buttonInputWidget' );
12209 };
12210
12211 /* Setup */
12212
12213 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
12214 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
12215 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
12216 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
12217 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
12218 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
12219
12220 /* Methods */
12221
12222 /**
12223 * @inheritdoc
12224 * @private
12225 */
12226 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
12227 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
12228 return $( html );
12229 };
12230
12231 /**
12232 * Set label value.
12233 *
12234 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
12235 *
12236 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
12237 * text, or `null` for no label
12238 * @chainable
12239 */
12240 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
12241 OO.ui.LabelElement.prototype.setLabel.call( this, label );
12242
12243 if ( this.useInputTag ) {
12244 if ( typeof label === 'function' ) {
12245 label = OO.ui.resolveMsg( label );
12246 }
12247 if ( label instanceof jQuery ) {
12248 label = label.text();
12249 }
12250 if ( !label ) {
12251 label = '';
12252 }
12253 this.$input.val( label );
12254 }
12255
12256 return this;
12257 };
12258
12259 /**
12260 * Set the value of the input.
12261 *
12262 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
12263 * they do not support {@link #value values}.
12264 *
12265 * @param {string} value New value
12266 * @chainable
12267 */
12268 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
12269 if ( !this.useInputTag ) {
12270 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
12271 }
12272 return this;
12273 };
12274
12275 /**
12276 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
12277 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
12278 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
12279 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
12280 *
12281 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12282 *
12283 * @example
12284 * // An example of selected, unselected, and disabled checkbox inputs
12285 * var checkbox1=new OO.ui.CheckboxInputWidget( {
12286 * value: 'a',
12287 * selected: true
12288 * } );
12289 * var checkbox2=new OO.ui.CheckboxInputWidget( {
12290 * value: 'b'
12291 * } );
12292 * var checkbox3=new OO.ui.CheckboxInputWidget( {
12293 * value:'c',
12294 * disabled: true
12295 * } );
12296 * // Create a fieldset layout with fields for each checkbox.
12297 * var fieldset = new OO.ui.FieldsetLayout( {
12298 * label: 'Checkboxes'
12299 * } );
12300 * fieldset.addItems( [
12301 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
12302 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
12303 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
12304 * ] );
12305 * $( 'body' ).append( fieldset.$element );
12306 *
12307 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12308 *
12309 * @class
12310 * @extends OO.ui.InputWidget
12311 *
12312 * @constructor
12313 * @param {Object} [config] Configuration options
12314 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
12315 */
12316 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
12317 // Configuration initialization
12318 config = config || {};
12319
12320 // Parent constructor
12321 OO.ui.CheckboxInputWidget.super.call( this, config );
12322
12323 // Initialization
12324 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
12325 this.setSelected( config.selected !== undefined ? config.selected : false );
12326 };
12327
12328 /* Setup */
12329
12330 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
12331
12332 /* Methods */
12333
12334 /**
12335 * @inheritdoc
12336 * @private
12337 */
12338 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
12339 return $( '<input type="checkbox" />' );
12340 };
12341
12342 /**
12343 * @inheritdoc
12344 */
12345 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
12346 var widget = this;
12347 if ( !this.isDisabled() ) {
12348 // Allow the stack to clear so the value will be updated
12349 setTimeout( function () {
12350 widget.setSelected( widget.$input.prop( 'checked' ) );
12351 } );
12352 }
12353 };
12354
12355 /**
12356 * Set selection state of this checkbox.
12357 *
12358 * @param {boolean} state `true` for selected
12359 * @chainable
12360 */
12361 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
12362 state = !!state;
12363 if ( this.selected !== state ) {
12364 this.selected = state;
12365 this.$input.prop( 'checked', this.selected );
12366 this.emit( 'change', this.selected );
12367 }
12368 return this;
12369 };
12370
12371 /**
12372 * Check if this checkbox is selected.
12373 *
12374 * @return {boolean} Checkbox is selected
12375 */
12376 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
12377 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
12378 // it, and we won't know unless they're kind enough to trigger a 'change' event.
12379 var selected = this.$input.prop( 'checked' );
12380 if ( this.selected !== selected ) {
12381 this.setSelected( selected );
12382 }
12383 return this.selected;
12384 };
12385
12386 /**
12387 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
12388 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
12389 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
12390 * more information about input widgets.
12391 *
12392 * @example
12393 * // Example: A DropdownInputWidget with three options
12394 * var dropDown = new OO.ui.DropdownInputWidget( {
12395 * label: 'Dropdown menu: Select a menu option',
12396 * options: [
12397 * { data: 'a', label: 'First' } ,
12398 * { data: 'b', label: 'Second'} ,
12399 * { data: 'c', label: 'Third' }
12400 * ]
12401 * } );
12402 * $( 'body' ).append( dropDown.$element );
12403 *
12404 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12405 *
12406 * @class
12407 * @extends OO.ui.InputWidget
12408 *
12409 * @constructor
12410 * @param {Object} [config] Configuration options
12411 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
12412 */
12413 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
12414 // Configuration initialization
12415 config = config || {};
12416
12417 // Properties (must be done before parent constructor which calls #setDisabled)
12418 this.dropdownWidget = new OO.ui.DropdownWidget();
12419
12420 // Parent constructor
12421 OO.ui.DropdownInputWidget.super.call( this, config );
12422
12423 // Events
12424 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
12425
12426 // Initialization
12427 this.setOptions( config.options || [] );
12428 this.$element
12429 .addClass( 'oo-ui-dropdownInputWidget' )
12430 .append( this.dropdownWidget.$element );
12431 };
12432
12433 /* Setup */
12434
12435 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
12436
12437 /* Methods */
12438
12439 /**
12440 * @inheritdoc
12441 * @private
12442 */
12443 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
12444 return $( '<input type="hidden">' );
12445 };
12446
12447 /**
12448 * Handles menu select events.
12449 *
12450 * @private
12451 * @param {OO.ui.MenuOptionWidget} item Selected menu item
12452 */
12453 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
12454 this.setValue( item.getData() );
12455 };
12456
12457 /**
12458 * @inheritdoc
12459 */
12460 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
12461 this.dropdownWidget.getMenu().selectItemByData( value );
12462 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
12463 return this;
12464 };
12465
12466 /**
12467 * @inheritdoc
12468 */
12469 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
12470 this.dropdownWidget.setDisabled( state );
12471 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
12472 return this;
12473 };
12474
12475 /**
12476 * Set the options available for this input.
12477 *
12478 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
12479 * @chainable
12480 */
12481 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
12482 var value = this.getValue();
12483
12484 // Rebuild the dropdown menu
12485 this.dropdownWidget.getMenu()
12486 .clearItems()
12487 .addItems( options.map( function ( opt ) {
12488 return new OO.ui.MenuOptionWidget( {
12489 data: opt.data,
12490 label: opt.label !== undefined ? opt.label : opt.data
12491 } );
12492 } ) );
12493
12494 // Restore the previous value, or reset to something sensible
12495 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
12496 // Previous value is still available, ensure consistency with the dropdown
12497 this.setValue( value );
12498 } else {
12499 // No longer valid, reset
12500 if ( options.length ) {
12501 this.setValue( options[ 0 ].data );
12502 }
12503 }
12504
12505 return this;
12506 };
12507
12508 /**
12509 * @inheritdoc
12510 */
12511 OO.ui.DropdownInputWidget.prototype.focus = function () {
12512 this.dropdownWidget.getMenu().toggle( true );
12513 return this;
12514 };
12515
12516 /**
12517 * @inheritdoc
12518 */
12519 OO.ui.DropdownInputWidget.prototype.blur = function () {
12520 this.dropdownWidget.getMenu().toggle( false );
12521 return this;
12522 };
12523
12524 /**
12525 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
12526 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
12527 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
12528 * please see the [OOjs UI documentation on MediaWiki][1].
12529 *
12530 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12531 *
12532 * @example
12533 * // An example of selected, unselected, and disabled radio inputs
12534 * var radio1 = new OO.ui.RadioInputWidget( {
12535 * value: 'a',
12536 * selected: true
12537 * } );
12538 * var radio2 = new OO.ui.RadioInputWidget( {
12539 * value: 'b'
12540 * } );
12541 * var radio3 = new OO.ui.RadioInputWidget( {
12542 * value: 'c',
12543 * disabled: true
12544 * } );
12545 * // Create a fieldset layout with fields for each radio button.
12546 * var fieldset = new OO.ui.FieldsetLayout( {
12547 * label: 'Radio inputs'
12548 * } );
12549 * fieldset.addItems( [
12550 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
12551 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
12552 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
12553 * ] );
12554 * $( 'body' ).append( fieldset.$element );
12555 *
12556 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12557 *
12558 * @class
12559 * @extends OO.ui.InputWidget
12560 *
12561 * @constructor
12562 * @param {Object} [config] Configuration options
12563 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
12564 */
12565 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
12566 // Configuration initialization
12567 config = config || {};
12568
12569 // Parent constructor
12570 OO.ui.RadioInputWidget.super.call( this, config );
12571
12572 // Initialization
12573 this.$element.addClass( 'oo-ui-radioInputWidget' );
12574 this.setSelected( config.selected !== undefined ? config.selected : false );
12575 };
12576
12577 /* Setup */
12578
12579 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
12580
12581 /* Methods */
12582
12583 /**
12584 * @inheritdoc
12585 * @private
12586 */
12587 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
12588 return $( '<input type="radio" />' );
12589 };
12590
12591 /**
12592 * @inheritdoc
12593 */
12594 OO.ui.RadioInputWidget.prototype.onEdit = function () {
12595 // RadioInputWidget doesn't track its state.
12596 };
12597
12598 /**
12599 * Set selection state of this radio button.
12600 *
12601 * @param {boolean} state `true` for selected
12602 * @chainable
12603 */
12604 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
12605 // RadioInputWidget doesn't track its state.
12606 this.$input.prop( 'checked', state );
12607 return this;
12608 };
12609
12610 /**
12611 * Check if this radio button is selected.
12612 *
12613 * @return {boolean} Radio is selected
12614 */
12615 OO.ui.RadioInputWidget.prototype.isSelected = function () {
12616 return this.$input.prop( 'checked' );
12617 };
12618
12619 /**
12620 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
12621 * size of the field as well as its presentation. In addition, these widgets can be configured
12622 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
12623 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
12624 * which modifies incoming values rather than validating them.
12625 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12626 *
12627 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12628 *
12629 * @example
12630 * // Example of a text input widget
12631 * var textInput = new OO.ui.TextInputWidget( {
12632 * value: 'Text input'
12633 * } )
12634 * $( 'body' ).append( textInput.$element );
12635 *
12636 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12637 *
12638 * @class
12639 * @extends OO.ui.InputWidget
12640 * @mixins OO.ui.IconElement
12641 * @mixins OO.ui.IndicatorElement
12642 * @mixins OO.ui.PendingElement
12643 * @mixins OO.ui.LabelElement
12644 *
12645 * @constructor
12646 * @param {Object} [config] Configuration options
12647 * @cfg {string} [type='text'] The value of the HTML `type` attribute
12648 * @cfg {string} [placeholder] Placeholder text
12649 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
12650 * instruct the browser to focus this widget.
12651 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
12652 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
12653 * @cfg {boolean} [multiline=false] Allow multiple lines of text
12654 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
12655 * Use the #maxRows config to specify a maximum number of displayed rows.
12656 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
12657 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
12658 * the value or placeholder text: `'before'` or `'after'`
12659 * @cfg {boolean} [required=false] Mark the field as required
12660 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
12661 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
12662 * (the value must contain only numbers); when RegExp, a regular expression that must match the
12663 * value for it to be considered valid; when Function, a function receiving the value as parameter
12664 * that must return true, or promise resolving to true, for it to be considered valid.
12665 */
12666 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
12667 // Configuration initialization
12668 config = $.extend( {
12669 type: 'text',
12670 labelPosition: 'after',
12671 maxRows: 10
12672 }, config );
12673
12674 // Parent constructor
12675 OO.ui.TextInputWidget.super.call( this, config );
12676
12677 // Mixin constructors
12678 OO.ui.IconElement.call( this, config );
12679 OO.ui.IndicatorElement.call( this, config );
12680 OO.ui.PendingElement.call( this, config );
12681 OO.ui.LabelElement.call( this, config );
12682
12683 // Properties
12684 this.readOnly = false;
12685 this.multiline = !!config.multiline;
12686 this.autosize = !!config.autosize;
12687 this.maxRows = config.maxRows;
12688 this.validate = null;
12689
12690 // Clone for resizing
12691 if ( this.autosize ) {
12692 this.$clone = this.$input
12693 .clone()
12694 .insertAfter( this.$input )
12695 .attr( 'aria-hidden', 'true' )
12696 .addClass( 'oo-ui-element-hidden' );
12697 }
12698
12699 this.setValidation( config.validate );
12700 this.setLabelPosition( config.labelPosition );
12701
12702 // Events
12703 this.$input.on( {
12704 keypress: this.onKeyPress.bind( this ),
12705 blur: this.setValidityFlag.bind( this )
12706 } );
12707 this.$input.one( {
12708 focus: this.onElementAttach.bind( this )
12709 } );
12710 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
12711 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
12712 this.on( 'labelChange', this.updatePosition.bind( this ) );
12713 this.connect( this, { change: 'onChange' } );
12714
12715 // Initialization
12716 this.$element
12717 .addClass( 'oo-ui-textInputWidget' )
12718 .append( this.$icon, this.$indicator );
12719 this.setReadOnly( !!config.readOnly );
12720 if ( config.placeholder ) {
12721 this.$input.attr( 'placeholder', config.placeholder );
12722 }
12723 if ( config.maxLength !== undefined ) {
12724 this.$input.attr( 'maxlength', config.maxLength );
12725 }
12726 if ( config.autofocus ) {
12727 this.$input.attr( 'autofocus', 'autofocus' );
12728 }
12729 if ( config.required ) {
12730 this.$input.attr( 'required', 'required' );
12731 }
12732 if ( this.label || config.autosize ) {
12733 this.installParentChangeDetector();
12734 }
12735 };
12736
12737 /* Setup */
12738
12739 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
12740 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
12741 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
12742 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
12743 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
12744
12745 /* Static properties */
12746
12747 OO.ui.TextInputWidget.static.validationPatterns = {
12748 'non-empty': /.+/,
12749 integer: /^\d+$/
12750 };
12751
12752 /* Events */
12753
12754 /**
12755 * An `enter` event is emitted when the user presses 'enter' inside the text box.
12756 *
12757 * Not emitted if the input is multiline.
12758 *
12759 * @event enter
12760 */
12761
12762 /* Methods */
12763
12764 /**
12765 * Handle icon mouse down events.
12766 *
12767 * @private
12768 * @param {jQuery.Event} e Mouse down event
12769 * @fires icon
12770 */
12771 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
12772 if ( e.which === 1 ) {
12773 this.$input[ 0 ].focus();
12774 return false;
12775 }
12776 };
12777
12778 /**
12779 * Handle indicator mouse down events.
12780 *
12781 * @private
12782 * @param {jQuery.Event} e Mouse down event
12783 * @fires indicator
12784 */
12785 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
12786 if ( e.which === 1 ) {
12787 this.$input[ 0 ].focus();
12788 return false;
12789 }
12790 };
12791
12792 /**
12793 * Handle key press events.
12794 *
12795 * @private
12796 * @param {jQuery.Event} e Key press event
12797 * @fires enter If enter key is pressed and input is not multiline
12798 */
12799 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
12800 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
12801 this.emit( 'enter', e );
12802 }
12803 };
12804
12805 /**
12806 * Handle element attach events.
12807 *
12808 * @private
12809 * @param {jQuery.Event} e Element attach event
12810 */
12811 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
12812 // Any previously calculated size is now probably invalid if we reattached elsewhere
12813 this.valCache = null;
12814 this.adjustSize();
12815 this.positionLabel();
12816 };
12817
12818 /**
12819 * Handle change events.
12820 *
12821 * @param {string} value
12822 * @private
12823 */
12824 OO.ui.TextInputWidget.prototype.onChange = function () {
12825 this.setValidityFlag();
12826 this.adjustSize();
12827 };
12828
12829 /**
12830 * Check if the input is {@link #readOnly read-only}.
12831 *
12832 * @return {boolean}
12833 */
12834 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
12835 return this.readOnly;
12836 };
12837
12838 /**
12839 * Set the {@link #readOnly read-only} state of the input.
12840 *
12841 * @param {boolean} state Make input read-only
12842 * @chainable
12843 */
12844 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
12845 this.readOnly = !!state;
12846 this.$input.prop( 'readOnly', this.readOnly );
12847 return this;
12848 };
12849
12850 /**
12851 * Support function for making #onElementAttach work across browsers.
12852 *
12853 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
12854 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
12855 *
12856 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
12857 * first time that the element gets attached to the documented.
12858 */
12859 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
12860 var mutationObserver, onRemove, topmostNode, fakeParentNode,
12861 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
12862 widget = this;
12863
12864 if ( MutationObserver ) {
12865 // The new way. If only it wasn't so ugly.
12866
12867 if ( this.$element.closest( 'html' ).length ) {
12868 // Widget is attached already, do nothing. This breaks the functionality of this function when
12869 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
12870 // would require observation of the whole document, which would hurt performance of other,
12871 // more important code.
12872 return;
12873 }
12874
12875 // Find topmost node in the tree
12876 topmostNode = this.$element[0];
12877 while ( topmostNode.parentNode ) {
12878 topmostNode = topmostNode.parentNode;
12879 }
12880
12881 // We have no way to detect the $element being attached somewhere without observing the entire
12882 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12883 // parent node of $element, and instead detect when $element is removed from it (and thus
12884 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12885 // doesn't get attached, we end up back here and create the parent.
12886
12887 mutationObserver = new MutationObserver( function ( mutations ) {
12888 var i, j, removedNodes;
12889 for ( i = 0; i < mutations.length; i++ ) {
12890 removedNodes = mutations[ i ].removedNodes;
12891 for ( j = 0; j < removedNodes.length; j++ ) {
12892 if ( removedNodes[ j ] === topmostNode ) {
12893 setTimeout( onRemove, 0 );
12894 return;
12895 }
12896 }
12897 }
12898 } );
12899
12900 onRemove = function () {
12901 // If the node was attached somewhere else, report it
12902 if ( widget.$element.closest( 'html' ).length ) {
12903 widget.onElementAttach();
12904 }
12905 mutationObserver.disconnect();
12906 widget.installParentChangeDetector();
12907 };
12908
12909 // Create a fake parent and observe it
12910 fakeParentNode = $( '<div>' ).append( this.$element )[0];
12911 mutationObserver.observe( fakeParentNode, { childList: true } );
12912 } else {
12913 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12914 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12915 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
12916 }
12917 };
12918
12919 /**
12920 * Automatically adjust the size of the text input.
12921 *
12922 * This only affects #multiline inputs that are {@link #autosize autosized}.
12923 *
12924 * @chainable
12925 */
12926 OO.ui.TextInputWidget.prototype.adjustSize = function () {
12927 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
12928
12929 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
12930 this.$clone
12931 .val( this.$input.val() )
12932 .attr( 'rows', '' )
12933 // Set inline height property to 0 to measure scroll height
12934 .css( 'height', 0 );
12935
12936 this.$clone.removeClass( 'oo-ui-element-hidden' );
12937
12938 this.valCache = this.$input.val();
12939
12940 scrollHeight = this.$clone[ 0 ].scrollHeight;
12941
12942 // Remove inline height property to measure natural heights
12943 this.$clone.css( 'height', '' );
12944 innerHeight = this.$clone.innerHeight();
12945 outerHeight = this.$clone.outerHeight();
12946
12947 // Measure max rows height
12948 this.$clone
12949 .attr( 'rows', this.maxRows )
12950 .css( 'height', 'auto' )
12951 .val( '' );
12952 maxInnerHeight = this.$clone.innerHeight();
12953
12954 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12955 // Equals 1 on Blink-based browsers and 0 everywhere else
12956 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
12957 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
12958
12959 this.$clone.addClass( 'oo-ui-element-hidden' );
12960
12961 // Only apply inline height when expansion beyond natural height is needed
12962 if ( idealHeight > innerHeight ) {
12963 // Use the difference between the inner and outer height as a buffer
12964 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
12965 } else {
12966 this.$input.css( 'height', '' );
12967 }
12968 }
12969 return this;
12970 };
12971
12972 /**
12973 * @inheritdoc
12974 * @private
12975 */
12976 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
12977 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
12978 };
12979
12980 /**
12981 * Check if the input supports multiple lines.
12982 *
12983 * @return {boolean}
12984 */
12985 OO.ui.TextInputWidget.prototype.isMultiline = function () {
12986 return !!this.multiline;
12987 };
12988
12989 /**
12990 * Check if the input automatically adjusts its size.
12991 *
12992 * @return {boolean}
12993 */
12994 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
12995 return !!this.autosize;
12996 };
12997
12998 /**
12999 * Select the entire text of the input.
13000 *
13001 * @chainable
13002 */
13003 OO.ui.TextInputWidget.prototype.select = function () {
13004 this.$input.select();
13005 return this;
13006 };
13007
13008 /**
13009 * Set the validation pattern.
13010 *
13011 * The validation pattern is either a regular expression, a function, or the symbolic name of a
13012 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
13013 * value must contain only numbers).
13014 *
13015 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
13016 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
13017 */
13018 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
13019 if ( validate instanceof RegExp || validate instanceof Function ) {
13020 this.validate = validate;
13021 } else {
13022 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
13023 }
13024 };
13025
13026 /**
13027 * Sets the 'invalid' flag appropriately.
13028 */
13029 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
13030 var widget = this;
13031 this.isValid().done( function ( valid ) {
13032 if ( !valid ) {
13033 widget.$input.attr( 'aria-invalid', 'true' );
13034 } else {
13035 widget.$input.removeAttr( 'aria-invalid' );
13036 }
13037 widget.setFlags( { invalid: !valid } );
13038 } );
13039 };
13040
13041 /**
13042 * Check if a value is valid.
13043 *
13044 * This method returns a promise that resolves with a boolean `true` if the current value is
13045 * considered valid according to the supplied {@link #validate validation pattern}.
13046 *
13047 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
13048 */
13049 OO.ui.TextInputWidget.prototype.isValid = function () {
13050 if ( this.validate instanceof Function ) {
13051 var result = this.validate( this.getValue() );
13052 if ( $.isFunction( result.promise ) ) {
13053 return result.promise();
13054 } else {
13055 return $.Deferred().resolve( !!result ).promise();
13056 }
13057 } else {
13058 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
13059 }
13060 };
13061
13062 /**
13063 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
13064 *
13065 * @param {string} labelPosition Label position, 'before' or 'after'
13066 * @chainable
13067 */
13068 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
13069 this.labelPosition = labelPosition;
13070 this.updatePosition();
13071 return this;
13072 };
13073
13074 /**
13075 * Deprecated alias of #setLabelPosition
13076 *
13077 * @deprecated Use setLabelPosition instead.
13078 */
13079 OO.ui.TextInputWidget.prototype.setPosition =
13080 OO.ui.TextInputWidget.prototype.setLabelPosition;
13081
13082 /**
13083 * Update the position of the inline label.
13084 *
13085 * This method is called by #setLabelPosition, and can also be called on its own if
13086 * something causes the label to be mispositioned.
13087 *
13088 *
13089 * @chainable
13090 */
13091 OO.ui.TextInputWidget.prototype.updatePosition = function () {
13092 var after = this.labelPosition === 'after';
13093
13094 this.$element
13095 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
13096 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
13097
13098 if ( this.label ) {
13099 this.positionLabel();
13100 }
13101
13102 return this;
13103 };
13104
13105 /**
13106 * Position the label by setting the correct padding on the input.
13107 *
13108 * @private
13109 * @chainable
13110 */
13111 OO.ui.TextInputWidget.prototype.positionLabel = function () {
13112 // Clear old values
13113 this.$input
13114 // Clear old values if present
13115 .css( {
13116 'padding-right': '',
13117 'padding-left': ''
13118 } );
13119
13120 if ( this.label ) {
13121 this.$element.append( this.$label );
13122 } else {
13123 this.$label.detach();
13124 return;
13125 }
13126
13127 var after = this.labelPosition === 'after',
13128 rtl = this.$element.css( 'direction' ) === 'rtl',
13129 property = after === rtl ? 'padding-left' : 'padding-right';
13130
13131 this.$input.css( property, this.$label.outerWidth( true ) );
13132
13133 return this;
13134 };
13135
13136 /**
13137 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
13138 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
13139 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
13140 *
13141 * - by typing a value in the text input field. If the value exactly matches the value of a menu
13142 * option, that option will appear to be selected.
13143 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
13144 * input field.
13145 *
13146 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13147 *
13148 * @example
13149 * // Example: A ComboBoxWidget.
13150 * var comboBox = new OO.ui.ComboBoxWidget( {
13151 * label: 'ComboBoxWidget',
13152 * input: { value: 'Option One' },
13153 * menu: {
13154 * items: [
13155 * new OO.ui.MenuOptionWidget( {
13156 * data: 'Option 1',
13157 * label: 'Option One'
13158 * } ),
13159 * new OO.ui.MenuOptionWidget( {
13160 * data: 'Option 2',
13161 * label: 'Option Two'
13162 * } ),
13163 * new OO.ui.MenuOptionWidget( {
13164 * data: 'Option 3',
13165 * label: 'Option Three'
13166 * } ),
13167 * new OO.ui.MenuOptionWidget( {
13168 * data: 'Option 4',
13169 * label: 'Option Four'
13170 * } ),
13171 * new OO.ui.MenuOptionWidget( {
13172 * data: 'Option 5',
13173 * label: 'Option Five'
13174 * } )
13175 * ]
13176 * }
13177 * } );
13178 * $( 'body' ).append( comboBox.$element );
13179 *
13180 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13181 *
13182 * @class
13183 * @extends OO.ui.Widget
13184 * @mixins OO.ui.TabIndexedElement
13185 *
13186 * @constructor
13187 * @param {Object} [config] Configuration options
13188 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13189 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
13190 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13191 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13192 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13193 */
13194 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
13195 // Configuration initialization
13196 config = config || {};
13197
13198 // Parent constructor
13199 OO.ui.ComboBoxWidget.super.call( this, config );
13200
13201 // Properties (must be set before TabIndexedElement constructor call)
13202 this.$indicator = this.$( '<span>' );
13203
13204 // Mixin constructors
13205 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13206
13207 // Properties
13208 this.$overlay = config.$overlay || this.$element;
13209 this.input = new OO.ui.TextInputWidget( $.extend(
13210 {
13211 indicator: 'down',
13212 $indicator: this.$indicator,
13213 disabled: this.isDisabled()
13214 },
13215 config.input
13216 ) );
13217 this.input.$input.eq( 0 ).attr( {
13218 role: 'combobox',
13219 'aria-autocomplete': 'list'
13220 } );
13221 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
13222 {
13223 widget: this,
13224 input: this.input,
13225 disabled: this.isDisabled()
13226 },
13227 config.menu
13228 ) );
13229
13230 // Events
13231 this.$indicator.on( {
13232 click: this.onClick.bind( this ),
13233 keypress: this.onKeyPress.bind( this )
13234 } );
13235 this.input.connect( this, {
13236 change: 'onInputChange',
13237 enter: 'onInputEnter'
13238 } );
13239 this.menu.connect( this, {
13240 choose: 'onMenuChoose',
13241 add: 'onMenuItemsChange',
13242 remove: 'onMenuItemsChange'
13243 } );
13244
13245 // Initialization
13246 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
13247 this.$overlay.append( this.menu.$element );
13248 this.onMenuItemsChange();
13249 };
13250
13251 /* Setup */
13252
13253 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
13254 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
13255
13256 /* Methods */
13257
13258 /**
13259 * Get the combobox's menu.
13260 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
13261 */
13262 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
13263 return this.menu;
13264 };
13265
13266 /**
13267 * Handle input change events.
13268 *
13269 * @private
13270 * @param {string} value New value
13271 */
13272 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
13273 var match = this.menu.getItemFromData( value );
13274
13275 this.menu.selectItem( match );
13276 if ( this.menu.getHighlightedItem() ) {
13277 this.menu.highlightItem( match );
13278 }
13279
13280 if ( !this.isDisabled() ) {
13281 this.menu.toggle( true );
13282 }
13283 };
13284
13285 /**
13286 * Handle mouse click events.
13287 *
13288 *
13289 * @private
13290 * @param {jQuery.Event} e Mouse click event
13291 */
13292 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
13293 if ( !this.isDisabled() && e.which === 1 ) {
13294 this.menu.toggle();
13295 this.input.$input[ 0 ].focus();
13296 }
13297 return false;
13298 };
13299
13300 /**
13301 * Handle key press events.
13302 *
13303 *
13304 * @private
13305 * @param {jQuery.Event} e Key press event
13306 */
13307 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
13308 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
13309 this.menu.toggle();
13310 this.input.$input[ 0 ].focus();
13311 return false;
13312 }
13313 };
13314
13315 /**
13316 * Handle input enter events.
13317 *
13318 * @private
13319 */
13320 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
13321 if ( !this.isDisabled() ) {
13322 this.menu.toggle( false );
13323 }
13324 };
13325
13326 /**
13327 * Handle menu choose events.
13328 *
13329 * @private
13330 * @param {OO.ui.OptionWidget} item Chosen item
13331 */
13332 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
13333 this.input.setValue( item.getData() );
13334 };
13335
13336 /**
13337 * Handle menu item change events.
13338 *
13339 * @private
13340 */
13341 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
13342 var match = this.menu.getItemFromData( this.input.getValue() );
13343 this.menu.selectItem( match );
13344 if ( this.menu.getHighlightedItem() ) {
13345 this.menu.highlightItem( match );
13346 }
13347 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
13348 };
13349
13350 /**
13351 * @inheritdoc
13352 */
13353 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
13354 // Parent method
13355 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
13356
13357 if ( this.input ) {
13358 this.input.setDisabled( this.isDisabled() );
13359 }
13360 if ( this.menu ) {
13361 this.menu.setDisabled( this.isDisabled() );
13362 }
13363
13364 return this;
13365 };
13366
13367 /**
13368 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
13369 * be configured with a `label` option that is set to a string, a label node, or a function:
13370 *
13371 * - String: a plaintext string
13372 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
13373 * label that includes a link or special styling, such as a gray color or additional graphical elements.
13374 * - Function: a function that will produce a string in the future. Functions are used
13375 * in cases where the value of the label is not currently defined.
13376 *
13377 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
13378 * will come into focus when the label is clicked.
13379 *
13380 * @example
13381 * // Examples of LabelWidgets
13382 * var label1 = new OO.ui.LabelWidget( {
13383 * label: 'plaintext label'
13384 * } );
13385 * var label2 = new OO.ui.LabelWidget( {
13386 * label: $( '<a href="default.html">jQuery label</a>' )
13387 * } );
13388 * // Create a fieldset layout with fields for each example
13389 * var fieldset = new OO.ui.FieldsetLayout();
13390 * fieldset.addItems( [
13391 * new OO.ui.FieldLayout( label1 ),
13392 * new OO.ui.FieldLayout( label2 )
13393 * ] );
13394 * $( 'body' ).append( fieldset.$element );
13395 *
13396 *
13397 * @class
13398 * @extends OO.ui.Widget
13399 * @mixins OO.ui.LabelElement
13400 *
13401 * @constructor
13402 * @param {Object} [config] Configuration options
13403 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
13404 * Clicking the label will focus the specified input field.
13405 */
13406 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
13407 // Configuration initialization
13408 config = config || {};
13409
13410 // Parent constructor
13411 OO.ui.LabelWidget.super.call( this, config );
13412
13413 // Mixin constructors
13414 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
13415 OO.ui.TitledElement.call( this, config );
13416
13417 // Properties
13418 this.input = config.input;
13419
13420 // Events
13421 if ( this.input instanceof OO.ui.InputWidget ) {
13422 this.$element.on( 'click', this.onClick.bind( this ) );
13423 }
13424
13425 // Initialization
13426 this.$element.addClass( 'oo-ui-labelWidget' );
13427 };
13428
13429 /* Setup */
13430
13431 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
13432 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
13433 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
13434
13435 /* Static Properties */
13436
13437 OO.ui.LabelWidget.static.tagName = 'span';
13438
13439 /* Methods */
13440
13441 /**
13442 * Handles label mouse click events.
13443 *
13444 * @private
13445 * @param {jQuery.Event} e Mouse click event
13446 */
13447 OO.ui.LabelWidget.prototype.onClick = function () {
13448 this.input.simulateLabelClick();
13449 return false;
13450 };
13451
13452 /**
13453 * OptionWidgets are special elements that can be selected and configured with data. The
13454 * data is often unique for each option, but it does not have to be. OptionWidgets are used
13455 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
13456 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
13457 *
13458 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13459 *
13460 * @class
13461 * @extends OO.ui.Widget
13462 * @mixins OO.ui.LabelElement
13463 * @mixins OO.ui.FlaggedElement
13464 *
13465 * @constructor
13466 * @param {Object} [config] Configuration options
13467 */
13468 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
13469 // Configuration initialization
13470 config = config || {};
13471
13472 // Parent constructor
13473 OO.ui.OptionWidget.super.call( this, config );
13474
13475 // Mixin constructors
13476 OO.ui.ItemWidget.call( this );
13477 OO.ui.LabelElement.call( this, config );
13478 OO.ui.FlaggedElement.call( this, config );
13479
13480 // Properties
13481 this.selected = false;
13482 this.highlighted = false;
13483 this.pressed = false;
13484
13485 // Initialization
13486 this.$element
13487 .data( 'oo-ui-optionWidget', this )
13488 .attr( 'role', 'option' )
13489 .addClass( 'oo-ui-optionWidget' )
13490 .append( this.$label );
13491 };
13492
13493 /* Setup */
13494
13495 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
13496 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
13497 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
13498 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
13499
13500 /* Static Properties */
13501
13502 OO.ui.OptionWidget.static.selectable = true;
13503
13504 OO.ui.OptionWidget.static.highlightable = true;
13505
13506 OO.ui.OptionWidget.static.pressable = true;
13507
13508 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
13509
13510 /* Methods */
13511
13512 /**
13513 * Check if the option can be selected.
13514 *
13515 * @return {boolean} Item is selectable
13516 */
13517 OO.ui.OptionWidget.prototype.isSelectable = function () {
13518 return this.constructor.static.selectable && !this.isDisabled();
13519 };
13520
13521 /**
13522 * Check if the option can be highlighted. A highlight indicates that the option
13523 * may be selected when a user presses enter or clicks. Disabled items cannot
13524 * be highlighted.
13525 *
13526 * @return {boolean} Item is highlightable
13527 */
13528 OO.ui.OptionWidget.prototype.isHighlightable = function () {
13529 return this.constructor.static.highlightable && !this.isDisabled();
13530 };
13531
13532 /**
13533 * Check if the option can be pressed. The pressed state occurs when a user mouses
13534 * down on an item, but has not yet let go of the mouse.
13535 *
13536 * @return {boolean} Item is pressable
13537 */
13538 OO.ui.OptionWidget.prototype.isPressable = function () {
13539 return this.constructor.static.pressable && !this.isDisabled();
13540 };
13541
13542 /**
13543 * Check if the option is selected.
13544 *
13545 * @return {boolean} Item is selected
13546 */
13547 OO.ui.OptionWidget.prototype.isSelected = function () {
13548 return this.selected;
13549 };
13550
13551 /**
13552 * Check if the option is highlighted. A highlight indicates that the
13553 * item may be selected when a user presses enter or clicks.
13554 *
13555 * @return {boolean} Item is highlighted
13556 */
13557 OO.ui.OptionWidget.prototype.isHighlighted = function () {
13558 return this.highlighted;
13559 };
13560
13561 /**
13562 * Check if the option is pressed. The pressed state occurs when a user mouses
13563 * down on an item, but has not yet let go of the mouse. The item may appear
13564 * selected, but it will not be selected until the user releases the mouse.
13565 *
13566 * @return {boolean} Item is pressed
13567 */
13568 OO.ui.OptionWidget.prototype.isPressed = function () {
13569 return this.pressed;
13570 };
13571
13572 /**
13573 * Set the option’s selected state. In general, all modifications to the selection
13574 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
13575 * method instead of this method.
13576 *
13577 * @param {boolean} [state=false] Select option
13578 * @chainable
13579 */
13580 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
13581 if ( this.constructor.static.selectable ) {
13582 this.selected = !!state;
13583 this.$element
13584 .toggleClass( 'oo-ui-optionWidget-selected', state )
13585 .attr( 'aria-selected', state.toString() );
13586 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
13587 this.scrollElementIntoView();
13588 }
13589 this.updateThemeClasses();
13590 }
13591 return this;
13592 };
13593
13594 /**
13595 * Set the option’s highlighted state. In general, all programmatic
13596 * modifications to the highlight should be handled by the
13597 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
13598 * method instead of this method.
13599 *
13600 * @param {boolean} [state=false] Highlight option
13601 * @chainable
13602 */
13603 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
13604 if ( this.constructor.static.highlightable ) {
13605 this.highlighted = !!state;
13606 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
13607 this.updateThemeClasses();
13608 }
13609 return this;
13610 };
13611
13612 /**
13613 * Set the option’s pressed state. In general, all
13614 * programmatic modifications to the pressed state should be handled by the
13615 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
13616 * method instead of this method.
13617 *
13618 * @param {boolean} [state=false] Press option
13619 * @chainable
13620 */
13621 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
13622 if ( this.constructor.static.pressable ) {
13623 this.pressed = !!state;
13624 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
13625 this.updateThemeClasses();
13626 }
13627 return this;
13628 };
13629
13630 /**
13631 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
13632 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
13633 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
13634 * options. For more information about options and selects, please see the
13635 * [OOjs UI documentation on MediaWiki][1].
13636 *
13637 * @example
13638 * // Decorated options in a select widget
13639 * var select = new OO.ui.SelectWidget( {
13640 * items: [
13641 * new OO.ui.DecoratedOptionWidget( {
13642 * data: 'a',
13643 * label: 'Option with icon',
13644 * icon: 'help'
13645 * } ),
13646 * new OO.ui.DecoratedOptionWidget( {
13647 * data: 'b',
13648 * label: 'Option with indicator',
13649 * indicator: 'next'
13650 * } )
13651 * ]
13652 * } );
13653 * $( 'body' ).append( select.$element );
13654 *
13655 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13656 *
13657 * @class
13658 * @extends OO.ui.OptionWidget
13659 * @mixins OO.ui.IconElement
13660 * @mixins OO.ui.IndicatorElement
13661 *
13662 * @constructor
13663 * @param {Object} [config] Configuration options
13664 */
13665 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
13666 // Parent constructor
13667 OO.ui.DecoratedOptionWidget.super.call( this, config );
13668
13669 // Mixin constructors
13670 OO.ui.IconElement.call( this, config );
13671 OO.ui.IndicatorElement.call( this, config );
13672
13673 // Initialization
13674 this.$element
13675 .addClass( 'oo-ui-decoratedOptionWidget' )
13676 .prepend( this.$icon )
13677 .append( this.$indicator );
13678 };
13679
13680 /* Setup */
13681
13682 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
13683 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
13684 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
13685
13686 /**
13687 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
13688 * can be selected and configured with data. The class is
13689 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
13690 * [OOjs UI documentation on MediaWiki] [1] for more information.
13691 *
13692 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
13693 *
13694 * @class
13695 * @extends OO.ui.DecoratedOptionWidget
13696 * @mixins OO.ui.ButtonElement
13697 * @mixins OO.ui.TabIndexedElement
13698 *
13699 * @constructor
13700 * @param {Object} [config] Configuration options
13701 */
13702 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
13703 // Configuration initialization
13704 config = $.extend( { tabIndex: -1 }, config );
13705
13706 // Parent constructor
13707 OO.ui.ButtonOptionWidget.super.call( this, config );
13708
13709 // Mixin constructors
13710 OO.ui.ButtonElement.call( this, config );
13711 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13712
13713 // Initialization
13714 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
13715 this.$button.append( this.$element.contents() );
13716 this.$element.append( this.$button );
13717 };
13718
13719 /* Setup */
13720
13721 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
13722 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
13723 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
13724
13725 /* Static Properties */
13726
13727 // Allow button mouse down events to pass through so they can be handled by the parent select widget
13728 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
13729
13730 OO.ui.ButtonOptionWidget.static.highlightable = false;
13731
13732 /* Methods */
13733
13734 /**
13735 * @inheritdoc
13736 */
13737 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
13738 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
13739
13740 if ( this.constructor.static.selectable ) {
13741 this.setActive( state );
13742 }
13743
13744 return this;
13745 };
13746
13747 /**
13748 * RadioOptionWidget is an option widget that looks like a radio button.
13749 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
13750 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
13751 *
13752 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
13753 *
13754 * @class
13755 * @extends OO.ui.OptionWidget
13756 *
13757 * @constructor
13758 * @param {Object} [config] Configuration options
13759 */
13760 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
13761 // Configuration initialization
13762 config = config || {};
13763
13764 // Properties (must be done before parent constructor which calls #setDisabled)
13765 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
13766
13767 // Parent constructor
13768 OO.ui.RadioOptionWidget.super.call( this, config );
13769
13770 // Initialization
13771 this.$element
13772 .addClass( 'oo-ui-radioOptionWidget' )
13773 .prepend( this.radio.$element );
13774 };
13775
13776 /* Setup */
13777
13778 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
13779
13780 /* Static Properties */
13781
13782 OO.ui.RadioOptionWidget.static.highlightable = false;
13783
13784 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
13785
13786 OO.ui.RadioOptionWidget.static.pressable = false;
13787
13788 OO.ui.RadioOptionWidget.static.tagName = 'label';
13789
13790 /* Methods */
13791
13792 /**
13793 * @inheritdoc
13794 */
13795 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
13796 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
13797
13798 this.radio.setSelected( state );
13799
13800 return this;
13801 };
13802
13803 /**
13804 * @inheritdoc
13805 */
13806 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
13807 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
13808
13809 this.radio.setDisabled( this.isDisabled() );
13810
13811 return this;
13812 };
13813
13814 /**
13815 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
13816 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
13817 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13818 *
13819 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13820 *
13821 * @class
13822 * @extends OO.ui.DecoratedOptionWidget
13823 *
13824 * @constructor
13825 * @param {Object} [config] Configuration options
13826 */
13827 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
13828 // Configuration initialization
13829 config = $.extend( { icon: 'check' }, config );
13830
13831 // Parent constructor
13832 OO.ui.MenuOptionWidget.super.call( this, config );
13833
13834 // Initialization
13835 this.$element
13836 .attr( 'role', 'menuitem' )
13837 .addClass( 'oo-ui-menuOptionWidget' );
13838 };
13839
13840 /* Setup */
13841
13842 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
13843
13844 /* Static Properties */
13845
13846 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
13847
13848 /**
13849 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
13850 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
13851 *
13852 * @example
13853 * var myDropdown = new OO.ui.DropdownWidget( {
13854 * menu: {
13855 * items: [
13856 * new OO.ui.MenuSectionOptionWidget( {
13857 * label: 'Dogs'
13858 * } ),
13859 * new OO.ui.MenuOptionWidget( {
13860 * data: 'corgi',
13861 * label: 'Welsh Corgi'
13862 * } ),
13863 * new OO.ui.MenuOptionWidget( {
13864 * data: 'poodle',
13865 * label: 'Standard Poodle'
13866 * } ),
13867 * new OO.ui.MenuSectionOptionWidget( {
13868 * label: 'Cats'
13869 * } ),
13870 * new OO.ui.MenuOptionWidget( {
13871 * data: 'lion',
13872 * label: 'Lion'
13873 * } )
13874 * ]
13875 * }
13876 * } );
13877 * $( 'body' ).append( myDropdown.$element );
13878 *
13879 *
13880 * @class
13881 * @extends OO.ui.DecoratedOptionWidget
13882 *
13883 * @constructor
13884 * @param {Object} [config] Configuration options
13885 */
13886 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
13887 // Parent constructor
13888 OO.ui.MenuSectionOptionWidget.super.call( this, config );
13889
13890 // Initialization
13891 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
13892 };
13893
13894 /* Setup */
13895
13896 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
13897
13898 /* Static Properties */
13899
13900 OO.ui.MenuSectionOptionWidget.static.selectable = false;
13901
13902 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
13903
13904 /**
13905 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
13906 *
13907 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
13908 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
13909 * for an example.
13910 *
13911 * @class
13912 * @extends OO.ui.DecoratedOptionWidget
13913 *
13914 * @constructor
13915 * @param {Object} [config] Configuration options
13916 * @cfg {number} [level] Indentation level
13917 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
13918 */
13919 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
13920 // Configuration initialization
13921 config = config || {};
13922
13923 // Parent constructor
13924 OO.ui.OutlineOptionWidget.super.call( this, config );
13925
13926 // Properties
13927 this.level = 0;
13928 this.movable = !!config.movable;
13929 this.removable = !!config.removable;
13930
13931 // Initialization
13932 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
13933 this.setLevel( config.level );
13934 };
13935
13936 /* Setup */
13937
13938 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
13939
13940 /* Static Properties */
13941
13942 OO.ui.OutlineOptionWidget.static.highlightable = false;
13943
13944 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
13945
13946 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
13947
13948 OO.ui.OutlineOptionWidget.static.levels = 3;
13949
13950 /* Methods */
13951
13952 /**
13953 * Check if item is movable.
13954 *
13955 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13956 *
13957 * @return {boolean} Item is movable
13958 */
13959 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
13960 return this.movable;
13961 };
13962
13963 /**
13964 * Check if item is removable.
13965 *
13966 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13967 *
13968 * @return {boolean} Item is removable
13969 */
13970 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
13971 return this.removable;
13972 };
13973
13974 /**
13975 * Get indentation level.
13976 *
13977 * @return {number} Indentation level
13978 */
13979 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
13980 return this.level;
13981 };
13982
13983 /**
13984 * Set movability.
13985 *
13986 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13987 *
13988 * @param {boolean} movable Item is movable
13989 * @chainable
13990 */
13991 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
13992 this.movable = !!movable;
13993 this.updateThemeClasses();
13994 return this;
13995 };
13996
13997 /**
13998 * Set removability.
13999 *
14000 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14001 *
14002 * @param {boolean} movable Item is removable
14003 * @chainable
14004 */
14005 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
14006 this.removable = !!removable;
14007 this.updateThemeClasses();
14008 return this;
14009 };
14010
14011 /**
14012 * Set indentation level.
14013 *
14014 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
14015 * @chainable
14016 */
14017 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
14018 var levels = this.constructor.static.levels,
14019 levelClass = this.constructor.static.levelClass,
14020 i = levels;
14021
14022 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
14023 while ( i-- ) {
14024 if ( this.level === i ) {
14025 this.$element.addClass( levelClass + i );
14026 } else {
14027 this.$element.removeClass( levelClass + i );
14028 }
14029 }
14030 this.updateThemeClasses();
14031
14032 return this;
14033 };
14034
14035 /**
14036 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
14037 *
14038 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
14039 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
14040 * for an example.
14041 *
14042 * @class
14043 * @extends OO.ui.OptionWidget
14044 *
14045 * @constructor
14046 * @param {Object} [config] Configuration options
14047 */
14048 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
14049 // Configuration initialization
14050 config = config || {};
14051
14052 // Parent constructor
14053 OO.ui.TabOptionWidget.super.call( this, config );
14054
14055 // Initialization
14056 this.$element.addClass( 'oo-ui-tabOptionWidget' );
14057 };
14058
14059 /* Setup */
14060
14061 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
14062
14063 /* Static Properties */
14064
14065 OO.ui.TabOptionWidget.static.highlightable = false;
14066
14067 /**
14068 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
14069 * By default, each popup has an anchor that points toward its origin.
14070 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
14071 *
14072 * @example
14073 * // A popup widget.
14074 * var popup = new OO.ui.PopupWidget( {
14075 * $content: $( '<p>Hi there!</p>' ),
14076 * padded: true,
14077 * width: 300
14078 * } );
14079 *
14080 * $( 'body' ).append( popup.$element );
14081 * // To display the popup, toggle the visibility to 'true'.
14082 * popup.toggle( true );
14083 *
14084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
14085 *
14086 * @class
14087 * @extends OO.ui.Widget
14088 * @mixins OO.ui.LabelElement
14089 *
14090 * @constructor
14091 * @param {Object} [config] Configuration options
14092 * @cfg {number} [width=320] Width of popup in pixels
14093 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
14094 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
14095 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
14096 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
14097 * popup is leaning towards the right of the screen.
14098 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
14099 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
14100 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
14101 * sentence in the given language.
14102 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
14103 * See the [OOjs UI docs on MediaWiki][3] for an example.
14104 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
14105 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
14106 * @cfg {jQuery} [$content] Content to append to the popup's body
14107 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
14108 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
14109 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
14110 * for an example.
14111 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
14112 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
14113 * button.
14114 * @cfg {boolean} [padded] Add padding to the popup's body
14115 */
14116 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
14117 // Configuration initialization
14118 config = config || {};
14119
14120 // Parent constructor
14121 OO.ui.PopupWidget.super.call( this, config );
14122
14123 // Properties (must be set before ClippableElement constructor call)
14124 this.$body = $( '<div>' );
14125
14126 // Mixin constructors
14127 OO.ui.LabelElement.call( this, config );
14128 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
14129
14130 // Properties
14131 this.$popup = $( '<div>' );
14132 this.$head = $( '<div>' );
14133 this.$anchor = $( '<div>' );
14134 // If undefined, will be computed lazily in updateDimensions()
14135 this.$container = config.$container;
14136 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
14137 this.autoClose = !!config.autoClose;
14138 this.$autoCloseIgnore = config.$autoCloseIgnore;
14139 this.transitionTimeout = null;
14140 this.anchor = null;
14141 this.width = config.width !== undefined ? config.width : 320;
14142 this.height = config.height !== undefined ? config.height : null;
14143 // Validate alignment and transform deprecated values
14144 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( config.align ) > -1 ) {
14145 this.align = { left: 'force-right', right: 'force-left' }[ config.align ] || config.align;
14146 } else {
14147 this.align = 'center';
14148 }
14149 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
14150 this.onMouseDownHandler = this.onMouseDown.bind( this );
14151 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
14152
14153 // Events
14154 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
14155
14156 // Initialization
14157 this.toggleAnchor( config.anchor === undefined || config.anchor );
14158 this.$body.addClass( 'oo-ui-popupWidget-body' );
14159 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
14160 this.$head
14161 .addClass( 'oo-ui-popupWidget-head' )
14162 .append( this.$label, this.closeButton.$element );
14163 if ( !config.head ) {
14164 this.$head.addClass( 'oo-ui-element-hidden' );
14165 }
14166 this.$popup
14167 .addClass( 'oo-ui-popupWidget-popup' )
14168 .append( this.$head, this.$body );
14169 this.$element
14170 .addClass( 'oo-ui-popupWidget' )
14171 .append( this.$popup, this.$anchor );
14172 // Move content, which was added to #$element by OO.ui.Widget, to the body
14173 if ( config.$content instanceof jQuery ) {
14174 this.$body.append( config.$content );
14175 }
14176 if ( config.padded ) {
14177 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
14178 }
14179
14180 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14181 // that reference properties not initialized at that time of parent class construction
14182 // TODO: Find a better way to handle post-constructor setup
14183 this.visible = false;
14184 this.$element.addClass( 'oo-ui-element-hidden' );
14185 };
14186
14187 /* Setup */
14188
14189 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
14190 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
14191 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
14192
14193 /* Methods */
14194
14195 /**
14196 * Handles mouse down events.
14197 *
14198 * @private
14199 * @param {MouseEvent} e Mouse down event
14200 */
14201 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
14202 if (
14203 this.isVisible() &&
14204 !$.contains( this.$element[ 0 ], e.target ) &&
14205 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
14206 ) {
14207 this.toggle( false );
14208 }
14209 };
14210
14211 /**
14212 * Bind mouse down listener.
14213 *
14214 * @private
14215 */
14216 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
14217 // Capture clicks outside popup
14218 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
14219 };
14220
14221 /**
14222 * Handles close button click events.
14223 *
14224 * @private
14225 */
14226 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
14227 if ( this.isVisible() ) {
14228 this.toggle( false );
14229 }
14230 };
14231
14232 /**
14233 * Unbind mouse down listener.
14234 *
14235 * @private
14236 */
14237 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
14238 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
14239 };
14240
14241 /**
14242 * Handles key down events.
14243 *
14244 * @private
14245 * @param {KeyboardEvent} e Key down event
14246 */
14247 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
14248 if (
14249 e.which === OO.ui.Keys.ESCAPE &&
14250 this.isVisible()
14251 ) {
14252 this.toggle( false );
14253 e.preventDefault();
14254 e.stopPropagation();
14255 }
14256 };
14257
14258 /**
14259 * Bind key down listener.
14260 *
14261 * @private
14262 */
14263 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
14264 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
14265 };
14266
14267 /**
14268 * Unbind key down listener.
14269 *
14270 * @private
14271 */
14272 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
14273 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
14274 };
14275
14276 /**
14277 * Show, hide, or toggle the visibility of the anchor.
14278 *
14279 * @param {boolean} [show] Show anchor, omit to toggle
14280 */
14281 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
14282 show = show === undefined ? !this.anchored : !!show;
14283
14284 if ( this.anchored !== show ) {
14285 if ( show ) {
14286 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
14287 } else {
14288 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
14289 }
14290 this.anchored = show;
14291 }
14292 };
14293
14294 /**
14295 * Check if the anchor is visible.
14296 *
14297 * @return {boolean} Anchor is visible
14298 */
14299 OO.ui.PopupWidget.prototype.hasAnchor = function () {
14300 return this.anchor;
14301 };
14302
14303 /**
14304 * @inheritdoc
14305 */
14306 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
14307 show = show === undefined ? !this.isVisible() : !!show;
14308
14309 var change = show !== this.isVisible();
14310
14311 // Parent method
14312 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
14313
14314 if ( change ) {
14315 if ( show ) {
14316 if ( this.autoClose ) {
14317 this.bindMouseDownListener();
14318 this.bindKeyDownListener();
14319 }
14320 this.updateDimensions();
14321 this.toggleClipping( true );
14322 } else {
14323 this.toggleClipping( false );
14324 if ( this.autoClose ) {
14325 this.unbindMouseDownListener();
14326 this.unbindKeyDownListener();
14327 }
14328 }
14329 }
14330
14331 return this;
14332 };
14333
14334 /**
14335 * Set the size of the popup.
14336 *
14337 * Changing the size may also change the popup's position depending on the alignment.
14338 *
14339 * @param {number} width Width in pixels
14340 * @param {number} height Height in pixels
14341 * @param {boolean} [transition=false] Use a smooth transition
14342 * @chainable
14343 */
14344 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
14345 this.width = width;
14346 this.height = height !== undefined ? height : null;
14347 if ( this.isVisible() ) {
14348 this.updateDimensions( transition );
14349 }
14350 };
14351
14352 /**
14353 * Update the size and position.
14354 *
14355 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
14356 * be called automatically.
14357 *
14358 * @param {boolean} [transition=false] Use a smooth transition
14359 * @chainable
14360 */
14361 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
14362 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
14363 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
14364 align = this.align,
14365 widget = this;
14366
14367 if ( !this.$container ) {
14368 // Lazy-initialize $container if not specified in constructor
14369 this.$container = $( this.getClosestScrollableElementContainer() );
14370 }
14371
14372 // Set height and width before measuring things, since it might cause our measurements
14373 // to change (e.g. due to scrollbars appearing or disappearing)
14374 this.$popup.css( {
14375 width: this.width,
14376 height: this.height !== null ? this.height : 'auto'
14377 } );
14378
14379 // If we are in RTL, we need to flip the alignment, unless it is center
14380 if ( align === 'forwards' || align === 'backwards' ) {
14381 if ( this.$container.css( 'direction' ) === 'rtl' ) {
14382 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
14383 } else {
14384 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
14385 }
14386
14387 }
14388
14389 // Compute initial popupOffset based on alignment
14390 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
14391
14392 // Figure out if this will cause the popup to go beyond the edge of the container
14393 originOffset = this.$element.offset().left;
14394 containerLeft = this.$container.offset().left;
14395 containerWidth = this.$container.innerWidth();
14396 containerRight = containerLeft + containerWidth;
14397 popupLeft = popupOffset - this.containerPadding;
14398 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
14399 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
14400 overlapRight = containerRight - ( originOffset + popupRight );
14401
14402 // Adjust offset to make the popup not go beyond the edge, if needed
14403 if ( overlapRight < 0 ) {
14404 popupOffset += overlapRight;
14405 } else if ( overlapLeft < 0 ) {
14406 popupOffset -= overlapLeft;
14407 }
14408
14409 // Adjust offset to avoid anchor being rendered too close to the edge
14410 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
14411 // TODO: Find a measurement that works for CSS anchors and image anchors
14412 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
14413 if ( popupOffset + this.width < anchorWidth ) {
14414 popupOffset = anchorWidth - this.width;
14415 } else if ( -popupOffset < anchorWidth ) {
14416 popupOffset = -anchorWidth;
14417 }
14418
14419 // Prevent transition from being interrupted
14420 clearTimeout( this.transitionTimeout );
14421 if ( transition ) {
14422 // Enable transition
14423 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
14424 }
14425
14426 // Position body relative to anchor
14427 this.$popup.css( 'margin-left', popupOffset );
14428
14429 if ( transition ) {
14430 // Prevent transitioning after transition is complete
14431 this.transitionTimeout = setTimeout( function () {
14432 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
14433 }, 200 );
14434 } else {
14435 // Prevent transitioning immediately
14436 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
14437 }
14438
14439 // Reevaluate clipping state since we've relocated and resized the popup
14440 this.clip();
14441
14442 return this;
14443 };
14444
14445 /**
14446 * Progress bars visually display the status of an operation, such as a download,
14447 * and can be either determinate or indeterminate:
14448 *
14449 * - **determinate** process bars show the percent of an operation that is complete.
14450 *
14451 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
14452 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
14453 * not use percentages.
14454 *
14455 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
14456 *
14457 * @example
14458 * // Examples of determinate and indeterminate progress bars.
14459 * var progressBar1 = new OO.ui.ProgressBarWidget( {
14460 * progress: 33
14461 * } );
14462 * var progressBar2 = new OO.ui.ProgressBarWidget();
14463 *
14464 * // Create a FieldsetLayout to layout progress bars
14465 * var fieldset = new OO.ui.FieldsetLayout;
14466 * fieldset.addItems( [
14467 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
14468 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
14469 * ] );
14470 * $( 'body' ).append( fieldset.$element );
14471 *
14472 * @class
14473 * @extends OO.ui.Widget
14474 *
14475 * @constructor
14476 * @param {Object} [config] Configuration options
14477 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
14478 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
14479 * By default, the progress bar is indeterminate.
14480 */
14481 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
14482 // Configuration initialization
14483 config = config || {};
14484
14485 // Parent constructor
14486 OO.ui.ProgressBarWidget.super.call( this, config );
14487
14488 // Properties
14489 this.$bar = $( '<div>' );
14490 this.progress = null;
14491
14492 // Initialization
14493 this.setProgress( config.progress !== undefined ? config.progress : false );
14494 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
14495 this.$element
14496 .attr( {
14497 role: 'progressbar',
14498 'aria-valuemin': 0,
14499 'aria-valuemax': 100
14500 } )
14501 .addClass( 'oo-ui-progressBarWidget' )
14502 .append( this.$bar );
14503 };
14504
14505 /* Setup */
14506
14507 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
14508
14509 /* Static Properties */
14510
14511 OO.ui.ProgressBarWidget.static.tagName = 'div';
14512
14513 /* Methods */
14514
14515 /**
14516 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
14517 *
14518 * @return {number|boolean} Progress percent
14519 */
14520 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
14521 return this.progress;
14522 };
14523
14524 /**
14525 * Set the percent of the process completed or `false` for an indeterminate process.
14526 *
14527 * @param {number|boolean} progress Progress percent or `false` for indeterminate
14528 */
14529 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
14530 this.progress = progress;
14531
14532 if ( progress !== false ) {
14533 this.$bar.css( 'width', this.progress + '%' );
14534 this.$element.attr( 'aria-valuenow', this.progress );
14535 } else {
14536 this.$bar.css( 'width', '' );
14537 this.$element.removeAttr( 'aria-valuenow' );
14538 }
14539 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
14540 };
14541
14542 /**
14543 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
14544 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
14545 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
14546 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
14547 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
14548 *
14549 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
14550 * the [OOjs UI demos][1] for an example.
14551 *
14552 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
14553 *
14554 * @class
14555 * @extends OO.ui.Widget
14556 *
14557 * @constructor
14558 * @param {Object} [config] Configuration options
14559 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
14560 * @cfg {string} [value] Initial query value
14561 */
14562 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
14563 // Configuration initialization
14564 config = config || {};
14565
14566 // Parent constructor
14567 OO.ui.SearchWidget.super.call( this, config );
14568
14569 // Properties
14570 this.query = new OO.ui.TextInputWidget( {
14571 icon: 'search',
14572 placeholder: config.placeholder,
14573 value: config.value
14574 } );
14575 this.results = new OO.ui.SelectWidget();
14576 this.$query = $( '<div>' );
14577 this.$results = $( '<div>' );
14578
14579 // Events
14580 this.query.connect( this, {
14581 change: 'onQueryChange',
14582 enter: 'onQueryEnter'
14583 } );
14584 this.results.connect( this, {
14585 highlight: 'onResultsHighlight',
14586 select: 'onResultsSelect'
14587 } );
14588 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
14589
14590 // Initialization
14591 this.$query
14592 .addClass( 'oo-ui-searchWidget-query' )
14593 .append( this.query.$element );
14594 this.$results
14595 .addClass( 'oo-ui-searchWidget-results' )
14596 .append( this.results.$element );
14597 this.$element
14598 .addClass( 'oo-ui-searchWidget' )
14599 .append( this.$results, this.$query );
14600 };
14601
14602 /* Setup */
14603
14604 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
14605
14606 /* Events */
14607
14608 /**
14609 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
14610 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
14611 * string is typed into the query field instead, the first menu item that matches the query
14612 * will be highlighted.
14613
14614 * @event highlight
14615 * @deprecated Connect straight to getResults() events instead
14616 * @param {Object|null} item Item data or null if no item is highlighted
14617 */
14618
14619 /**
14620 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
14621 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
14622 *
14623 * @event select
14624 * @deprecated Connect straight to getResults() events instead
14625 * @param {Object|null} item Item data or null if no item is selected
14626 */
14627
14628 /* Methods */
14629
14630 /**
14631 * Handle query key down events.
14632 *
14633 * @private
14634 * @param {jQuery.Event} e Key down event
14635 */
14636 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
14637 var highlightedItem, nextItem,
14638 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
14639
14640 if ( dir ) {
14641 highlightedItem = this.results.getHighlightedItem();
14642 if ( !highlightedItem ) {
14643 highlightedItem = this.results.getSelectedItem();
14644 }
14645 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
14646 this.results.highlightItem( nextItem );
14647 nextItem.scrollElementIntoView();
14648 }
14649 };
14650
14651 /**
14652 * Handle select widget select events.
14653 *
14654 * Clears existing results. Subclasses should repopulate items according to new query.
14655 *
14656 * @private
14657 * @param {string} value New value
14658 */
14659 OO.ui.SearchWidget.prototype.onQueryChange = function () {
14660 // Reset
14661 this.results.clearItems();
14662 };
14663
14664 /**
14665 * Handle select widget enter key events.
14666 *
14667 * Selects highlighted item.
14668 *
14669 * @private
14670 * @param {string} value New value
14671 */
14672 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
14673 // Reset
14674 this.results.selectItem( this.results.getHighlightedItem() );
14675 };
14676
14677 /**
14678 * Handle select widget highlight events.
14679 *
14680 * @private
14681 * @deprecated Connect straight to getResults() events instead
14682 * @param {OO.ui.OptionWidget} item Highlighted item
14683 * @fires highlight
14684 */
14685 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
14686 this.emit( 'highlight', item ? item.getData() : null );
14687 };
14688
14689 /**
14690 * Handle select widget select events.
14691 *
14692 * @private
14693 * @deprecated Connect straight to getResults() events instead
14694 * @param {OO.ui.OptionWidget} item Selected item
14695 * @fires select
14696 */
14697 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
14698 this.emit( 'select', item ? item.getData() : null );
14699 };
14700
14701 /**
14702 * Get the query input.
14703 *
14704 * @return {OO.ui.TextInputWidget} Query input
14705 */
14706 OO.ui.SearchWidget.prototype.getQuery = function () {
14707 return this.query;
14708 };
14709
14710 /**
14711 * Get the search results menu.
14712 *
14713 * @return {OO.ui.SelectWidget} Menu of search results
14714 */
14715 OO.ui.SearchWidget.prototype.getResults = function () {
14716 return this.results;
14717 };
14718
14719 /**
14720 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
14721 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
14722 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
14723 * menu selects}.
14724 *
14725 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
14726 * information, please see the [OOjs UI documentation on MediaWiki][1].
14727 *
14728 * @example
14729 * // Example of a select widget with three options
14730 * var select = new OO.ui.SelectWidget( {
14731 * items: [
14732 * new OO.ui.OptionWidget( {
14733 * data: 'a',
14734 * label: 'Option One',
14735 * } ),
14736 * new OO.ui.OptionWidget( {
14737 * data: 'b',
14738 * label: 'Option Two',
14739 * } ),
14740 * new OO.ui.OptionWidget( {
14741 * data: 'c',
14742 * label: 'Option Three',
14743 * } )
14744 * ]
14745 * } );
14746 * $( 'body' ).append( select.$element );
14747 *
14748 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14749 *
14750 * @class
14751 * @extends OO.ui.Widget
14752 * @mixins OO.ui.GroupElement
14753 *
14754 * @constructor
14755 * @param {Object} [config] Configuration options
14756 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
14757 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
14758 * the [OOjs UI documentation on MediaWiki] [2] for examples.
14759 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14760 */
14761 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
14762 // Configuration initialization
14763 config = config || {};
14764
14765 // Parent constructor
14766 OO.ui.SelectWidget.super.call( this, config );
14767
14768 // Mixin constructors
14769 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
14770
14771 // Properties
14772 this.pressed = false;
14773 this.selecting = null;
14774 this.onMouseUpHandler = this.onMouseUp.bind( this );
14775 this.onMouseMoveHandler = this.onMouseMove.bind( this );
14776 this.onKeyDownHandler = this.onKeyDown.bind( this );
14777
14778 // Events
14779 this.$element.on( {
14780 mousedown: this.onMouseDown.bind( this ),
14781 mouseover: this.onMouseOver.bind( this ),
14782 mouseleave: this.onMouseLeave.bind( this )
14783 } );
14784
14785 // Initialization
14786 this.$element
14787 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
14788 .attr( 'role', 'listbox' );
14789 if ( Array.isArray( config.items ) ) {
14790 this.addItems( config.items );
14791 }
14792 };
14793
14794 /* Setup */
14795
14796 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
14797
14798 // Need to mixin base class as well
14799 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
14800 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
14801
14802 /* Events */
14803
14804 /**
14805 * @event highlight
14806 *
14807 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
14808 *
14809 * @param {OO.ui.OptionWidget|null} item Highlighted item
14810 */
14811
14812 /**
14813 * @event press
14814 *
14815 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
14816 * pressed state of an option.
14817 *
14818 * @param {OO.ui.OptionWidget|null} item Pressed item
14819 */
14820
14821 /**
14822 * @event select
14823 *
14824 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
14825 *
14826 * @param {OO.ui.OptionWidget|null} item Selected item
14827 */
14828
14829 /**
14830 * @event choose
14831 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
14832 * @param {OO.ui.OptionWidget} item Chosen item
14833 */
14834
14835 /**
14836 * @event add
14837 *
14838 * An `add` event is emitted when options are added to the select with the #addItems method.
14839 *
14840 * @param {OO.ui.OptionWidget[]} items Added items
14841 * @param {number} index Index of insertion point
14842 */
14843
14844 /**
14845 * @event remove
14846 *
14847 * A `remove` event is emitted when options are removed from the select with the #clearItems
14848 * or #removeItems methods.
14849 *
14850 * @param {OO.ui.OptionWidget[]} items Removed items
14851 */
14852
14853 /* Methods */
14854
14855 /**
14856 * Handle mouse down events.
14857 *
14858 * @private
14859 * @param {jQuery.Event} e Mouse down event
14860 */
14861 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
14862 var item;
14863
14864 if ( !this.isDisabled() && e.which === 1 ) {
14865 this.togglePressed( true );
14866 item = this.getTargetItem( e );
14867 if ( item && item.isSelectable() ) {
14868 this.pressItem( item );
14869 this.selecting = item;
14870 this.getElementDocument().addEventListener(
14871 'mouseup',
14872 this.onMouseUpHandler,
14873 true
14874 );
14875 this.getElementDocument().addEventListener(
14876 'mousemove',
14877 this.onMouseMoveHandler,
14878 true
14879 );
14880 }
14881 }
14882 return false;
14883 };
14884
14885 /**
14886 * Handle mouse up events.
14887 *
14888 * @private
14889 * @param {jQuery.Event} e Mouse up event
14890 */
14891 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
14892 var item;
14893
14894 this.togglePressed( false );
14895 if ( !this.selecting ) {
14896 item = this.getTargetItem( e );
14897 if ( item && item.isSelectable() ) {
14898 this.selecting = item;
14899 }
14900 }
14901 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
14902 this.pressItem( null );
14903 this.chooseItem( this.selecting );
14904 this.selecting = null;
14905 }
14906
14907 this.getElementDocument().removeEventListener(
14908 'mouseup',
14909 this.onMouseUpHandler,
14910 true
14911 );
14912 this.getElementDocument().removeEventListener(
14913 'mousemove',
14914 this.onMouseMoveHandler,
14915 true
14916 );
14917
14918 return false;
14919 };
14920
14921 /**
14922 * Handle mouse move events.
14923 *
14924 * @private
14925 * @param {jQuery.Event} e Mouse move event
14926 */
14927 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
14928 var item;
14929
14930 if ( !this.isDisabled() && this.pressed ) {
14931 item = this.getTargetItem( e );
14932 if ( item && item !== this.selecting && item.isSelectable() ) {
14933 this.pressItem( item );
14934 this.selecting = item;
14935 }
14936 }
14937 return false;
14938 };
14939
14940 /**
14941 * Handle mouse over events.
14942 *
14943 * @private
14944 * @param {jQuery.Event} e Mouse over event
14945 */
14946 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
14947 var item;
14948
14949 if ( !this.isDisabled() ) {
14950 item = this.getTargetItem( e );
14951 this.highlightItem( item && item.isHighlightable() ? item : null );
14952 }
14953 return false;
14954 };
14955
14956 /**
14957 * Handle mouse leave events.
14958 *
14959 * @private
14960 * @param {jQuery.Event} e Mouse over event
14961 */
14962 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
14963 if ( !this.isDisabled() ) {
14964 this.highlightItem( null );
14965 }
14966 return false;
14967 };
14968
14969 /**
14970 * Handle key down events.
14971 *
14972 * @protected
14973 * @param {jQuery.Event} e Key down event
14974 */
14975 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
14976 var nextItem,
14977 handled = false,
14978 currentItem = this.getHighlightedItem() || this.getSelectedItem();
14979
14980 if ( !this.isDisabled() && this.isVisible() ) {
14981 switch ( e.keyCode ) {
14982 case OO.ui.Keys.ENTER:
14983 if ( currentItem && currentItem.constructor.static.highlightable ) {
14984 // Was only highlighted, now let's select it. No-op if already selected.
14985 this.chooseItem( currentItem );
14986 handled = true;
14987 }
14988 break;
14989 case OO.ui.Keys.UP:
14990 case OO.ui.Keys.LEFT:
14991 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
14992 handled = true;
14993 break;
14994 case OO.ui.Keys.DOWN:
14995 case OO.ui.Keys.RIGHT:
14996 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
14997 handled = true;
14998 break;
14999 case OO.ui.Keys.ESCAPE:
15000 case OO.ui.Keys.TAB:
15001 if ( currentItem && currentItem.constructor.static.highlightable ) {
15002 currentItem.setHighlighted( false );
15003 }
15004 this.unbindKeyDownListener();
15005 // Don't prevent tabbing away / defocusing
15006 handled = false;
15007 break;
15008 }
15009
15010 if ( nextItem ) {
15011 if ( nextItem.constructor.static.highlightable ) {
15012 this.highlightItem( nextItem );
15013 } else {
15014 this.chooseItem( nextItem );
15015 }
15016 nextItem.scrollElementIntoView();
15017 }
15018
15019 if ( handled ) {
15020 // Can't just return false, because e is not always a jQuery event
15021 e.preventDefault();
15022 e.stopPropagation();
15023 }
15024 }
15025 };
15026
15027 /**
15028 * Bind key down listener.
15029 *
15030 * @protected
15031 */
15032 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
15033 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
15034 };
15035
15036 /**
15037 * Unbind key down listener.
15038 *
15039 * @protected
15040 */
15041 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
15042 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
15043 };
15044
15045 /**
15046 * Get the closest item to a jQuery.Event.
15047 *
15048 * @private
15049 * @param {jQuery.Event} e
15050 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
15051 */
15052 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
15053 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
15054 };
15055
15056 /**
15057 * Get selected item.
15058 *
15059 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
15060 */
15061 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
15062 var i, len;
15063
15064 for ( i = 0, len = this.items.length; i < len; i++ ) {
15065 if ( this.items[ i ].isSelected() ) {
15066 return this.items[ i ];
15067 }
15068 }
15069 return null;
15070 };
15071
15072 /**
15073 * Get highlighted item.
15074 *
15075 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
15076 */
15077 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
15078 var i, len;
15079
15080 for ( i = 0, len = this.items.length; i < len; i++ ) {
15081 if ( this.items[ i ].isHighlighted() ) {
15082 return this.items[ i ];
15083 }
15084 }
15085 return null;
15086 };
15087
15088 /**
15089 * Toggle pressed state.
15090 *
15091 * Press is a state that occurs when a user mouses down on an item, but
15092 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
15093 * until the user releases the mouse.
15094 *
15095 * @param {boolean} pressed An option is being pressed
15096 */
15097 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
15098 if ( pressed === undefined ) {
15099 pressed = !this.pressed;
15100 }
15101 if ( pressed !== this.pressed ) {
15102 this.$element
15103 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
15104 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
15105 this.pressed = pressed;
15106 }
15107 };
15108
15109 /**
15110 * Highlight an option. If the `item` param is omitted, no options will be highlighted
15111 * and any existing highlight will be removed. The highlight is mutually exclusive.
15112 *
15113 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
15114 * @fires highlight
15115 * @chainable
15116 */
15117 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
15118 var i, len, highlighted,
15119 changed = false;
15120
15121 for ( i = 0, len = this.items.length; i < len; i++ ) {
15122 highlighted = this.items[ i ] === item;
15123 if ( this.items[ i ].isHighlighted() !== highlighted ) {
15124 this.items[ i ].setHighlighted( highlighted );
15125 changed = true;
15126 }
15127 }
15128 if ( changed ) {
15129 this.emit( 'highlight', item );
15130 }
15131
15132 return this;
15133 };
15134
15135 /**
15136 * Programmatically select an option by its data. If the `data` parameter is omitted,
15137 * or if the item does not exist, all options will be deselected.
15138 *
15139 * @param {Object|string} [data] Value of the item to select, omit to deselect all
15140 * @fires select
15141 * @chainable
15142 */
15143 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
15144 var itemFromData = this.getItemFromData( data );
15145 if ( data === undefined || !itemFromData ) {
15146 return this.selectItem();
15147 }
15148 return this.selectItem( itemFromData );
15149 };
15150
15151 /**
15152 * Programmatically select an option by its reference. If the `item` parameter is omitted,
15153 * all options will be deselected.
15154 *
15155 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
15156 * @fires select
15157 * @chainable
15158 */
15159 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
15160 var i, len, selected,
15161 changed = false;
15162
15163 for ( i = 0, len = this.items.length; i < len; i++ ) {
15164 selected = this.items[ i ] === item;
15165 if ( this.items[ i ].isSelected() !== selected ) {
15166 this.items[ i ].setSelected( selected );
15167 changed = true;
15168 }
15169 }
15170 if ( changed ) {
15171 this.emit( 'select', item );
15172 }
15173
15174 return this;
15175 };
15176
15177 /**
15178 * Press an item.
15179 *
15180 * Press is a state that occurs when a user mouses down on an item, but has not
15181 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
15182 * releases the mouse.
15183 *
15184 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
15185 * @fires press
15186 * @chainable
15187 */
15188 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
15189 var i, len, pressed,
15190 changed = false;
15191
15192 for ( i = 0, len = this.items.length; i < len; i++ ) {
15193 pressed = this.items[ i ] === item;
15194 if ( this.items[ i ].isPressed() !== pressed ) {
15195 this.items[ i ].setPressed( pressed );
15196 changed = true;
15197 }
15198 }
15199 if ( changed ) {
15200 this.emit( 'press', item );
15201 }
15202
15203 return this;
15204 };
15205
15206 /**
15207 * Choose an item.
15208 *
15209 * Note that ‘choose’ should never be modified programmatically. A user can choose
15210 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
15211 * use the #selectItem method.
15212 *
15213 * This method is identical to #selectItem, but may vary in subclasses that take additional action
15214 * when users choose an item with the keyboard or mouse.
15215 *
15216 * @param {OO.ui.OptionWidget} item Item to choose
15217 * @fires choose
15218 * @chainable
15219 */
15220 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
15221 this.selectItem( item );
15222 this.emit( 'choose', item );
15223
15224 return this;
15225 };
15226
15227 /**
15228 * Get an option by its position relative to the specified item (or to the start of the option array,
15229 * if item is `null`). The direction in which to search through the option array is specified with a
15230 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
15231 * `null` if there are no options in the array.
15232 *
15233 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
15234 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
15235 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
15236 */
15237 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
15238 var currentIndex, nextIndex, i,
15239 increase = direction > 0 ? 1 : -1,
15240 len = this.items.length;
15241
15242 if ( item instanceof OO.ui.OptionWidget ) {
15243 currentIndex = $.inArray( item, this.items );
15244 nextIndex = ( currentIndex + increase + len ) % len;
15245 } else {
15246 // If no item is selected and moving forward, start at the beginning.
15247 // If moving backward, start at the end.
15248 nextIndex = direction > 0 ? 0 : len - 1;
15249 }
15250
15251 for ( i = 0; i < len; i++ ) {
15252 item = this.items[ nextIndex ];
15253 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
15254 return item;
15255 }
15256 nextIndex = ( nextIndex + increase + len ) % len;
15257 }
15258 return null;
15259 };
15260
15261 /**
15262 * Get the next selectable item or `null` if there are no selectable items.
15263 * Disabled options and menu-section markers and breaks are not selectable.
15264 *
15265 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
15266 */
15267 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
15268 var i, len, item;
15269
15270 for ( i = 0, len = this.items.length; i < len; i++ ) {
15271 item = this.items[ i ];
15272 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
15273 return item;
15274 }
15275 }
15276
15277 return null;
15278 };
15279
15280 /**
15281 * Add an array of options to the select. Optionally, an index number can be used to
15282 * specify an insertion point.
15283 *
15284 * @param {OO.ui.OptionWidget[]} items Items to add
15285 * @param {number} [index] Index to insert items after
15286 * @fires add
15287 * @chainable
15288 */
15289 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
15290 // Mixin method
15291 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
15292
15293 // Always provide an index, even if it was omitted
15294 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
15295
15296 return this;
15297 };
15298
15299 /**
15300 * Remove the specified array of options from the select. Options will be detached
15301 * from the DOM, not removed, so they can be reused later. To remove all options from
15302 * the select, you may wish to use the #clearItems method instead.
15303 *
15304 * @param {OO.ui.OptionWidget[]} items Items to remove
15305 * @fires remove
15306 * @chainable
15307 */
15308 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
15309 var i, len, item;
15310
15311 // Deselect items being removed
15312 for ( i = 0, len = items.length; i < len; i++ ) {
15313 item = items[ i ];
15314 if ( item.isSelected() ) {
15315 this.selectItem( null );
15316 }
15317 }
15318
15319 // Mixin method
15320 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
15321
15322 this.emit( 'remove', items );
15323
15324 return this;
15325 };
15326
15327 /**
15328 * Clear all options from the select. Options will be detached from the DOM, not removed,
15329 * so that they can be reused later. To remove a subset of options from the select, use
15330 * the #removeItems method.
15331 *
15332 * @fires remove
15333 * @chainable
15334 */
15335 OO.ui.SelectWidget.prototype.clearItems = function () {
15336 var items = this.items.slice();
15337
15338 // Mixin method
15339 OO.ui.GroupWidget.prototype.clearItems.call( this );
15340
15341 // Clear selection
15342 this.selectItem( null );
15343
15344 this.emit( 'remove', items );
15345
15346 return this;
15347 };
15348
15349 /**
15350 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
15351 * button options and is used together with
15352 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
15353 * highlighting, choosing, and selecting mutually exclusive options. Please see
15354 * the [OOjs UI documentation on MediaWiki] [1] for more information.
15355 *
15356 * @example
15357 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
15358 * var option1 = new OO.ui.ButtonOptionWidget( {
15359 * data: 1,
15360 * label: 'Option 1',
15361 * title: 'Button option 1'
15362 * } );
15363 *
15364 * var option2 = new OO.ui.ButtonOptionWidget( {
15365 * data: 2,
15366 * label: 'Option 2',
15367 * title: 'Button option 2'
15368 * } );
15369 *
15370 * var option3 = new OO.ui.ButtonOptionWidget( {
15371 * data: 3,
15372 * label: 'Option 3',
15373 * title: 'Button option 3'
15374 * } );
15375 *
15376 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
15377 * items: [ option1, option2, option3 ]
15378 * } );
15379 * $( 'body' ).append( buttonSelect.$element );
15380 *
15381 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15382 *
15383 * @class
15384 * @extends OO.ui.SelectWidget
15385 * @mixins OO.ui.TabIndexedElement
15386 *
15387 * @constructor
15388 * @param {Object} [config] Configuration options
15389 */
15390 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
15391 // Parent constructor
15392 OO.ui.ButtonSelectWidget.super.call( this, config );
15393
15394 // Mixin constructors
15395 OO.ui.TabIndexedElement.call( this, config );
15396
15397 // Events
15398 this.$element.on( {
15399 focus: this.bindKeyDownListener.bind( this ),
15400 blur: this.unbindKeyDownListener.bind( this )
15401 } );
15402
15403 // Initialization
15404 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
15405 };
15406
15407 /* Setup */
15408
15409 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
15410 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
15411
15412 /**
15413 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
15414 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
15415 * an interface for adding, removing and selecting options.
15416 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
15417 *
15418 * @example
15419 * // A RadioSelectWidget with RadioOptions.
15420 * var option1 = new OO.ui.RadioOptionWidget( {
15421 * data: 'a',
15422 * label: 'Selected radio option'
15423 * } );
15424 *
15425 * var option2 = new OO.ui.RadioOptionWidget( {
15426 * data: 'b',
15427 * label: 'Unselected radio option'
15428 * } );
15429 *
15430 * var radioSelect=new OO.ui.RadioSelectWidget( {
15431 * items: [ option1, option2 ]
15432 * } );
15433 *
15434 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
15435 * radioSelect.selectItem( option1 );
15436 *
15437 * $( 'body' ).append( radioSelect.$element );
15438 *
15439 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15440
15441 *
15442 * @class
15443 * @extends OO.ui.SelectWidget
15444 * @mixins OO.ui.TabIndexedElement
15445 *
15446 * @constructor
15447 * @param {Object} [config] Configuration options
15448 */
15449 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
15450 // Parent constructor
15451 OO.ui.RadioSelectWidget.super.call( this, config );
15452
15453 // Mixin constructors
15454 OO.ui.TabIndexedElement.call( this, config );
15455
15456 // Events
15457 this.$element.on( {
15458 focus: this.bindKeyDownListener.bind( this ),
15459 blur: this.unbindKeyDownListener.bind( this )
15460 } );
15461
15462 // Initialization
15463 this.$element.addClass( 'oo-ui-radioSelectWidget' );
15464 };
15465
15466 /* Setup */
15467
15468 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
15469 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
15470
15471 /**
15472 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
15473 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
15474 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
15475 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
15476 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
15477 * and customized to be opened, closed, and displayed as needed.
15478 *
15479 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
15480 * mouse outside the menu.
15481 *
15482 * Menus also have support for keyboard interaction:
15483 *
15484 * - Enter/Return key: choose and select a menu option
15485 * - Up-arrow key: highlight the previous menu option
15486 * - Down-arrow key: highlight the next menu option
15487 * - Esc key: hide the menu
15488 *
15489 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
15490 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15491 *
15492 * @class
15493 * @extends OO.ui.SelectWidget
15494 * @mixins OO.ui.ClippableElement
15495 *
15496 * @constructor
15497 * @param {Object} [config] Configuration options
15498 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
15499 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
15500 * and {@link OO.ui.LookupElement LookupElement}
15501 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
15502 * anywhere on the page outside of this widget, the menu is hidden.
15503 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
15504 */
15505 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
15506 // Configuration initialization
15507 config = config || {};
15508
15509 // Parent constructor
15510 OO.ui.MenuSelectWidget.super.call( this, config );
15511
15512 // Mixin constructors
15513 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
15514
15515 // Properties
15516 this.newItems = null;
15517 this.autoHide = config.autoHide === undefined || !!config.autoHide;
15518 this.$input = config.input ? config.input.$input : null;
15519 this.$widget = config.widget ? config.widget.$element : null;
15520 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
15521
15522 // Initialization
15523 this.$element
15524 .addClass( 'oo-ui-menuSelectWidget' )
15525 .attr( 'role', 'menu' );
15526
15527 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
15528 // that reference properties not initialized at that time of parent class construction
15529 // TODO: Find a better way to handle post-constructor setup
15530 this.visible = false;
15531 this.$element.addClass( 'oo-ui-element-hidden' );
15532 };
15533
15534 /* Setup */
15535
15536 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
15537 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
15538
15539 /* Methods */
15540
15541 /**
15542 * Handles document mouse down events.
15543 *
15544 * @protected
15545 * @param {jQuery.Event} e Key down event
15546 */
15547 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
15548 if (
15549 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
15550 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
15551 ) {
15552 this.toggle( false );
15553 }
15554 };
15555
15556 /**
15557 * @inheritdoc
15558 */
15559 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
15560 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
15561
15562 if ( !this.isDisabled() && this.isVisible() ) {
15563 switch ( e.keyCode ) {
15564 case OO.ui.Keys.LEFT:
15565 case OO.ui.Keys.RIGHT:
15566 // Do nothing if a text field is associated, arrow keys will be handled natively
15567 if ( !this.$input ) {
15568 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
15569 }
15570 break;
15571 case OO.ui.Keys.ESCAPE:
15572 case OO.ui.Keys.TAB:
15573 if ( currentItem ) {
15574 currentItem.setHighlighted( false );
15575 }
15576 this.toggle( false );
15577 // Don't prevent tabbing away, prevent defocusing
15578 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
15579 e.preventDefault();
15580 e.stopPropagation();
15581 }
15582 break;
15583 default:
15584 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
15585 return;
15586 }
15587 }
15588 };
15589
15590 /**
15591 * @inheritdoc
15592 */
15593 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
15594 if ( this.$input ) {
15595 this.$input.on( 'keydown', this.onKeyDownHandler );
15596 } else {
15597 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
15598 }
15599 };
15600
15601 /**
15602 * @inheritdoc
15603 */
15604 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
15605 if ( this.$input ) {
15606 this.$input.off( 'keydown', this.onKeyDownHandler );
15607 } else {
15608 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
15609 }
15610 };
15611
15612 /**
15613 * Choose an item.
15614 *
15615 * When a user chooses an item, the menu is closed.
15616 *
15617 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
15618 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
15619 * @param {OO.ui.OptionWidget} item Item to choose
15620 * @chainable
15621 */
15622 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
15623 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
15624 this.toggle( false );
15625 return this;
15626 };
15627
15628 /**
15629 * @inheritdoc
15630 */
15631 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
15632 var i, len, item;
15633
15634 // Parent method
15635 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
15636
15637 // Auto-initialize
15638 if ( !this.newItems ) {
15639 this.newItems = [];
15640 }
15641
15642 for ( i = 0, len = items.length; i < len; i++ ) {
15643 item = items[ i ];
15644 if ( this.isVisible() ) {
15645 // Defer fitting label until item has been attached
15646 item.fitLabel();
15647 } else {
15648 this.newItems.push( item );
15649 }
15650 }
15651
15652 // Reevaluate clipping
15653 this.clip();
15654
15655 return this;
15656 };
15657
15658 /**
15659 * @inheritdoc
15660 */
15661 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
15662 // Parent method
15663 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
15664
15665 // Reevaluate clipping
15666 this.clip();
15667
15668 return this;
15669 };
15670
15671 /**
15672 * @inheritdoc
15673 */
15674 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
15675 // Parent method
15676 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
15677
15678 // Reevaluate clipping
15679 this.clip();
15680
15681 return this;
15682 };
15683
15684 /**
15685 * @inheritdoc
15686 */
15687 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
15688 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
15689
15690 var i, len,
15691 change = visible !== this.isVisible();
15692
15693 // Parent method
15694 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
15695
15696 if ( change ) {
15697 if ( visible ) {
15698 this.bindKeyDownListener();
15699
15700 if ( this.newItems && this.newItems.length ) {
15701 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
15702 this.newItems[ i ].fitLabel();
15703 }
15704 this.newItems = null;
15705 }
15706 this.toggleClipping( true );
15707
15708 // Auto-hide
15709 if ( this.autoHide ) {
15710 this.getElementDocument().addEventListener(
15711 'mousedown', this.onDocumentMouseDownHandler, true
15712 );
15713 }
15714 } else {
15715 this.unbindKeyDownListener();
15716 this.getElementDocument().removeEventListener(
15717 'mousedown', this.onDocumentMouseDownHandler, true
15718 );
15719 this.toggleClipping( false );
15720 }
15721 }
15722
15723 return this;
15724 };
15725
15726 /**
15727 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
15728 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
15729 * calculated and maintained when the menu is toggled or the window is resized.
15730 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
15731 *
15732 * @class
15733 * @extends OO.ui.MenuSelectWidget
15734 *
15735 * @constructor
15736 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
15737 * @param {Object} [config] Configuration options
15738 * @cfg {jQuery} [$container=input.$element] Element to render menu under
15739 */
15740 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
15741 // Allow passing positional parameters inside the config object
15742 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
15743 config = inputWidget;
15744 inputWidget = config.inputWidget;
15745 }
15746
15747 // Configuration initialization
15748 config = config || {};
15749
15750 // Parent constructor
15751 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
15752
15753 // Properties
15754 this.inputWidget = inputWidget;
15755 this.$container = config.$container || this.inputWidget.$element;
15756 this.onWindowResizeHandler = this.onWindowResize.bind( this );
15757
15758 // Initialization
15759 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
15760 };
15761
15762 /* Setup */
15763
15764 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
15765
15766 /* Methods */
15767
15768 /**
15769 * Handle window resize event.
15770 *
15771 * @private
15772 * @param {jQuery.Event} e Window resize event
15773 */
15774 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
15775 this.position();
15776 };
15777
15778 /**
15779 * @inheritdoc
15780 */
15781 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
15782 visible = visible === undefined ? !this.isVisible() : !!visible;
15783
15784 var change = visible !== this.isVisible();
15785
15786 if ( change && visible ) {
15787 // Make sure the width is set before the parent method runs.
15788 // After this we have to call this.position(); again to actually
15789 // position ourselves correctly.
15790 this.position();
15791 }
15792
15793 // Parent method
15794 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
15795
15796 if ( change ) {
15797 if ( this.isVisible() ) {
15798 this.position();
15799 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
15800 } else {
15801 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
15802 }
15803 }
15804
15805 return this;
15806 };
15807
15808 /**
15809 * Position the menu.
15810 *
15811 * @private
15812 * @chainable
15813 */
15814 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
15815 var $container = this.$container,
15816 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
15817
15818 // Position under input
15819 pos.top += $container.height();
15820 this.$element.css( pos );
15821
15822 // Set width
15823 this.setIdealSize( $container.width() );
15824 // We updated the position, so re-evaluate the clipping state
15825 this.clip();
15826
15827 return this;
15828 };
15829
15830 /**
15831 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
15832 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
15833 *
15834 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
15835 *
15836 * @class
15837 * @extends OO.ui.SelectWidget
15838 * @mixins OO.ui.TabIndexedElement
15839 *
15840 * @constructor
15841 * @param {Object} [config] Configuration options
15842 */
15843 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
15844 // Parent constructor
15845 OO.ui.OutlineSelectWidget.super.call( this, config );
15846
15847 // Mixin constructors
15848 OO.ui.TabIndexedElement.call( this, config );
15849
15850 // Events
15851 this.$element.on( {
15852 focus: this.bindKeyDownListener.bind( this ),
15853 blur: this.unbindKeyDownListener.bind( this )
15854 } );
15855
15856 // Initialization
15857 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
15858 };
15859
15860 /* Setup */
15861
15862 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
15863 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
15864
15865 /**
15866 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
15867 *
15868 * ####Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.####
15869 *
15870 * @class
15871 * @extends OO.ui.SelectWidget
15872 * @mixins OO.ui.TabIndexedElement
15873 *
15874 * @constructor
15875 * @param {Object} [config] Configuration options
15876 */
15877 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
15878 // Parent constructor
15879 OO.ui.TabSelectWidget.super.call( this, config );
15880
15881 // Mixin constructors
15882 OO.ui.TabIndexedElement.call( this, config );
15883
15884 // Events
15885 this.$element.on( {
15886 focus: this.bindKeyDownListener.bind( this ),
15887 blur: this.unbindKeyDownListener.bind( this )
15888 } );
15889
15890 // Initialization
15891 this.$element.addClass( 'oo-ui-tabSelectWidget' );
15892 };
15893
15894 /* Setup */
15895
15896 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
15897 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.TabIndexedElement );
15898
15899 /**
15900 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
15901 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
15902 * visually by a slider in the leftmost position.
15903 *
15904 * @example
15905 * // Toggle switches in the 'off' and 'on' position.
15906 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
15907 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
15908 * value: true
15909 * } );
15910 *
15911 * // Create a FieldsetLayout to layout and label switches
15912 * var fieldset = new OO.ui.FieldsetLayout( {
15913 * label: 'Toggle switches'
15914 * } );
15915 * fieldset.addItems( [
15916 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
15917 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
15918 * ] );
15919 * $( 'body' ).append( fieldset.$element );
15920 *
15921 * @class
15922 * @extends OO.ui.ToggleWidget
15923 * @mixins OO.ui.TabIndexedElement
15924 *
15925 * @constructor
15926 * @param {Object} [config] Configuration options
15927 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
15928 * By default, the toggle switch is in the 'off' position.
15929 */
15930 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
15931 // Parent constructor
15932 OO.ui.ToggleSwitchWidget.super.call( this, config );
15933
15934 // Mixin constructors
15935 OO.ui.TabIndexedElement.call( this, config );
15936
15937 // Properties
15938 this.dragging = false;
15939 this.dragStart = null;
15940 this.sliding = false;
15941 this.$glow = $( '<span>' );
15942 this.$grip = $( '<span>' );
15943
15944 // Events
15945 this.$element.on( {
15946 click: this.onClick.bind( this ),
15947 keypress: this.onKeyPress.bind( this )
15948 } );
15949
15950 // Initialization
15951 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
15952 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
15953 this.$element
15954 .addClass( 'oo-ui-toggleSwitchWidget' )
15955 .attr( 'role', 'checkbox' )
15956 .append( this.$glow, this.$grip );
15957 };
15958
15959 /* Setup */
15960
15961 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
15962 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
15963
15964 /* Methods */
15965
15966 /**
15967 * Handle mouse click events.
15968 *
15969 * @private
15970 * @param {jQuery.Event} e Mouse click event
15971 */
15972 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
15973 if ( !this.isDisabled() && e.which === 1 ) {
15974 this.setValue( !this.value );
15975 }
15976 return false;
15977 };
15978
15979 /**
15980 * Handle key press events.
15981 *
15982 * @private
15983 * @param {jQuery.Event} e Key press event
15984 */
15985 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
15986 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
15987 this.setValue( !this.value );
15988 return false;
15989 }
15990 };
15991
15992 }( OO ) );