Merge "Allow for dynamic TTLs in getWithSetCallback()"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.11.3
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-12T12:15:37Z
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 if ( this.emit( 'click' ) ) {
4191 return false;
4192 }
4193 }
4194 };
4195
4196 /**
4197 * Handles key down events.
4198 *
4199 * @protected
4200 * @param {jQuery.Event} e Key down event
4201 */
4202 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4203 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4204 return;
4205 }
4206 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4207 // Run the keyup handler no matter where the key is when the button is let go, so we can
4208 // reliably remove the pressed class
4209 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4210 };
4211
4212 /**
4213 * Handles key up events.
4214 *
4215 * @protected
4216 * @param {jQuery.Event} e Key up event
4217 */
4218 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4219 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4220 return;
4221 }
4222 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4223 // Stop listening for keyup, since we only needed this once
4224 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4225 };
4226
4227 /**
4228 * Handles key press events.
4229 *
4230 * @protected
4231 * @param {jQuery.Event} e Key press event
4232 * @fires click
4233 */
4234 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4235 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4236 if ( this.emit( 'click' ) ) {
4237 return false;
4238 }
4239 }
4240 };
4241
4242 /**
4243 * Check if button has a frame.
4244 *
4245 * @return {boolean} Button is framed
4246 */
4247 OO.ui.ButtonElement.prototype.isFramed = function () {
4248 return this.framed;
4249 };
4250
4251 /**
4252 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4253 *
4254 * @param {boolean} [framed] Make button framed, omit to toggle
4255 * @chainable
4256 */
4257 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4258 framed = framed === undefined ? !this.framed : !!framed;
4259 if ( framed !== this.framed ) {
4260 this.framed = framed;
4261 this.$element
4262 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4263 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4264 this.updateThemeClasses();
4265 }
4266
4267 return this;
4268 };
4269
4270 /**
4271 * Set the button's access key.
4272 *
4273 * @param {string} accessKey Button's access key, use empty string to remove
4274 * @chainable
4275 */
4276 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4277 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4278
4279 if ( this.accessKey !== accessKey ) {
4280 if ( this.$button ) {
4281 if ( accessKey !== null ) {
4282 this.$button.attr( 'accesskey', accessKey );
4283 } else {
4284 this.$button.removeAttr( 'accesskey' );
4285 }
4286 }
4287 this.accessKey = accessKey;
4288 }
4289
4290 return this;
4291 };
4292
4293 /**
4294 * Set the button to its 'active' state.
4295 *
4296 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4297 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4298 * for other button types.
4299 *
4300 * @param {boolean} [value] Make button active
4301 * @chainable
4302 */
4303 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4304 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4305 return this;
4306 };
4307
4308 /**
4309 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4310 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4311 * items from the group is done through the interface the class provides.
4312 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4313 *
4314 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4315 *
4316 * @abstract
4317 * @class
4318 *
4319 * @constructor
4320 * @param {Object} [config] Configuration options
4321 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4322 * is omitted, the group element will use a generated `<div>`.
4323 */
4324 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4325 // Configuration initialization
4326 config = config || {};
4327
4328 // Properties
4329 this.$group = null;
4330 this.items = [];
4331 this.aggregateItemEvents = {};
4332
4333 // Initialization
4334 this.setGroupElement( config.$group || $( '<div>' ) );
4335 };
4336
4337 /* Methods */
4338
4339 /**
4340 * Set the group element.
4341 *
4342 * If an element is already set, items will be moved to the new element.
4343 *
4344 * @param {jQuery} $group Element to use as group
4345 */
4346 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4347 var i, len;
4348
4349 this.$group = $group;
4350 for ( i = 0, len = this.items.length; i < len; i++ ) {
4351 this.$group.append( this.items[ i ].$element );
4352 }
4353 };
4354
4355 /**
4356 * Check if a group contains no items.
4357 *
4358 * @return {boolean} Group is empty
4359 */
4360 OO.ui.GroupElement.prototype.isEmpty = function () {
4361 return !this.items.length;
4362 };
4363
4364 /**
4365 * Get all items in the group.
4366 *
4367 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4368 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4369 * from a group).
4370 *
4371 * @return {OO.ui.Element[]} An array of items.
4372 */
4373 OO.ui.GroupElement.prototype.getItems = function () {
4374 return this.items.slice( 0 );
4375 };
4376
4377 /**
4378 * Get an item by its data.
4379 *
4380 * Only the first item with matching data will be returned. To return all matching items,
4381 * use the #getItemsFromData method.
4382 *
4383 * @param {Object} data Item data to search for
4384 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4385 */
4386 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4387 var i, len, item,
4388 hash = OO.getHash( data );
4389
4390 for ( i = 0, len = this.items.length; i < len; i++ ) {
4391 item = this.items[ i ];
4392 if ( hash === OO.getHash( item.getData() ) ) {
4393 return item;
4394 }
4395 }
4396
4397 return null;
4398 };
4399
4400 /**
4401 * Get items by their data.
4402 *
4403 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4404 *
4405 * @param {Object} data Item data to search for
4406 * @return {OO.ui.Element[]} Items with equivalent data
4407 */
4408 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4409 var i, len, item,
4410 hash = OO.getHash( data ),
4411 items = [];
4412
4413 for ( i = 0, len = this.items.length; i < len; i++ ) {
4414 item = this.items[ i ];
4415 if ( hash === OO.getHash( item.getData() ) ) {
4416 items.push( item );
4417 }
4418 }
4419
4420 return items;
4421 };
4422
4423 /**
4424 * Aggregate the events emitted by the group.
4425 *
4426 * When events are aggregated, the group will listen to all contained items for the event,
4427 * and then emit the event under a new name. The new event will contain an additional leading
4428 * parameter containing the item that emitted the original event. Other arguments emitted from
4429 * the original event are passed through.
4430 *
4431 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4432 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4433 * A `null` value will remove aggregated events.
4434
4435 * @throws {Error} An error is thrown if aggregation already exists.
4436 */
4437 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4438 var i, len, item, add, remove, itemEvent, groupEvent;
4439
4440 for ( itemEvent in events ) {
4441 groupEvent = events[ itemEvent ];
4442
4443 // Remove existing aggregated event
4444 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4445 // Don't allow duplicate aggregations
4446 if ( groupEvent ) {
4447 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4448 }
4449 // Remove event aggregation from existing items
4450 for ( i = 0, len = this.items.length; i < len; i++ ) {
4451 item = this.items[ i ];
4452 if ( item.connect && item.disconnect ) {
4453 remove = {};
4454 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4455 item.disconnect( this, remove );
4456 }
4457 }
4458 // Prevent future items from aggregating event
4459 delete this.aggregateItemEvents[ itemEvent ];
4460 }
4461
4462 // Add new aggregate event
4463 if ( groupEvent ) {
4464 // Make future items aggregate event
4465 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4466 // Add event aggregation to existing items
4467 for ( i = 0, len = this.items.length; i < len; i++ ) {
4468 item = this.items[ i ];
4469 if ( item.connect && item.disconnect ) {
4470 add = {};
4471 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4472 item.connect( this, add );
4473 }
4474 }
4475 }
4476 }
4477 };
4478
4479 /**
4480 * Add items to the group.
4481 *
4482 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4483 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4484 *
4485 * @param {OO.ui.Element[]} items An array of items to add to the group
4486 * @param {number} [index] Index of the insertion point
4487 * @chainable
4488 */
4489 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4490 var i, len, item, event, events, currentIndex,
4491 itemElements = [];
4492
4493 for ( i = 0, len = items.length; i < len; i++ ) {
4494 item = items[ i ];
4495
4496 // Check if item exists then remove it first, effectively "moving" it
4497 currentIndex = $.inArray( item, this.items );
4498 if ( currentIndex >= 0 ) {
4499 this.removeItems( [ item ] );
4500 // Adjust index to compensate for removal
4501 if ( currentIndex < index ) {
4502 index--;
4503 }
4504 }
4505 // Add the item
4506 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4507 events = {};
4508 for ( event in this.aggregateItemEvents ) {
4509 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4510 }
4511 item.connect( this, events );
4512 }
4513 item.setElementGroup( this );
4514 itemElements.push( item.$element.get( 0 ) );
4515 }
4516
4517 if ( index === undefined || index < 0 || index >= this.items.length ) {
4518 this.$group.append( itemElements );
4519 this.items.push.apply( this.items, items );
4520 } else if ( index === 0 ) {
4521 this.$group.prepend( itemElements );
4522 this.items.unshift.apply( this.items, items );
4523 } else {
4524 this.items[ index ].$element.before( itemElements );
4525 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4526 }
4527
4528 return this;
4529 };
4530
4531 /**
4532 * Remove the specified items from a group.
4533 *
4534 * Removed items are detached (not removed) from the DOM so that they may be reused.
4535 * To remove all items from a group, you may wish to use the #clearItems method instead.
4536 *
4537 * @param {OO.ui.Element[]} items An array of items to remove
4538 * @chainable
4539 */
4540 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4541 var i, len, item, index, remove, itemEvent;
4542
4543 // Remove specific items
4544 for ( i = 0, len = items.length; i < len; i++ ) {
4545 item = items[ i ];
4546 index = $.inArray( item, this.items );
4547 if ( index !== -1 ) {
4548 if (
4549 item.connect && item.disconnect &&
4550 !$.isEmptyObject( this.aggregateItemEvents )
4551 ) {
4552 remove = {};
4553 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4554 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4555 }
4556 item.disconnect( this, remove );
4557 }
4558 item.setElementGroup( null );
4559 this.items.splice( index, 1 );
4560 item.$element.detach();
4561 }
4562 }
4563
4564 return this;
4565 };
4566
4567 /**
4568 * Clear all items from the group.
4569 *
4570 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4571 * To remove only a subset of items from a group, use the #removeItems method.
4572 *
4573 * @chainable
4574 */
4575 OO.ui.GroupElement.prototype.clearItems = function () {
4576 var i, len, item, remove, itemEvent;
4577
4578 // Remove all items
4579 for ( i = 0, len = this.items.length; i < len; i++ ) {
4580 item = this.items[ i ];
4581 if (
4582 item.connect && item.disconnect &&
4583 !$.isEmptyObject( this.aggregateItemEvents )
4584 ) {
4585 remove = {};
4586 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4587 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4588 }
4589 item.disconnect( this, remove );
4590 }
4591 item.setElementGroup( null );
4592 item.$element.detach();
4593 }
4594
4595 this.items = [];
4596 return this;
4597 };
4598
4599 /**
4600 * DraggableElement is a mixin class used to create elements that can be clicked
4601 * and dragged by a mouse to a new position within a group. This class must be used
4602 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4603 * the draggable elements.
4604 *
4605 * @abstract
4606 * @class
4607 *
4608 * @constructor
4609 */
4610 OO.ui.DraggableElement = function OoUiDraggableElement() {
4611 // Properties
4612 this.index = null;
4613
4614 // Initialize and events
4615 this.$element
4616 .attr( 'draggable', true )
4617 .addClass( 'oo-ui-draggableElement' )
4618 .on( {
4619 dragstart: this.onDragStart.bind( this ),
4620 dragover: this.onDragOver.bind( this ),
4621 dragend: this.onDragEnd.bind( this ),
4622 drop: this.onDrop.bind( this )
4623 } );
4624 };
4625
4626 OO.initClass( OO.ui.DraggableElement );
4627
4628 /* Events */
4629
4630 /**
4631 * @event dragstart
4632 *
4633 * A dragstart event is emitted when the user clicks and begins dragging an item.
4634 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4635 */
4636
4637 /**
4638 * @event dragend
4639 * A dragend event is emitted when the user drags an item and releases the mouse,
4640 * thus terminating the drag operation.
4641 */
4642
4643 /**
4644 * @event drop
4645 * A drop event is emitted when the user drags an item and then releases the mouse button
4646 * over a valid target.
4647 */
4648
4649 /* Static Properties */
4650
4651 /**
4652 * @inheritdoc OO.ui.ButtonElement
4653 */
4654 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4655
4656 /* Methods */
4657
4658 /**
4659 * Respond to dragstart event.
4660 *
4661 * @private
4662 * @param {jQuery.Event} event jQuery event
4663 * @fires dragstart
4664 */
4665 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4666 var dataTransfer = e.originalEvent.dataTransfer;
4667 // Define drop effect
4668 dataTransfer.dropEffect = 'none';
4669 dataTransfer.effectAllowed = 'move';
4670 // We must set up a dataTransfer data property or Firefox seems to
4671 // ignore the fact the element is draggable.
4672 try {
4673 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4674 } catch ( err ) {
4675 // The above is only for firefox. No need to set a catch clause
4676 // if it fails, move on.
4677 }
4678 // Add dragging class
4679 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4680 // Emit event
4681 this.emit( 'dragstart', this );
4682 return true;
4683 };
4684
4685 /**
4686 * Respond to dragend event.
4687 *
4688 * @private
4689 * @fires dragend
4690 */
4691 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4692 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4693 this.emit( 'dragend' );
4694 };
4695
4696 /**
4697 * Handle drop event.
4698 *
4699 * @private
4700 * @param {jQuery.Event} event jQuery event
4701 * @fires drop
4702 */
4703 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4704 e.preventDefault();
4705 this.emit( 'drop', e );
4706 };
4707
4708 /**
4709 * In order for drag/drop to work, the dragover event must
4710 * return false and stop propogation.
4711 *
4712 * @private
4713 */
4714 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4715 e.preventDefault();
4716 };
4717
4718 /**
4719 * Set item index.
4720 * Store it in the DOM so we can access from the widget drag event
4721 *
4722 * @private
4723 * @param {number} Item index
4724 */
4725 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4726 if ( this.index !== index ) {
4727 this.index = index;
4728 this.$element.data( 'index', index );
4729 }
4730 };
4731
4732 /**
4733 * Get item index
4734 *
4735 * @private
4736 * @return {number} Item index
4737 */
4738 OO.ui.DraggableElement.prototype.getIndex = function () {
4739 return this.index;
4740 };
4741
4742 /**
4743 * DraggableGroupElement is a mixin class used to create a group element to
4744 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4745 * The class is used with OO.ui.DraggableElement.
4746 *
4747 * @abstract
4748 * @class
4749 * @mixins OO.ui.GroupElement
4750 *
4751 * @constructor
4752 * @param {Object} [config] Configuration options
4753 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4754 * should match the layout of the items. Items displayed in a single row
4755 * or in several rows should use horizontal orientation. The vertical orientation should only be
4756 * used when the items are displayed in a single column. Defaults to 'vertical'
4757 */
4758 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4759 // Configuration initialization
4760 config = config || {};
4761
4762 // Parent constructor
4763 OO.ui.GroupElement.call( this, config );
4764
4765 // Properties
4766 this.orientation = config.orientation || 'vertical';
4767 this.dragItem = null;
4768 this.itemDragOver = null;
4769 this.itemKeys = {};
4770 this.sideInsertion = '';
4771
4772 // Events
4773 this.aggregate( {
4774 dragstart: 'itemDragStart',
4775 dragend: 'itemDragEnd',
4776 drop: 'itemDrop'
4777 } );
4778 this.connect( this, {
4779 itemDragStart: 'onItemDragStart',
4780 itemDrop: 'onItemDrop',
4781 itemDragEnd: 'onItemDragEnd'
4782 } );
4783 this.$element.on( {
4784 dragover: $.proxy( this.onDragOver, this ),
4785 dragleave: $.proxy( this.onDragLeave, this )
4786 } );
4787
4788 // Initialize
4789 if ( Array.isArray( config.items ) ) {
4790 this.addItems( config.items );
4791 }
4792 this.$placeholder = $( '<div>' )
4793 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4794 this.$element
4795 .addClass( 'oo-ui-draggableGroupElement' )
4796 .append( this.$status )
4797 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4798 .prepend( this.$placeholder );
4799 };
4800
4801 /* Setup */
4802 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4803
4804 /* Events */
4805
4806 /**
4807 * A 'reorder' event is emitted when the order of items in the group changes.
4808 *
4809 * @event reorder
4810 * @param {OO.ui.DraggableElement} item Reordered item
4811 * @param {number} [newIndex] New index for the item
4812 */
4813
4814 /* Methods */
4815
4816 /**
4817 * Respond to item drag start event
4818 *
4819 * @private
4820 * @param {OO.ui.DraggableElement} item Dragged item
4821 */
4822 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4823 var i, len;
4824
4825 // Map the index of each object
4826 for ( i = 0, len = this.items.length; i < len; i++ ) {
4827 this.items[ i ].setIndex( i );
4828 }
4829
4830 if ( this.orientation === 'horizontal' ) {
4831 // Set the height of the indicator
4832 this.$placeholder.css( {
4833 height: item.$element.outerHeight(),
4834 width: 2
4835 } );
4836 } else {
4837 // Set the width of the indicator
4838 this.$placeholder.css( {
4839 height: 2,
4840 width: item.$element.outerWidth()
4841 } );
4842 }
4843 this.setDragItem( item );
4844 };
4845
4846 /**
4847 * Respond to item drag end event
4848 *
4849 * @private
4850 */
4851 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4852 this.unsetDragItem();
4853 return false;
4854 };
4855
4856 /**
4857 * Handle drop event and switch the order of the items accordingly
4858 *
4859 * @private
4860 * @param {OO.ui.DraggableElement} item Dropped item
4861 * @fires reorder
4862 */
4863 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4864 var toIndex = item.getIndex();
4865 // Check if the dropped item is from the current group
4866 // TODO: Figure out a way to configure a list of legally droppable
4867 // elements even if they are not yet in the list
4868 if ( this.getDragItem() ) {
4869 // If the insertion point is 'after', the insertion index
4870 // is shifted to the right (or to the left in RTL, hence 'after')
4871 if ( this.sideInsertion === 'after' ) {
4872 toIndex++;
4873 }
4874 // Emit change event
4875 this.emit( 'reorder', this.getDragItem(), toIndex );
4876 }
4877 this.unsetDragItem();
4878 // Return false to prevent propogation
4879 return false;
4880 };
4881
4882 /**
4883 * Handle dragleave event.
4884 *
4885 * @private
4886 */
4887 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4888 // This means the item was dragged outside the widget
4889 this.$placeholder
4890 .css( 'left', 0 )
4891 .addClass( 'oo-ui-element-hidden' );
4892 };
4893
4894 /**
4895 * Respond to dragover event
4896 *
4897 * @private
4898 * @param {jQuery.Event} event Event details
4899 */
4900 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4901 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4902 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4903 clientX = e.originalEvent.clientX,
4904 clientY = e.originalEvent.clientY;
4905
4906 // Get the OptionWidget item we are dragging over
4907 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4908 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4909 if ( $optionWidget[ 0 ] ) {
4910 itemOffset = $optionWidget.offset();
4911 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4912 itemPosition = $optionWidget.position();
4913 itemIndex = $optionWidget.data( 'index' );
4914 }
4915
4916 if (
4917 itemOffset &&
4918 this.isDragging() &&
4919 itemIndex !== this.getDragItem().getIndex()
4920 ) {
4921 if ( this.orientation === 'horizontal' ) {
4922 // Calculate where the mouse is relative to the item width
4923 itemSize = itemBoundingRect.width;
4924 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4925 dragPosition = clientX;
4926 // Which side of the item we hover over will dictate
4927 // where the placeholder will appear, on the left or
4928 // on the right
4929 cssOutput = {
4930 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4931 top: itemPosition.top
4932 };
4933 } else {
4934 // Calculate where the mouse is relative to the item height
4935 itemSize = itemBoundingRect.height;
4936 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4937 dragPosition = clientY;
4938 // Which side of the item we hover over will dictate
4939 // where the placeholder will appear, on the top or
4940 // on the bottom
4941 cssOutput = {
4942 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4943 left: itemPosition.left
4944 };
4945 }
4946 // Store whether we are before or after an item to rearrange
4947 // For horizontal layout, we need to account for RTL, as this is flipped
4948 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4949 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4950 } else {
4951 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4952 }
4953 // Add drop indicator between objects
4954 this.$placeholder
4955 .css( cssOutput )
4956 .removeClass( 'oo-ui-element-hidden' );
4957 } else {
4958 // This means the item was dragged outside the widget
4959 this.$placeholder
4960 .css( 'left', 0 )
4961 .addClass( 'oo-ui-element-hidden' );
4962 }
4963 // Prevent default
4964 e.preventDefault();
4965 };
4966
4967 /**
4968 * Set a dragged item
4969 *
4970 * @param {OO.ui.DraggableElement} item Dragged item
4971 */
4972 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4973 this.dragItem = item;
4974 };
4975
4976 /**
4977 * Unset the current dragged item
4978 */
4979 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4980 this.dragItem = null;
4981 this.itemDragOver = null;
4982 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4983 this.sideInsertion = '';
4984 };
4985
4986 /**
4987 * Get the item that is currently being dragged.
4988 *
4989 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4990 */
4991 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4992 return this.dragItem;
4993 };
4994
4995 /**
4996 * Check if an item in the group is currently being dragged.
4997 *
4998 * @return {Boolean} Item is being dragged
4999 */
5000 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
5001 return this.getDragItem() !== null;
5002 };
5003
5004 /**
5005 * IconElement is often mixed into other classes to generate an icon.
5006 * Icons are graphics, about the size of normal text. They are used to aid the user
5007 * in locating a control or to convey information in a space-efficient way. See the
5008 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5009 * included in the library.
5010 *
5011 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5012 *
5013 * @abstract
5014 * @class
5015 *
5016 * @constructor
5017 * @param {Object} [config] Configuration options
5018 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5019 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5020 * the icon element be set to an existing icon instead of the one generated by this class, set a
5021 * value using a jQuery selection. For example:
5022 *
5023 * // Use a <div> tag instead of a <span>
5024 * $icon: $("<div>")
5025 * // Use an existing icon element instead of the one generated by the class
5026 * $icon: this.$element
5027 * // Use an icon element from a child widget
5028 * $icon: this.childwidget.$element
5029 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5030 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5031 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5032 * by the user's language.
5033 *
5034 * Example of an i18n map:
5035 *
5036 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5037 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5038 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5039 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5040 * text. The icon title is displayed when users move the mouse over the icon.
5041 */
5042 OO.ui.IconElement = function OoUiIconElement( config ) {
5043 // Configuration initialization
5044 config = config || {};
5045
5046 // Properties
5047 this.$icon = null;
5048 this.icon = null;
5049 this.iconTitle = null;
5050
5051 // Initialization
5052 this.setIcon( config.icon || this.constructor.static.icon );
5053 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5054 this.setIconElement( config.$icon || $( '<span>' ) );
5055 };
5056
5057 /* Setup */
5058
5059 OO.initClass( OO.ui.IconElement );
5060
5061 /* Static Properties */
5062
5063 /**
5064 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5065 * for i18n purposes and contains a `default` icon name and additional names keyed by
5066 * language code. The `default` name is used when no icon is keyed by the user's language.
5067 *
5068 * Example of an i18n map:
5069 *
5070 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5071 *
5072 * Note: the static property will be overridden if the #icon configuration is used.
5073 *
5074 * @static
5075 * @inheritable
5076 * @property {Object|string}
5077 */
5078 OO.ui.IconElement.static.icon = null;
5079
5080 /**
5081 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5082 * function that returns title text, or `null` for no title.
5083 *
5084 * The static property will be overridden if the #iconTitle configuration is used.
5085 *
5086 * @static
5087 * @inheritable
5088 * @property {string|Function|null}
5089 */
5090 OO.ui.IconElement.static.iconTitle = null;
5091
5092 /* Methods */
5093
5094 /**
5095 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5096 * applies to the specified icon element instead of the one created by the class. If an icon
5097 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5098 * and mixin methods will no longer affect the element.
5099 *
5100 * @param {jQuery} $icon Element to use as icon
5101 */
5102 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
5103 if ( this.$icon ) {
5104 this.$icon
5105 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5106 .removeAttr( 'title' );
5107 }
5108
5109 this.$icon = $icon
5110 .addClass( 'oo-ui-iconElement-icon' )
5111 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5112 if ( this.iconTitle !== null ) {
5113 this.$icon.attr( 'title', this.iconTitle );
5114 }
5115 };
5116
5117 /**
5118 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5119 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5120 * for an example.
5121 *
5122 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5123 * by language code, or `null` to remove the icon.
5124 * @chainable
5125 */
5126 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5127 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5128 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5129
5130 if ( this.icon !== icon ) {
5131 if ( this.$icon ) {
5132 if ( this.icon !== null ) {
5133 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5134 }
5135 if ( icon !== null ) {
5136 this.$icon.addClass( 'oo-ui-icon-' + icon );
5137 }
5138 }
5139 this.icon = icon;
5140 }
5141
5142 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5143 this.updateThemeClasses();
5144
5145 return this;
5146 };
5147
5148 /**
5149 * Set the icon title. Use `null` to remove the title.
5150 *
5151 * @param {string|Function|null} iconTitle A text string used as the icon title,
5152 * a function that returns title text, or `null` for no title.
5153 * @chainable
5154 */
5155 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5156 iconTitle = typeof iconTitle === 'function' ||
5157 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5158 OO.ui.resolveMsg( iconTitle ) : null;
5159
5160 if ( this.iconTitle !== iconTitle ) {
5161 this.iconTitle = iconTitle;
5162 if ( this.$icon ) {
5163 if ( this.iconTitle !== null ) {
5164 this.$icon.attr( 'title', iconTitle );
5165 } else {
5166 this.$icon.removeAttr( 'title' );
5167 }
5168 }
5169 }
5170
5171 return this;
5172 };
5173
5174 /**
5175 * Get the symbolic name of the icon.
5176 *
5177 * @return {string} Icon name
5178 */
5179 OO.ui.IconElement.prototype.getIcon = function () {
5180 return this.icon;
5181 };
5182
5183 /**
5184 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5185 *
5186 * @return {string} Icon title text
5187 */
5188 OO.ui.IconElement.prototype.getIconTitle = function () {
5189 return this.iconTitle;
5190 };
5191
5192 /**
5193 * IndicatorElement is often mixed into other classes to generate an indicator.
5194 * Indicators are small graphics that are generally used in two ways:
5195 *
5196 * - To draw attention to the status of an item. For example, an indicator might be
5197 * used to show that an item in a list has errors that need to be resolved.
5198 * - To clarify the function of a control that acts in an exceptional way (a button
5199 * that opens a menu instead of performing an action directly, for example).
5200 *
5201 * For a list of indicators included in the library, please see the
5202 * [OOjs UI documentation on MediaWiki] [1].
5203 *
5204 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5205 *
5206 * @abstract
5207 * @class
5208 *
5209 * @constructor
5210 * @param {Object} [config] Configuration options
5211 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5212 * configuration is omitted, the indicator element will use a generated `<span>`.
5213 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5214 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5215 * in the library.
5216 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5217 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5218 * or a function that returns title text. The indicator title is displayed when users move
5219 * the mouse over the indicator.
5220 */
5221 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5222 // Configuration initialization
5223 config = config || {};
5224
5225 // Properties
5226 this.$indicator = null;
5227 this.indicator = null;
5228 this.indicatorTitle = null;
5229
5230 // Initialization
5231 this.setIndicator( config.indicator || this.constructor.static.indicator );
5232 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5233 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5234 };
5235
5236 /* Setup */
5237
5238 OO.initClass( OO.ui.IndicatorElement );
5239
5240 /* Static Properties */
5241
5242 /**
5243 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5244 * The static property will be overridden if the #indicator configuration is used.
5245 *
5246 * @static
5247 * @inheritable
5248 * @property {string|null}
5249 */
5250 OO.ui.IndicatorElement.static.indicator = null;
5251
5252 /**
5253 * A text string used as the indicator title, a function that returns title text, or `null`
5254 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5255 *
5256 * @static
5257 * @inheritable
5258 * @property {string|Function|null}
5259 */
5260 OO.ui.IndicatorElement.static.indicatorTitle = null;
5261
5262 /* Methods */
5263
5264 /**
5265 * Set the indicator element.
5266 *
5267 * If an element is already set, it will be cleaned up before setting up the new element.
5268 *
5269 * @param {jQuery} $indicator Element to use as indicator
5270 */
5271 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5272 if ( this.$indicator ) {
5273 this.$indicator
5274 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5275 .removeAttr( 'title' );
5276 }
5277
5278 this.$indicator = $indicator
5279 .addClass( 'oo-ui-indicatorElement-indicator' )
5280 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5281 if ( this.indicatorTitle !== null ) {
5282 this.$indicator.attr( 'title', this.indicatorTitle );
5283 }
5284 };
5285
5286 /**
5287 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5288 *
5289 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5290 * @chainable
5291 */
5292 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5293 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5294
5295 if ( this.indicator !== indicator ) {
5296 if ( this.$indicator ) {
5297 if ( this.indicator !== null ) {
5298 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5299 }
5300 if ( indicator !== null ) {
5301 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5302 }
5303 }
5304 this.indicator = indicator;
5305 }
5306
5307 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5308 this.updateThemeClasses();
5309
5310 return this;
5311 };
5312
5313 /**
5314 * Set the indicator title.
5315 *
5316 * The title is displayed when a user moves the mouse over the indicator.
5317 *
5318 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5319 * `null` for no indicator title
5320 * @chainable
5321 */
5322 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5323 indicatorTitle = typeof indicatorTitle === 'function' ||
5324 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5325 OO.ui.resolveMsg( indicatorTitle ) : null;
5326
5327 if ( this.indicatorTitle !== indicatorTitle ) {
5328 this.indicatorTitle = indicatorTitle;
5329 if ( this.$indicator ) {
5330 if ( this.indicatorTitle !== null ) {
5331 this.$indicator.attr( 'title', indicatorTitle );
5332 } else {
5333 this.$indicator.removeAttr( 'title' );
5334 }
5335 }
5336 }
5337
5338 return this;
5339 };
5340
5341 /**
5342 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5343 *
5344 * @return {string} Symbolic name of indicator
5345 */
5346 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5347 return this.indicator;
5348 };
5349
5350 /**
5351 * Get the indicator title.
5352 *
5353 * The title is displayed when a user moves the mouse over the indicator.
5354 *
5355 * @return {string} Indicator title text
5356 */
5357 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5358 return this.indicatorTitle;
5359 };
5360
5361 /**
5362 * LabelElement is often mixed into other classes to generate a label, which
5363 * helps identify the function of an interface element.
5364 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5365 *
5366 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5367 *
5368 * @abstract
5369 * @class
5370 *
5371 * @constructor
5372 * @param {Object} [config] Configuration options
5373 * @cfg {jQuery} [$label] The label element created by the class. If this
5374 * configuration is omitted, the label element will use a generated `<span>`.
5375 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5376 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5377 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5378 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5379 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5380 * The label will be truncated to fit if necessary.
5381 */
5382 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5383 // Configuration initialization
5384 config = config || {};
5385
5386 // Properties
5387 this.$label = null;
5388 this.label = null;
5389 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5390
5391 // Initialization
5392 this.setLabel( config.label || this.constructor.static.label );
5393 this.setLabelElement( config.$label || $( '<span>' ) );
5394 };
5395
5396 /* Setup */
5397
5398 OO.initClass( OO.ui.LabelElement );
5399
5400 /* Events */
5401
5402 /**
5403 * @event labelChange
5404 * @param {string} value
5405 */
5406
5407 /* Static Properties */
5408
5409 /**
5410 * The label text. The label can be specified as a plaintext string, a function that will
5411 * produce a string in the future, or `null` for no label. The static value will
5412 * be overridden if a label is specified with the #label config option.
5413 *
5414 * @static
5415 * @inheritable
5416 * @property {string|Function|null}
5417 */
5418 OO.ui.LabelElement.static.label = null;
5419
5420 /* Methods */
5421
5422 /**
5423 * Set the label element.
5424 *
5425 * If an element is already set, it will be cleaned up before setting up the new element.
5426 *
5427 * @param {jQuery} $label Element to use as label
5428 */
5429 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5430 if ( this.$label ) {
5431 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5432 }
5433
5434 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5435 this.setLabelContent( this.label );
5436 };
5437
5438 /**
5439 * Set the label.
5440 *
5441 * An empty string will result in the label being hidden. A string containing only whitespace will
5442 * be converted to a single `&nbsp;`.
5443 *
5444 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5445 * text; or null for no label
5446 * @chainable
5447 */
5448 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5449 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5450 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5451
5452 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5453
5454 if ( this.label !== label ) {
5455 if ( this.$label ) {
5456 this.setLabelContent( label );
5457 }
5458 this.label = label;
5459 this.emit( 'labelChange' );
5460 }
5461
5462 return this;
5463 };
5464
5465 /**
5466 * Get the label.
5467 *
5468 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5469 * text; or null for no label
5470 */
5471 OO.ui.LabelElement.prototype.getLabel = function () {
5472 return this.label;
5473 };
5474
5475 /**
5476 * Fit the label.
5477 *
5478 * @chainable
5479 */
5480 OO.ui.LabelElement.prototype.fitLabel = function () {
5481 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5482 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5483 }
5484
5485 return this;
5486 };
5487
5488 /**
5489 * Set the content of the label.
5490 *
5491 * Do not call this method until after the label element has been set by #setLabelElement.
5492 *
5493 * @private
5494 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5495 * text; or null for no label
5496 */
5497 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5498 if ( typeof label === 'string' ) {
5499 if ( label.match( /^\s*$/ ) ) {
5500 // Convert whitespace only string to a single non-breaking space
5501 this.$label.html( '&nbsp;' );
5502 } else {
5503 this.$label.text( label );
5504 }
5505 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5506 this.$label.html( label.toString() );
5507 } else if ( label instanceof jQuery ) {
5508 this.$label.empty().append( label );
5509 } else {
5510 this.$label.empty();
5511 }
5512 };
5513
5514 /**
5515 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5516 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5517 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5518 * from the lookup menu, that value becomes the value of the input field.
5519 *
5520 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5521 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5522 * re-enable lookups.
5523 *
5524 * See the [OOjs UI demos][1] for an example.
5525 *
5526 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5527 *
5528 * @class
5529 * @abstract
5530 *
5531 * @constructor
5532 * @param {Object} [config] Configuration options
5533 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5534 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5535 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5536 * By default, the lookup menu is not generated and displayed until the user begins to type.
5537 */
5538 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5539 // Configuration initialization
5540 config = config || {};
5541
5542 // Properties
5543 this.$overlay = config.$overlay || this.$element;
5544 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5545 widget: this,
5546 input: this,
5547 $container: config.$container
5548 } );
5549
5550 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5551
5552 this.lookupCache = {};
5553 this.lookupQuery = null;
5554 this.lookupRequest = null;
5555 this.lookupsDisabled = false;
5556 this.lookupInputFocused = false;
5557
5558 // Events
5559 this.$input.on( {
5560 focus: this.onLookupInputFocus.bind( this ),
5561 blur: this.onLookupInputBlur.bind( this ),
5562 mousedown: this.onLookupInputMouseDown.bind( this )
5563 } );
5564 this.connect( this, { change: 'onLookupInputChange' } );
5565 this.lookupMenu.connect( this, {
5566 toggle: 'onLookupMenuToggle',
5567 choose: 'onLookupMenuItemChoose'
5568 } );
5569
5570 // Initialization
5571 this.$element.addClass( 'oo-ui-lookupElement' );
5572 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5573 this.$overlay.append( this.lookupMenu.$element );
5574 };
5575
5576 /* Methods */
5577
5578 /**
5579 * Handle input focus event.
5580 *
5581 * @protected
5582 * @param {jQuery.Event} e Input focus event
5583 */
5584 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5585 this.lookupInputFocused = true;
5586 this.populateLookupMenu();
5587 };
5588
5589 /**
5590 * Handle input blur event.
5591 *
5592 * @protected
5593 * @param {jQuery.Event} e Input blur event
5594 */
5595 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5596 this.closeLookupMenu();
5597 this.lookupInputFocused = false;
5598 };
5599
5600 /**
5601 * Handle input mouse down event.
5602 *
5603 * @protected
5604 * @param {jQuery.Event} e Input mouse down event
5605 */
5606 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5607 // Only open the menu if the input was already focused.
5608 // This way we allow the user to open the menu again after closing it with Esc
5609 // by clicking in the input. Opening (and populating) the menu when initially
5610 // clicking into the input is handled by the focus handler.
5611 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5612 this.populateLookupMenu();
5613 }
5614 };
5615
5616 /**
5617 * Handle input change event.
5618 *
5619 * @protected
5620 * @param {string} value New input value
5621 */
5622 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5623 if ( this.lookupInputFocused ) {
5624 this.populateLookupMenu();
5625 }
5626 };
5627
5628 /**
5629 * Handle the lookup menu being shown/hidden.
5630 *
5631 * @protected
5632 * @param {boolean} visible Whether the lookup menu is now visible.
5633 */
5634 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5635 if ( !visible ) {
5636 // When the menu is hidden, abort any active request and clear the menu.
5637 // This has to be done here in addition to closeLookupMenu(), because
5638 // MenuSelectWidget will close itself when the user presses Esc.
5639 this.abortLookupRequest();
5640 this.lookupMenu.clearItems();
5641 }
5642 };
5643
5644 /**
5645 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5646 *
5647 * @protected
5648 * @param {OO.ui.MenuOptionWidget} item Selected item
5649 */
5650 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5651 this.setValue( item.getData() );
5652 };
5653
5654 /**
5655 * Get lookup menu.
5656 *
5657 * @private
5658 * @return {OO.ui.TextInputMenuSelectWidget}
5659 */
5660 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5661 return this.lookupMenu;
5662 };
5663
5664 /**
5665 * Disable or re-enable lookups.
5666 *
5667 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5668 *
5669 * @param {boolean} disabled Disable lookups
5670 */
5671 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5672 this.lookupsDisabled = !!disabled;
5673 };
5674
5675 /**
5676 * Open the menu. If there are no entries in the menu, this does nothing.
5677 *
5678 * @private
5679 * @chainable
5680 */
5681 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5682 if ( !this.lookupMenu.isEmpty() ) {
5683 this.lookupMenu.toggle( true );
5684 }
5685 return this;
5686 };
5687
5688 /**
5689 * Close the menu, empty it, and abort any pending request.
5690 *
5691 * @private
5692 * @chainable
5693 */
5694 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5695 this.lookupMenu.toggle( false );
5696 this.abortLookupRequest();
5697 this.lookupMenu.clearItems();
5698 return this;
5699 };
5700
5701 /**
5702 * Request menu items based on the input's current value, and when they arrive,
5703 * populate the menu with these items and show the menu.
5704 *
5705 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5706 *
5707 * @private
5708 * @chainable
5709 */
5710 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5711 var widget = this,
5712 value = this.getValue();
5713
5714 if ( this.lookupsDisabled ) {
5715 return;
5716 }
5717
5718 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5719 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5720 this.closeLookupMenu();
5721 // Skip population if there is already a request pending for the current value
5722 } else if ( value !== this.lookupQuery ) {
5723 this.getLookupMenuItems()
5724 .done( function ( items ) {
5725 widget.lookupMenu.clearItems();
5726 if ( items.length ) {
5727 widget.lookupMenu
5728 .addItems( items )
5729 .toggle( true );
5730 widget.initializeLookupMenuSelection();
5731 } else {
5732 widget.lookupMenu.toggle( false );
5733 }
5734 } )
5735 .fail( function () {
5736 widget.lookupMenu.clearItems();
5737 } );
5738 }
5739
5740 return this;
5741 };
5742
5743 /**
5744 * Highlight the first selectable item in the menu.
5745 *
5746 * @private
5747 * @chainable
5748 */
5749 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5750 if ( !this.lookupMenu.getSelectedItem() ) {
5751 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
5752 }
5753 };
5754
5755 /**
5756 * Get lookup menu items for the current query.
5757 *
5758 * @private
5759 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5760 * the done event. If the request was aborted to make way for a subsequent request, this promise
5761 * will not be rejected: it will remain pending forever.
5762 */
5763 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5764 var widget = this,
5765 value = this.getValue(),
5766 deferred = $.Deferred(),
5767 ourRequest;
5768
5769 this.abortLookupRequest();
5770 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5771 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5772 } else {
5773 this.pushPending();
5774 this.lookupQuery = value;
5775 ourRequest = this.lookupRequest = this.getLookupRequest();
5776 ourRequest
5777 .always( function () {
5778 // We need to pop pending even if this is an old request, otherwise
5779 // the widget will remain pending forever.
5780 // TODO: this assumes that an aborted request will fail or succeed soon after
5781 // being aborted, or at least eventually. It would be nice if we could popPending()
5782 // at abort time, but only if we knew that we hadn't already called popPending()
5783 // for that request.
5784 widget.popPending();
5785 } )
5786 .done( function ( response ) {
5787 // If this is an old request (and aborting it somehow caused it to still succeed),
5788 // ignore its success completely
5789 if ( ourRequest === widget.lookupRequest ) {
5790 widget.lookupQuery = null;
5791 widget.lookupRequest = null;
5792 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
5793 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5794 }
5795 } )
5796 .fail( function () {
5797 // If this is an old request (or a request failing because it's being aborted),
5798 // ignore its failure completely
5799 if ( ourRequest === widget.lookupRequest ) {
5800 widget.lookupQuery = null;
5801 widget.lookupRequest = null;
5802 deferred.reject();
5803 }
5804 } );
5805 }
5806 return deferred.promise();
5807 };
5808
5809 /**
5810 * Abort the currently pending lookup request, if any.
5811 *
5812 * @private
5813 */
5814 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5815 var oldRequest = this.lookupRequest;
5816 if ( oldRequest ) {
5817 // First unset this.lookupRequest to the fail handler will notice
5818 // that the request is no longer current
5819 this.lookupRequest = null;
5820 this.lookupQuery = null;
5821 oldRequest.abort();
5822 }
5823 };
5824
5825 /**
5826 * Get a new request object of the current lookup query value.
5827 *
5828 * @protected
5829 * @abstract
5830 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5831 */
5832 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5833 // Stub, implemented in subclass
5834 return null;
5835 };
5836
5837 /**
5838 * Pre-process data returned by the request from #getLookupRequest.
5839 *
5840 * The return value of this function will be cached, and any further queries for the given value
5841 * will use the cache rather than doing API requests.
5842 *
5843 * @protected
5844 * @abstract
5845 * @param {Mixed} response Response from server
5846 * @return {Mixed} Cached result data
5847 */
5848 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5849 // Stub, implemented in subclass
5850 return [];
5851 };
5852
5853 /**
5854 * Get a list of menu option widgets from the (possibly cached) data returned by
5855 * #getLookupCacheDataFromResponse.
5856 *
5857 * @protected
5858 * @abstract
5859 * @param {Mixed} data Cached result data, usually an array
5860 * @return {OO.ui.MenuOptionWidget[]} Menu items
5861 */
5862 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5863 // Stub, implemented in subclass
5864 return [];
5865 };
5866
5867 /**
5868 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5869 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5870 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5871 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5872 *
5873 * @abstract
5874 * @class
5875 *
5876 * @constructor
5877 * @param {Object} [config] Configuration options
5878 * @cfg {Object} [popup] Configuration to pass to popup
5879 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5880 */
5881 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5882 // Configuration initialization
5883 config = config || {};
5884
5885 // Properties
5886 this.popup = new OO.ui.PopupWidget( $.extend(
5887 { autoClose: true },
5888 config.popup,
5889 { $autoCloseIgnore: this.$element }
5890 ) );
5891 };
5892
5893 /* Methods */
5894
5895 /**
5896 * Get popup.
5897 *
5898 * @return {OO.ui.PopupWidget} Popup widget
5899 */
5900 OO.ui.PopupElement.prototype.getPopup = function () {
5901 return this.popup;
5902 };
5903
5904 /**
5905 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5906 * additional functionality to an element created by another class. The class provides
5907 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5908 * which are used to customize the look and feel of a widget to better describe its
5909 * importance and functionality.
5910 *
5911 * The library currently contains the following styling flags for general use:
5912 *
5913 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5914 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5915 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5916 *
5917 * The flags affect the appearance of the buttons:
5918 *
5919 * @example
5920 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5921 * var button1 = new OO.ui.ButtonWidget( {
5922 * label: 'Constructive',
5923 * flags: 'constructive'
5924 * } );
5925 * var button2 = new OO.ui.ButtonWidget( {
5926 * label: 'Destructive',
5927 * flags: 'destructive'
5928 * } );
5929 * var button3 = new OO.ui.ButtonWidget( {
5930 * label: 'Progressive',
5931 * flags: 'progressive'
5932 * } );
5933 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5934 *
5935 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5936 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5937 *
5938 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5939 *
5940 * @abstract
5941 * @class
5942 *
5943 * @constructor
5944 * @param {Object} [config] Configuration options
5945 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5946 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5947 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5948 * @cfg {jQuery} [$flagged] The flagged element. By default,
5949 * the flagged functionality is applied to the element created by the class ($element).
5950 * If a different element is specified, the flagged functionality will be applied to it instead.
5951 */
5952 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5953 // Configuration initialization
5954 config = config || {};
5955
5956 // Properties
5957 this.flags = {};
5958 this.$flagged = null;
5959
5960 // Initialization
5961 this.setFlags( config.flags );
5962 this.setFlaggedElement( config.$flagged || this.$element );
5963 };
5964
5965 /* Events */
5966
5967 /**
5968 * @event flag
5969 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5970 * parameter contains the name of each modified flag and indicates whether it was
5971 * added or removed.
5972 *
5973 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5974 * that the flag was added, `false` that the flag was removed.
5975 */
5976
5977 /* Methods */
5978
5979 /**
5980 * Set the flagged element.
5981 *
5982 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5983 * If an element is already set, the method will remove the mixin’s effect on that element.
5984 *
5985 * @param {jQuery} $flagged Element that should be flagged
5986 */
5987 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5988 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5989 return 'oo-ui-flaggedElement-' + flag;
5990 } ).join( ' ' );
5991
5992 if ( this.$flagged ) {
5993 this.$flagged.removeClass( classNames );
5994 }
5995
5996 this.$flagged = $flagged.addClass( classNames );
5997 };
5998
5999 /**
6000 * Check if the specified flag is set.
6001 *
6002 * @param {string} flag Name of flag
6003 * @return {boolean} The flag is set
6004 */
6005 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
6006 return flag in this.flags;
6007 };
6008
6009 /**
6010 * Get the names of all flags set.
6011 *
6012 * @return {string[]} Flag names
6013 */
6014 OO.ui.FlaggedElement.prototype.getFlags = function () {
6015 return Object.keys( this.flags );
6016 };
6017
6018 /**
6019 * Clear all flags.
6020 *
6021 * @chainable
6022 * @fires flag
6023 */
6024 OO.ui.FlaggedElement.prototype.clearFlags = function () {
6025 var flag, className,
6026 changes = {},
6027 remove = [],
6028 classPrefix = 'oo-ui-flaggedElement-';
6029
6030 for ( flag in this.flags ) {
6031 className = classPrefix + flag;
6032 changes[ flag ] = false;
6033 delete this.flags[ flag ];
6034 remove.push( className );
6035 }
6036
6037 if ( this.$flagged ) {
6038 this.$flagged.removeClass( remove.join( ' ' ) );
6039 }
6040
6041 this.updateThemeClasses();
6042 this.emit( 'flag', changes );
6043
6044 return this;
6045 };
6046
6047 /**
6048 * Add one or more flags.
6049 *
6050 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6051 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6052 * be added (`true`) or removed (`false`).
6053 * @chainable
6054 * @fires flag
6055 */
6056 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
6057 var i, len, flag, className,
6058 changes = {},
6059 add = [],
6060 remove = [],
6061 classPrefix = 'oo-ui-flaggedElement-';
6062
6063 if ( typeof flags === 'string' ) {
6064 className = classPrefix + flags;
6065 // Set
6066 if ( !this.flags[ flags ] ) {
6067 this.flags[ flags ] = true;
6068 add.push( className );
6069 }
6070 } else if ( Array.isArray( flags ) ) {
6071 for ( i = 0, len = flags.length; i < len; i++ ) {
6072 flag = flags[ i ];
6073 className = classPrefix + flag;
6074 // Set
6075 if ( !this.flags[ flag ] ) {
6076 changes[ flag ] = true;
6077 this.flags[ flag ] = true;
6078 add.push( className );
6079 }
6080 }
6081 } else if ( OO.isPlainObject( flags ) ) {
6082 for ( flag in flags ) {
6083 className = classPrefix + flag;
6084 if ( flags[ flag ] ) {
6085 // Set
6086 if ( !this.flags[ flag ] ) {
6087 changes[ flag ] = true;
6088 this.flags[ flag ] = true;
6089 add.push( className );
6090 }
6091 } else {
6092 // Remove
6093 if ( this.flags[ flag ] ) {
6094 changes[ flag ] = false;
6095 delete this.flags[ flag ];
6096 remove.push( className );
6097 }
6098 }
6099 }
6100 }
6101
6102 if ( this.$flagged ) {
6103 this.$flagged
6104 .addClass( add.join( ' ' ) )
6105 .removeClass( remove.join( ' ' ) );
6106 }
6107
6108 this.updateThemeClasses();
6109 this.emit( 'flag', changes );
6110
6111 return this;
6112 };
6113
6114 /**
6115 * TitledElement is mixed into other classes to provide a `title` attribute.
6116 * Titles are rendered by the browser and are made visible when the user moves
6117 * the mouse over the element. Titles are not visible on touch devices.
6118 *
6119 * @example
6120 * // TitledElement provides a 'title' attribute to the
6121 * // ButtonWidget class
6122 * var button = new OO.ui.ButtonWidget( {
6123 * label: 'Button with Title',
6124 * title: 'I am a button'
6125 * } );
6126 * $( 'body' ).append( button.$element );
6127 *
6128 * @abstract
6129 * @class
6130 *
6131 * @constructor
6132 * @param {Object} [config] Configuration options
6133 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6134 * If this config is omitted, the title functionality is applied to $element, the
6135 * element created by the class.
6136 * @cfg {string|Function} [title] The title text or a function that returns text. If
6137 * this config is omitted, the value of the {@link #static-title static title} property is used.
6138 */
6139 OO.ui.TitledElement = function OoUiTitledElement( config ) {
6140 // Configuration initialization
6141 config = config || {};
6142
6143 // Properties
6144 this.$titled = null;
6145 this.title = null;
6146
6147 // Initialization
6148 this.setTitle( config.title || this.constructor.static.title );
6149 this.setTitledElement( config.$titled || this.$element );
6150 };
6151
6152 /* Setup */
6153
6154 OO.initClass( OO.ui.TitledElement );
6155
6156 /* Static Properties */
6157
6158 /**
6159 * The title text, a function that returns text, or `null` for no title. The value of the static property
6160 * is overridden if the #title config option is used.
6161 *
6162 * @static
6163 * @inheritable
6164 * @property {string|Function|null}
6165 */
6166 OO.ui.TitledElement.static.title = null;
6167
6168 /* Methods */
6169
6170 /**
6171 * Set the titled element.
6172 *
6173 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6174 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6175 *
6176 * @param {jQuery} $titled Element that should use the 'titled' functionality
6177 */
6178 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6179 if ( this.$titled ) {
6180 this.$titled.removeAttr( 'title' );
6181 }
6182
6183 this.$titled = $titled;
6184 if ( this.title ) {
6185 this.$titled.attr( 'title', this.title );
6186 }
6187 };
6188
6189 /**
6190 * Set title.
6191 *
6192 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6193 * @chainable
6194 */
6195 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6196 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6197
6198 if ( this.title !== title ) {
6199 if ( this.$titled ) {
6200 if ( title !== null ) {
6201 this.$titled.attr( 'title', title );
6202 } else {
6203 this.$titled.removeAttr( 'title' );
6204 }
6205 }
6206 this.title = title;
6207 }
6208
6209 return this;
6210 };
6211
6212 /**
6213 * Get title.
6214 *
6215 * @return {string} Title string
6216 */
6217 OO.ui.TitledElement.prototype.getTitle = function () {
6218 return this.title;
6219 };
6220
6221 /**
6222 * Element that can be automatically clipped to visible boundaries.
6223 *
6224 * Whenever the element's natural height changes, you have to call
6225 * #clip to make sure it's still clipping correctly.
6226 *
6227 * @abstract
6228 * @class
6229 *
6230 * @constructor
6231 * @param {Object} [config] Configuration options
6232 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6233 */
6234 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6235 // Configuration initialization
6236 config = config || {};
6237
6238 // Properties
6239 this.$clippable = null;
6240 this.clipping = false;
6241 this.clippedHorizontally = false;
6242 this.clippedVertically = false;
6243 this.$clippableContainer = null;
6244 this.$clippableScroller = null;
6245 this.$clippableWindow = null;
6246 this.idealWidth = null;
6247 this.idealHeight = null;
6248 this.onClippableContainerScrollHandler = this.clip.bind( this );
6249 this.onClippableWindowResizeHandler = this.clip.bind( this );
6250
6251 // Initialization
6252 this.setClippableElement( config.$clippable || this.$element );
6253 };
6254
6255 /* Methods */
6256
6257 /**
6258 * Set clippable element.
6259 *
6260 * If an element is already set, it will be cleaned up before setting up the new element.
6261 *
6262 * @param {jQuery} $clippable Element to make clippable
6263 */
6264 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6265 if ( this.$clippable ) {
6266 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6267 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6268 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6269 }
6270
6271 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6272 this.clip();
6273 };
6274
6275 /**
6276 * Toggle clipping.
6277 *
6278 * Do not turn clipping on until after the element is attached to the DOM and visible.
6279 *
6280 * @param {boolean} [clipping] Enable clipping, omit to toggle
6281 * @chainable
6282 */
6283 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6284 clipping = clipping === undefined ? !this.clipping : !!clipping;
6285
6286 if ( this.clipping !== clipping ) {
6287 this.clipping = clipping;
6288 if ( clipping ) {
6289 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6290 // If the clippable container is the root, we have to listen to scroll events and check
6291 // jQuery.scrollTop on the window because of browser inconsistencies
6292 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6293 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6294 this.$clippableContainer;
6295 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6296 this.$clippableWindow = $( this.getElementWindow() )
6297 .on( 'resize', this.onClippableWindowResizeHandler );
6298 // Initial clip after visible
6299 this.clip();
6300 } else {
6301 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6302 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6303
6304 this.$clippableContainer = null;
6305 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6306 this.$clippableScroller = null;
6307 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6308 this.$clippableWindow = null;
6309 }
6310 }
6311
6312 return this;
6313 };
6314
6315 /**
6316 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6317 *
6318 * @return {boolean} Element will be clipped to the visible area
6319 */
6320 OO.ui.ClippableElement.prototype.isClipping = function () {
6321 return this.clipping;
6322 };
6323
6324 /**
6325 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6326 *
6327 * @return {boolean} Part of the element is being clipped
6328 */
6329 OO.ui.ClippableElement.prototype.isClipped = function () {
6330 return this.clippedHorizontally || this.clippedVertically;
6331 };
6332
6333 /**
6334 * Check if the right of the element is being clipped by the nearest scrollable container.
6335 *
6336 * @return {boolean} Part of the element is being clipped
6337 */
6338 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6339 return this.clippedHorizontally;
6340 };
6341
6342 /**
6343 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6344 *
6345 * @return {boolean} Part of the element is being clipped
6346 */
6347 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6348 return this.clippedVertically;
6349 };
6350
6351 /**
6352 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6353 *
6354 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6355 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6356 */
6357 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6358 this.idealWidth = width;
6359 this.idealHeight = height;
6360
6361 if ( !this.clipping ) {
6362 // Update dimensions
6363 this.$clippable.css( { width: width, height: height } );
6364 }
6365 // While clipping, idealWidth and idealHeight are not considered
6366 };
6367
6368 /**
6369 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6370 * the element's natural height changes.
6371 *
6372 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6373 * overlapped by, the visible area of the nearest scrollable container.
6374 *
6375 * @chainable
6376 */
6377 OO.ui.ClippableElement.prototype.clip = function () {
6378 if ( !this.clipping ) {
6379 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6380 return this;
6381 }
6382
6383 var buffer = 7, // Chosen by fair dice roll
6384 cOffset = this.$clippable.offset(),
6385 $container = this.$clippableContainer.is( 'html, body' ) ?
6386 this.$clippableWindow : this.$clippableContainer,
6387 ccOffset = $container.offset() || { top: 0, left: 0 },
6388 ccHeight = $container.innerHeight() - buffer,
6389 ccWidth = $container.innerWidth() - buffer,
6390 cHeight = this.$clippable.outerHeight() + buffer,
6391 cWidth = this.$clippable.outerWidth() + buffer,
6392 scrollTop = this.$clippableScroller.scrollTop(),
6393 scrollLeft = this.$clippableScroller.scrollLeft(),
6394 desiredWidth = cOffset.left < 0 ?
6395 cWidth + cOffset.left :
6396 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6397 desiredHeight = cOffset.top < 0 ?
6398 cHeight + cOffset.top :
6399 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6400 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6401 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6402 clipWidth = desiredWidth < naturalWidth,
6403 clipHeight = desiredHeight < naturalHeight;
6404
6405 if ( clipWidth ) {
6406 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6407 } else {
6408 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6409 }
6410 if ( clipHeight ) {
6411 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6412 } else {
6413 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6414 }
6415
6416 // If we stopped clipping in at least one of the dimensions
6417 if ( !clipWidth || !clipHeight ) {
6418 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6419 }
6420
6421 this.clippedHorizontally = clipWidth;
6422 this.clippedVertically = clipHeight;
6423
6424 return this;
6425 };
6426
6427 /**
6428 * Generic toolbar tool.
6429 *
6430 * @abstract
6431 * @class
6432 * @extends OO.ui.Widget
6433 * @mixins OO.ui.IconElement
6434 * @mixins OO.ui.FlaggedElement
6435 * @mixins OO.ui.TabIndexedElement
6436 *
6437 * @constructor
6438 * @param {OO.ui.ToolGroup} toolGroup
6439 * @param {Object} [config] Configuration options
6440 * @cfg {string|Function} [title] Title text or a function that returns text
6441 */
6442 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6443 // Allow passing positional parameters inside the config object
6444 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6445 config = toolGroup;
6446 toolGroup = config.toolGroup;
6447 }
6448
6449 // Configuration initialization
6450 config = config || {};
6451
6452 // Parent constructor
6453 OO.ui.Tool.super.call( this, config );
6454
6455 // Properties
6456 this.toolGroup = toolGroup;
6457 this.toolbar = this.toolGroup.getToolbar();
6458 this.active = false;
6459 this.$title = $( '<span>' );
6460 this.$accel = $( '<span>' );
6461 this.$link = $( '<a>' );
6462 this.title = null;
6463
6464 // Mixin constructors
6465 OO.ui.IconElement.call( this, config );
6466 OO.ui.FlaggedElement.call( this, config );
6467 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) );
6468
6469 // Events
6470 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6471
6472 // Initialization
6473 this.$title.addClass( 'oo-ui-tool-title' );
6474 this.$accel
6475 .addClass( 'oo-ui-tool-accel' )
6476 .prop( {
6477 // This may need to be changed if the key names are ever localized,
6478 // but for now they are essentially written in English
6479 dir: 'ltr',
6480 lang: 'en'
6481 } );
6482 this.$link
6483 .addClass( 'oo-ui-tool-link' )
6484 .append( this.$icon, this.$title, this.$accel )
6485 .attr( 'role', 'button' );
6486 this.$element
6487 .data( 'oo-ui-tool', this )
6488 .addClass(
6489 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6490 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6491 )
6492 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
6493 .append( this.$link );
6494 this.setTitle( config.title || this.constructor.static.title );
6495 };
6496
6497 /* Setup */
6498
6499 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6500 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6501 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6502 OO.mixinClass( OO.ui.Tool, OO.ui.TabIndexedElement );
6503
6504 /* Events */
6505
6506 /**
6507 * @event select
6508 */
6509
6510 /* Static Properties */
6511
6512 /**
6513 * @static
6514 * @inheritdoc
6515 */
6516 OO.ui.Tool.static.tagName = 'span';
6517
6518 /**
6519 * Symbolic name of tool.
6520 *
6521 * @abstract
6522 * @static
6523 * @inheritable
6524 * @property {string}
6525 */
6526 OO.ui.Tool.static.name = '';
6527
6528 /**
6529 * Tool group.
6530 *
6531 * @abstract
6532 * @static
6533 * @inheritable
6534 * @property {string}
6535 */
6536 OO.ui.Tool.static.group = '';
6537
6538 /**
6539 * Tool title.
6540 *
6541 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6542 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6543 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6544 * appended to the title if the tool is part of a bar tool group.
6545 *
6546 * @abstract
6547 * @static
6548 * @inheritable
6549 * @property {string|Function} Title text or a function that returns text
6550 */
6551 OO.ui.Tool.static.title = '';
6552
6553 /**
6554 * Whether this tool should be displayed with both title and label when used in a bar tool group.
6555 * Normally only the icon is displayed, or only the label if no icon is given.
6556 *
6557 * @static
6558 * @inheritable
6559 * @property {boolean}
6560 */
6561 OO.ui.Tool.static.displayBothIconAndLabel = false;
6562
6563 /**
6564 * Tool can be automatically added to catch-all groups.
6565 *
6566 * @static
6567 * @inheritable
6568 * @property {boolean}
6569 */
6570 OO.ui.Tool.static.autoAddToCatchall = true;
6571
6572 /**
6573 * Tool can be automatically added to named groups.
6574 *
6575 * @static
6576 * @property {boolean}
6577 * @inheritable
6578 */
6579 OO.ui.Tool.static.autoAddToGroup = true;
6580
6581 /**
6582 * Check if this tool is compatible with given data.
6583 *
6584 * @static
6585 * @inheritable
6586 * @param {Mixed} data Data to check
6587 * @return {boolean} Tool can be used with data
6588 */
6589 OO.ui.Tool.static.isCompatibleWith = function () {
6590 return false;
6591 };
6592
6593 /* Methods */
6594
6595 /**
6596 * Handle the toolbar state being updated.
6597 *
6598 * This is an abstract method that must be overridden in a concrete subclass.
6599 *
6600 * @abstract
6601 */
6602 OO.ui.Tool.prototype.onUpdateState = function () {
6603 throw new Error(
6604 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6605 );
6606 };
6607
6608 /**
6609 * Handle the tool being selected.
6610 *
6611 * This is an abstract method that must be overridden in a concrete subclass.
6612 *
6613 * @abstract
6614 */
6615 OO.ui.Tool.prototype.onSelect = function () {
6616 throw new Error(
6617 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6618 );
6619 };
6620
6621 /**
6622 * Check if the button is active.
6623 *
6624 * @return {boolean} Button is active
6625 */
6626 OO.ui.Tool.prototype.isActive = function () {
6627 return this.active;
6628 };
6629
6630 /**
6631 * Make the button appear active or inactive.
6632 *
6633 * @param {boolean} state Make button appear active
6634 */
6635 OO.ui.Tool.prototype.setActive = function ( state ) {
6636 this.active = !!state;
6637 if ( this.active ) {
6638 this.$element.addClass( 'oo-ui-tool-active' );
6639 } else {
6640 this.$element.removeClass( 'oo-ui-tool-active' );
6641 }
6642 };
6643
6644 /**
6645 * Get the tool title.
6646 *
6647 * @param {string|Function} title Title text or a function that returns text
6648 * @chainable
6649 */
6650 OO.ui.Tool.prototype.setTitle = function ( title ) {
6651 this.title = OO.ui.resolveMsg( title );
6652 this.updateTitle();
6653 return this;
6654 };
6655
6656 /**
6657 * Get the tool title.
6658 *
6659 * @return {string} Title text
6660 */
6661 OO.ui.Tool.prototype.getTitle = function () {
6662 return this.title;
6663 };
6664
6665 /**
6666 * Get the tool's symbolic name.
6667 *
6668 * @return {string} Symbolic name of tool
6669 */
6670 OO.ui.Tool.prototype.getName = function () {
6671 return this.constructor.static.name;
6672 };
6673
6674 /**
6675 * Update the title.
6676 */
6677 OO.ui.Tool.prototype.updateTitle = function () {
6678 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6679 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6680 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6681 tooltipParts = [];
6682
6683 this.$title.text( this.title );
6684 this.$accel.text( accel );
6685
6686 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6687 tooltipParts.push( this.title );
6688 }
6689 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6690 tooltipParts.push( accel );
6691 }
6692 if ( tooltipParts.length ) {
6693 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6694 } else {
6695 this.$link.removeAttr( 'title' );
6696 }
6697 };
6698
6699 /**
6700 * Destroy tool.
6701 */
6702 OO.ui.Tool.prototype.destroy = function () {
6703 this.toolbar.disconnect( this );
6704 this.$element.remove();
6705 };
6706
6707 /**
6708 * Collection of tool groups.
6709 *
6710 * The following is a minimal example using several tools and tool groups.
6711 *
6712 * @example
6713 * // Create the toolbar
6714 * var toolFactory = new OO.ui.ToolFactory();
6715 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6716 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6717 *
6718 * // We will be placing status text in this element when tools are used
6719 * var $area = $( '<p>' ).text( 'Toolbar example' );
6720 *
6721 * // Define the tools that we're going to place in our toolbar
6722 *
6723 * // Create a class inheriting from OO.ui.Tool
6724 * function PictureTool() {
6725 * PictureTool.super.apply( this, arguments );
6726 * }
6727 * OO.inheritClass( PictureTool, OO.ui.Tool );
6728 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6729 * // of 'icon' and 'title' (displayed icon and text).
6730 * PictureTool.static.name = 'picture';
6731 * PictureTool.static.icon = 'picture';
6732 * PictureTool.static.title = 'Insert picture';
6733 * // Defines the action that will happen when this tool is selected (clicked).
6734 * PictureTool.prototype.onSelect = function () {
6735 * $area.text( 'Picture tool clicked!' );
6736 * // Never display this tool as "active" (selected).
6737 * this.setActive( false );
6738 * };
6739 * // Make this tool available in our toolFactory and thus our toolbar
6740 * toolFactory.register( PictureTool );
6741 *
6742 * // Register two more tools, nothing interesting here
6743 * function SettingsTool() {
6744 * SettingsTool.super.apply( this, arguments );
6745 * }
6746 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6747 * SettingsTool.static.name = 'settings';
6748 * SettingsTool.static.icon = 'settings';
6749 * SettingsTool.static.title = 'Change settings';
6750 * SettingsTool.prototype.onSelect = function () {
6751 * $area.text( 'Settings tool clicked!' );
6752 * this.setActive( false );
6753 * };
6754 * toolFactory.register( SettingsTool );
6755 *
6756 * // Register two more tools, nothing interesting here
6757 * function StuffTool() {
6758 * StuffTool.super.apply( this, arguments );
6759 * }
6760 * OO.inheritClass( StuffTool, OO.ui.Tool );
6761 * StuffTool.static.name = 'stuff';
6762 * StuffTool.static.icon = 'ellipsis';
6763 * StuffTool.static.title = 'More stuff';
6764 * StuffTool.prototype.onSelect = function () {
6765 * $area.text( 'More stuff tool clicked!' );
6766 * this.setActive( false );
6767 * };
6768 * toolFactory.register( StuffTool );
6769 *
6770 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6771 * // little popup window (a PopupWidget).
6772 * function HelpTool( toolGroup, config ) {
6773 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6774 * padded: true,
6775 * label: 'Help',
6776 * head: true
6777 * } }, config ) );
6778 * this.popup.$body.append( '<p>I am helpful!</p>' );
6779 * }
6780 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6781 * HelpTool.static.name = 'help';
6782 * HelpTool.static.icon = 'help';
6783 * HelpTool.static.title = 'Help';
6784 * toolFactory.register( HelpTool );
6785 *
6786 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6787 * // used once (but not all defined tools must be used).
6788 * toolbar.setup( [
6789 * {
6790 * // 'bar' tool groups display tools' icons only, side-by-side.
6791 * type: 'bar',
6792 * include: [ 'picture', 'help' ]
6793 * },
6794 * {
6795 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6796 * type: 'list',
6797 * indicator: 'down',
6798 * label: 'More',
6799 * include: [ 'settings', 'stuff' ]
6800 * }
6801 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6802 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
6803 * // since it's more complicated to use. (See the next example snippet on this page.)
6804 * ] );
6805 *
6806 * // Create some UI around the toolbar and place it in the document
6807 * var frame = new OO.ui.PanelLayout( {
6808 * expanded: false,
6809 * framed: true
6810 * } );
6811 * var contentFrame = new OO.ui.PanelLayout( {
6812 * expanded: false,
6813 * padded: true
6814 * } );
6815 * frame.$element.append(
6816 * toolbar.$element,
6817 * contentFrame.$element.append( $area )
6818 * );
6819 * $( 'body' ).append( frame.$element );
6820 *
6821 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6822 * // document.
6823 * toolbar.initialize();
6824 *
6825 * The following example extends the previous one to illustrate 'menu' tool groups and the usage of
6826 * 'updateState' event.
6827 *
6828 * @example
6829 * // Create the toolbar
6830 * var toolFactory = new OO.ui.ToolFactory();
6831 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6832 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6833 *
6834 * // We will be placing status text in this element when tools are used
6835 * var $area = $( '<p>' ).text( 'Toolbar example' );
6836 *
6837 * // Define the tools that we're going to place in our toolbar
6838 *
6839 * // Create a class inheriting from OO.ui.Tool
6840 * function PictureTool() {
6841 * PictureTool.super.apply( this, arguments );
6842 * }
6843 * OO.inheritClass( PictureTool, OO.ui.Tool );
6844 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6845 * // of 'icon' and 'title' (displayed icon and text).
6846 * PictureTool.static.name = 'picture';
6847 * PictureTool.static.icon = 'picture';
6848 * PictureTool.static.title = 'Insert picture';
6849 * // Defines the action that will happen when this tool is selected (clicked).
6850 * PictureTool.prototype.onSelect = function () {
6851 * $area.text( 'Picture tool clicked!' );
6852 * // Never display this tool as "active" (selected).
6853 * this.setActive( false );
6854 * };
6855 * // The toolbar can be synchronized with the state of some external stuff, like a text
6856 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
6857 * // when the text cursor was inside bolded text). Here we simply disable this feature.
6858 * PictureTool.prototype.onUpdateState = function () {
6859 * };
6860 * // Make this tool available in our toolFactory and thus our toolbar
6861 * toolFactory.register( PictureTool );
6862 *
6863 * // Register two more tools, nothing interesting here
6864 * function SettingsTool() {
6865 * SettingsTool.super.apply( this, arguments );
6866 * this.reallyActive = false;
6867 * }
6868 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6869 * SettingsTool.static.name = 'settings';
6870 * SettingsTool.static.icon = 'settings';
6871 * SettingsTool.static.title = 'Change settings';
6872 * SettingsTool.prototype.onSelect = function () {
6873 * $area.text( 'Settings tool clicked!' );
6874 * // Toggle the active state on each click
6875 * this.reallyActive = !this.reallyActive;
6876 * this.setActive( this.reallyActive );
6877 * // To update the menu label
6878 * this.toolbar.emit( 'updateState' );
6879 * };
6880 * SettingsTool.prototype.onUpdateState = function () {
6881 * };
6882 * toolFactory.register( SettingsTool );
6883 *
6884 * // Register two more tools, nothing interesting here
6885 * function StuffTool() {
6886 * StuffTool.super.apply( this, arguments );
6887 * this.reallyActive = false;
6888 * }
6889 * OO.inheritClass( StuffTool, OO.ui.Tool );
6890 * StuffTool.static.name = 'stuff';
6891 * StuffTool.static.icon = 'ellipsis';
6892 * StuffTool.static.title = 'More stuff';
6893 * StuffTool.prototype.onSelect = function () {
6894 * $area.text( 'More stuff tool clicked!' );
6895 * // Toggle the active state on each click
6896 * this.reallyActive = !this.reallyActive;
6897 * this.setActive( this.reallyActive );
6898 * // To update the menu label
6899 * this.toolbar.emit( 'updateState' );
6900 * };
6901 * StuffTool.prototype.onUpdateState = function () {
6902 * };
6903 * toolFactory.register( StuffTool );
6904 *
6905 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6906 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
6907 * function HelpTool( toolGroup, config ) {
6908 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6909 * padded: true,
6910 * label: 'Help',
6911 * head: true
6912 * } }, config ) );
6913 * this.popup.$body.append( '<p>I am helpful!</p>' );
6914 * }
6915 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6916 * HelpTool.static.name = 'help';
6917 * HelpTool.static.icon = 'help';
6918 * HelpTool.static.title = 'Help';
6919 * toolFactory.register( HelpTool );
6920 *
6921 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6922 * // used once (but not all defined tools must be used).
6923 * toolbar.setup( [
6924 * {
6925 * // 'bar' tool groups display tools' icons only, side-by-side.
6926 * type: 'bar',
6927 * include: [ 'picture', 'help' ]
6928 * },
6929 * {
6930 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
6931 * // Menu label indicates which items are selected.
6932 * type: 'menu',
6933 * indicator: 'down',
6934 * include: [ 'settings', 'stuff' ]
6935 * }
6936 * ] );
6937 *
6938 * // Create some UI around the toolbar and place it in the document
6939 * var frame = new OO.ui.PanelLayout( {
6940 * expanded: false,
6941 * framed: true
6942 * } );
6943 * var contentFrame = new OO.ui.PanelLayout( {
6944 * expanded: false,
6945 * padded: true
6946 * } );
6947 * frame.$element.append(
6948 * toolbar.$element,
6949 * contentFrame.$element.append( $area )
6950 * );
6951 * $( 'body' ).append( frame.$element );
6952 *
6953 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6954 * // document.
6955 * toolbar.initialize();
6956 * toolbar.emit( 'updateState' );
6957 *
6958 * @class
6959 * @extends OO.ui.Element
6960 * @mixins OO.EventEmitter
6961 * @mixins OO.ui.GroupElement
6962 *
6963 * @constructor
6964 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6965 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6966 * @param {Object} [config] Configuration options
6967 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6968 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6969 */
6970 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6971 // Allow passing positional parameters inside the config object
6972 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6973 config = toolFactory;
6974 toolFactory = config.toolFactory;
6975 toolGroupFactory = config.toolGroupFactory;
6976 }
6977
6978 // Configuration initialization
6979 config = config || {};
6980
6981 // Parent constructor
6982 OO.ui.Toolbar.super.call( this, config );
6983
6984 // Mixin constructors
6985 OO.EventEmitter.call( this );
6986 OO.ui.GroupElement.call( this, config );
6987
6988 // Properties
6989 this.toolFactory = toolFactory;
6990 this.toolGroupFactory = toolGroupFactory;
6991 this.groups = [];
6992 this.tools = {};
6993 this.$bar = $( '<div>' );
6994 this.$actions = $( '<div>' );
6995 this.initialized = false;
6996 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6997
6998 // Events
6999 this.$element
7000 .add( this.$bar ).add( this.$group ).add( this.$actions )
7001 .on( 'mousedown keydown', this.onPointerDown.bind( this ) );
7002
7003 // Initialization
7004 this.$group.addClass( 'oo-ui-toolbar-tools' );
7005 if ( config.actions ) {
7006 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
7007 }
7008 this.$bar
7009 .addClass( 'oo-ui-toolbar-bar' )
7010 .append( this.$group, '<div style="clear:both"></div>' );
7011 if ( config.shadow ) {
7012 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7013 }
7014 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
7015 };
7016
7017 /* Setup */
7018
7019 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
7020 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
7021 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
7022
7023 /* Methods */
7024
7025 /**
7026 * Get the tool factory.
7027 *
7028 * @return {OO.ui.ToolFactory} Tool factory
7029 */
7030 OO.ui.Toolbar.prototype.getToolFactory = function () {
7031 return this.toolFactory;
7032 };
7033
7034 /**
7035 * Get the tool group factory.
7036 *
7037 * @return {OO.Factory} Tool group factory
7038 */
7039 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
7040 return this.toolGroupFactory;
7041 };
7042
7043 /**
7044 * Handles mouse down events.
7045 *
7046 * @param {jQuery.Event} e Mouse down event
7047 */
7048 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
7049 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
7050 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
7051 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
7052 return false;
7053 }
7054 };
7055
7056 /**
7057 * Handle window resize event.
7058 *
7059 * @private
7060 * @param {jQuery.Event} e Window resize event
7061 */
7062 OO.ui.Toolbar.prototype.onWindowResize = function () {
7063 this.$element.toggleClass(
7064 'oo-ui-toolbar-narrow',
7065 this.$bar.width() <= this.narrowThreshold
7066 );
7067 };
7068
7069 /**
7070 * Sets up handles and preloads required information for the toolbar to work.
7071 * This must be called after it is attached to a visible document and before doing anything else.
7072 */
7073 OO.ui.Toolbar.prototype.initialize = function () {
7074 this.initialized = true;
7075 this.narrowThreshold = this.$group.width() + this.$actions.width();
7076 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
7077 this.onWindowResize();
7078 };
7079
7080 /**
7081 * Setup toolbar.
7082 *
7083 * Tools can be specified in the following ways:
7084 *
7085 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7086 * - All tools in a group: `{ group: 'group-name' }`
7087 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
7088 *
7089 * @param {Object.<string,Array>} groups List of tool group configurations
7090 * @param {Array|string} [groups.include] Tools to include
7091 * @param {Array|string} [groups.exclude] Tools to exclude
7092 * @param {Array|string} [groups.promote] Tools to promote to the beginning
7093 * @param {Array|string} [groups.demote] Tools to demote to the end
7094 */
7095 OO.ui.Toolbar.prototype.setup = function ( groups ) {
7096 var i, len, type, group,
7097 items = [],
7098 defaultType = 'bar';
7099
7100 // Cleanup previous groups
7101 this.reset();
7102
7103 // Build out new groups
7104 for ( i = 0, len = groups.length; i < len; i++ ) {
7105 group = groups[ i ];
7106 if ( group.include === '*' ) {
7107 // Apply defaults to catch-all groups
7108 if ( group.type === undefined ) {
7109 group.type = 'list';
7110 }
7111 if ( group.label === undefined ) {
7112 group.label = OO.ui.msg( 'ooui-toolbar-more' );
7113 }
7114 }
7115 // Check type has been registered
7116 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
7117 items.push(
7118 this.getToolGroupFactory().create( type, this, group )
7119 );
7120 }
7121 this.addItems( items );
7122 };
7123
7124 /**
7125 * Remove all tools and groups from the toolbar.
7126 */
7127 OO.ui.Toolbar.prototype.reset = function () {
7128 var i, len;
7129
7130 this.groups = [];
7131 this.tools = {};
7132 for ( i = 0, len = this.items.length; i < len; i++ ) {
7133 this.items[ i ].destroy();
7134 }
7135 this.clearItems();
7136 };
7137
7138 /**
7139 * Destroys toolbar, removing event handlers and DOM elements.
7140 *
7141 * Call this whenever you are done using a toolbar.
7142 */
7143 OO.ui.Toolbar.prototype.destroy = function () {
7144 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
7145 this.reset();
7146 this.$element.remove();
7147 };
7148
7149 /**
7150 * Check if tool has not been used yet.
7151 *
7152 * @param {string} name Symbolic name of tool
7153 * @return {boolean} Tool is available
7154 */
7155 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
7156 return !this.tools[ name ];
7157 };
7158
7159 /**
7160 * Prevent tool from being used again.
7161 *
7162 * @param {OO.ui.Tool} tool Tool to reserve
7163 */
7164 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
7165 this.tools[ tool.getName() ] = tool;
7166 };
7167
7168 /**
7169 * Allow tool to be used again.
7170 *
7171 * @param {OO.ui.Tool} tool Tool to release
7172 */
7173 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7174 delete this.tools[ tool.getName() ];
7175 };
7176
7177 /**
7178 * Get accelerator label for tool.
7179 *
7180 * This is a stub that should be overridden to provide access to accelerator information.
7181 *
7182 * @param {string} name Symbolic name of tool
7183 * @return {string|undefined} Tool accelerator label if available
7184 */
7185 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7186 return undefined;
7187 };
7188
7189 /**
7190 * Collection of tools.
7191 *
7192 * Tools can be specified in the following ways:
7193 *
7194 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7195 * - All tools in a group: `{ group: 'group-name' }`
7196 * - All tools: `'*'`
7197 *
7198 * @abstract
7199 * @class
7200 * @extends OO.ui.Widget
7201 * @mixins OO.ui.GroupElement
7202 *
7203 * @constructor
7204 * @param {OO.ui.Toolbar} toolbar
7205 * @param {Object} [config] Configuration options
7206 * @cfg {Array|string} [include=[]] List of tools to include
7207 * @cfg {Array|string} [exclude=[]] List of tools to exclude
7208 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
7209 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
7210 */
7211 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7212 // Allow passing positional parameters inside the config object
7213 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7214 config = toolbar;
7215 toolbar = config.toolbar;
7216 }
7217
7218 // Configuration initialization
7219 config = config || {};
7220
7221 // Parent constructor
7222 OO.ui.ToolGroup.super.call( this, config );
7223
7224 // Mixin constructors
7225 OO.ui.GroupElement.call( this, config );
7226
7227 // Properties
7228 this.toolbar = toolbar;
7229 this.tools = {};
7230 this.pressed = null;
7231 this.autoDisabled = false;
7232 this.include = config.include || [];
7233 this.exclude = config.exclude || [];
7234 this.promote = config.promote || [];
7235 this.demote = config.demote || [];
7236 this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this );
7237
7238 // Events
7239 this.$element.on( {
7240 mousedown: this.onMouseKeyDown.bind( this ),
7241 mouseup: this.onMouseKeyUp.bind( this ),
7242 keydown: this.onMouseKeyDown.bind( this ),
7243 keyup: this.onMouseKeyUp.bind( this ),
7244 focus: this.onMouseOverFocus.bind( this ),
7245 blur: this.onMouseOutBlur.bind( this ),
7246 mouseover: this.onMouseOverFocus.bind( this ),
7247 mouseout: this.onMouseOutBlur.bind( this )
7248 } );
7249 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7250 this.aggregate( { disable: 'itemDisable' } );
7251 this.connect( this, { itemDisable: 'updateDisabled' } );
7252
7253 // Initialization
7254 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7255 this.$element
7256 .addClass( 'oo-ui-toolGroup' )
7257 .append( this.$group );
7258 this.populate();
7259 };
7260
7261 /* Setup */
7262
7263 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7264 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
7265
7266 /* Events */
7267
7268 /**
7269 * @event update
7270 */
7271
7272 /* Static Properties */
7273
7274 /**
7275 * Show labels in tooltips.
7276 *
7277 * @static
7278 * @inheritable
7279 * @property {boolean}
7280 */
7281 OO.ui.ToolGroup.static.titleTooltips = false;
7282
7283 /**
7284 * Show acceleration labels in tooltips.
7285 *
7286 * @static
7287 * @inheritable
7288 * @property {boolean}
7289 */
7290 OO.ui.ToolGroup.static.accelTooltips = false;
7291
7292 /**
7293 * Automatically disable the toolgroup when all tools are disabled
7294 *
7295 * @static
7296 * @inheritable
7297 * @property {boolean}
7298 */
7299 OO.ui.ToolGroup.static.autoDisable = true;
7300
7301 /* Methods */
7302
7303 /**
7304 * @inheritdoc
7305 */
7306 OO.ui.ToolGroup.prototype.isDisabled = function () {
7307 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
7308 };
7309
7310 /**
7311 * @inheritdoc
7312 */
7313 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7314 var i, item, allDisabled = true;
7315
7316 if ( this.constructor.static.autoDisable ) {
7317 for ( i = this.items.length - 1; i >= 0; i-- ) {
7318 item = this.items[ i ];
7319 if ( !item.isDisabled() ) {
7320 allDisabled = false;
7321 break;
7322 }
7323 }
7324 this.autoDisabled = allDisabled;
7325 }
7326 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
7327 };
7328
7329 /**
7330 * Handle mouse down and key down events.
7331 *
7332 * @param {jQuery.Event} e Mouse down or key down event
7333 */
7334 OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
7335 if (
7336 !this.isDisabled() &&
7337 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7338 ) {
7339 this.pressed = this.getTargetTool( e );
7340 if ( this.pressed ) {
7341 this.pressed.setActive( true );
7342 this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
7343 this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
7344 }
7345 return false;
7346 }
7347 };
7348
7349 /**
7350 * Handle captured mouse up and key up events.
7351 *
7352 * @param {Event} e Mouse up or key up event
7353 */
7354 OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) {
7355 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true );
7356 this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true );
7357 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7358 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7359 this.onMouseKeyUp( e );
7360 };
7361
7362 /**
7363 * Handle mouse up and key up events.
7364 *
7365 * @param {jQuery.Event} e Mouse up or key up event
7366 */
7367 OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
7368 var tool = this.getTargetTool( e );
7369
7370 if (
7371 !this.isDisabled() && this.pressed && this.pressed === tool &&
7372 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
7373 ) {
7374 this.pressed.onSelect();
7375 this.pressed = null;
7376 return false;
7377 }
7378
7379 this.pressed = null;
7380 };
7381
7382 /**
7383 * Handle mouse over and focus events.
7384 *
7385 * @param {jQuery.Event} e Mouse over or focus event
7386 */
7387 OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
7388 var tool = this.getTargetTool( e );
7389
7390 if ( this.pressed && this.pressed === tool ) {
7391 this.pressed.setActive( true );
7392 }
7393 };
7394
7395 /**
7396 * Handle mouse out and blur events.
7397 *
7398 * @param {jQuery.Event} e Mouse out or blur event
7399 */
7400 OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
7401 var tool = this.getTargetTool( e );
7402
7403 if ( this.pressed && this.pressed === tool ) {
7404 this.pressed.setActive( false );
7405 }
7406 };
7407
7408 /**
7409 * Get the closest tool to a jQuery.Event.
7410 *
7411 * Only tool links are considered, which prevents other elements in the tool such as popups from
7412 * triggering tool group interactions.
7413 *
7414 * @private
7415 * @param {jQuery.Event} e
7416 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7417 */
7418 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7419 var tool,
7420 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7421
7422 if ( $item.length ) {
7423 tool = $item.parent().data( 'oo-ui-tool' );
7424 }
7425
7426 return tool && !tool.isDisabled() ? tool : null;
7427 };
7428
7429 /**
7430 * Handle tool registry register events.
7431 *
7432 * If a tool is registered after the group is created, we must repopulate the list to account for:
7433 *
7434 * - a tool being added that may be included
7435 * - a tool already included being overridden
7436 *
7437 * @param {string} name Symbolic name of tool
7438 */
7439 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7440 this.populate();
7441 };
7442
7443 /**
7444 * Get the toolbar this group is in.
7445 *
7446 * @return {OO.ui.Toolbar} Toolbar of group
7447 */
7448 OO.ui.ToolGroup.prototype.getToolbar = function () {
7449 return this.toolbar;
7450 };
7451
7452 /**
7453 * Add and remove tools based on configuration.
7454 */
7455 OO.ui.ToolGroup.prototype.populate = function () {
7456 var i, len, name, tool,
7457 toolFactory = this.toolbar.getToolFactory(),
7458 names = {},
7459 add = [],
7460 remove = [],
7461 list = this.toolbar.getToolFactory().getTools(
7462 this.include, this.exclude, this.promote, this.demote
7463 );
7464
7465 // Build a list of needed tools
7466 for ( i = 0, len = list.length; i < len; i++ ) {
7467 name = list[ i ];
7468 if (
7469 // Tool exists
7470 toolFactory.lookup( name ) &&
7471 // Tool is available or is already in this group
7472 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7473 ) {
7474 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7475 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7476 this.toolbar.tools[ name ] = true;
7477 tool = this.tools[ name ];
7478 if ( !tool ) {
7479 // Auto-initialize tools on first use
7480 this.tools[ name ] = tool = toolFactory.create( name, this );
7481 tool.updateTitle();
7482 }
7483 this.toolbar.reserveTool( tool );
7484 add.push( tool );
7485 names[ name ] = true;
7486 }
7487 }
7488 // Remove tools that are no longer needed
7489 for ( name in this.tools ) {
7490 if ( !names[ name ] ) {
7491 this.tools[ name ].destroy();
7492 this.toolbar.releaseTool( this.tools[ name ] );
7493 remove.push( this.tools[ name ] );
7494 delete this.tools[ name ];
7495 }
7496 }
7497 if ( remove.length ) {
7498 this.removeItems( remove );
7499 }
7500 // Update emptiness state
7501 if ( add.length ) {
7502 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7503 } else {
7504 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7505 }
7506 // Re-add tools (moving existing ones to new locations)
7507 this.addItems( add );
7508 // Disabled state may depend on items
7509 this.updateDisabled();
7510 };
7511
7512 /**
7513 * Destroy tool group.
7514 */
7515 OO.ui.ToolGroup.prototype.destroy = function () {
7516 var name;
7517
7518 this.clearItems();
7519 this.toolbar.getToolFactory().disconnect( this );
7520 for ( name in this.tools ) {
7521 this.toolbar.releaseTool( this.tools[ name ] );
7522 this.tools[ name ].disconnect( this ).destroy();
7523 delete this.tools[ name ];
7524 }
7525 this.$element.remove();
7526 };
7527
7528 /**
7529 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7530 * consists of a header that contains the dialog title, a body with the message, and a footer that
7531 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7532 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7533 *
7534 * There are two basic types of message dialogs, confirmation and alert:
7535 *
7536 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7537 * more details about the consequences.
7538 * - **alert**: the dialog title describes which event occurred and the message provides more information
7539 * about why the event occurred.
7540 *
7541 * The MessageDialog class specifies two actions: ‘accept’, the primary
7542 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7543 * passing along the selected action.
7544 *
7545 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7546 *
7547 * @example
7548 * // Example: Creating and opening a message dialog window.
7549 * var messageDialog = new OO.ui.MessageDialog();
7550 *
7551 * // Create and append a window manager.
7552 * var windowManager = new OO.ui.WindowManager();
7553 * $( 'body' ).append( windowManager.$element );
7554 * windowManager.addWindows( [ messageDialog ] );
7555 * // Open the window.
7556 * windowManager.openWindow( messageDialog, {
7557 * title: 'Basic message dialog',
7558 * message: 'This is the message'
7559 * } );
7560 *
7561 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7562 *
7563 * @class
7564 * @extends OO.ui.Dialog
7565 *
7566 * @constructor
7567 * @param {Object} [config] Configuration options
7568 */
7569 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7570 // Parent constructor
7571 OO.ui.MessageDialog.super.call( this, config );
7572
7573 // Properties
7574 this.verticalActionLayout = null;
7575
7576 // Initialization
7577 this.$element.addClass( 'oo-ui-messageDialog' );
7578 };
7579
7580 /* Inheritance */
7581
7582 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7583
7584 /* Static Properties */
7585
7586 OO.ui.MessageDialog.static.name = 'message';
7587
7588 OO.ui.MessageDialog.static.size = 'small';
7589
7590 OO.ui.MessageDialog.static.verbose = false;
7591
7592 /**
7593 * Dialog title.
7594 *
7595 * The title of a confirmation dialog describes what a progressive action will do. The
7596 * title of an alert dialog describes which event occurred.
7597 *
7598 * @static
7599 * @inheritable
7600 * @property {jQuery|string|Function|null}
7601 */
7602 OO.ui.MessageDialog.static.title = null;
7603
7604 /**
7605 * The message displayed in the dialog body.
7606 *
7607 * A confirmation message describes the consequences of a progressive action. An alert
7608 * message describes why an event occurred.
7609 *
7610 * @static
7611 * @inheritable
7612 * @property {jQuery|string|Function|null}
7613 */
7614 OO.ui.MessageDialog.static.message = null;
7615
7616 OO.ui.MessageDialog.static.actions = [
7617 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7618 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7619 ];
7620
7621 /* Methods */
7622
7623 /**
7624 * @inheritdoc
7625 */
7626 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7627 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7628
7629 // Events
7630 this.manager.connect( this, {
7631 resize: 'onResize'
7632 } );
7633
7634 return this;
7635 };
7636
7637 /**
7638 * @inheritdoc
7639 */
7640 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7641 this.fitActions();
7642 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7643 };
7644
7645 /**
7646 * Handle window resized events.
7647 *
7648 * @private
7649 */
7650 OO.ui.MessageDialog.prototype.onResize = function () {
7651 var dialog = this;
7652 dialog.fitActions();
7653 // Wait for CSS transition to finish and do it again :(
7654 setTimeout( function () {
7655 dialog.fitActions();
7656 }, 300 );
7657 };
7658
7659 /**
7660 * Toggle action layout between vertical and horizontal.
7661 *
7662 *
7663 * @private
7664 * @param {boolean} [value] Layout actions vertically, omit to toggle
7665 * @chainable
7666 */
7667 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7668 value = value === undefined ? !this.verticalActionLayout : !!value;
7669
7670 if ( value !== this.verticalActionLayout ) {
7671 this.verticalActionLayout = value;
7672 this.$actions
7673 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7674 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7675 }
7676
7677 return this;
7678 };
7679
7680 /**
7681 * @inheritdoc
7682 */
7683 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7684 if ( action ) {
7685 return new OO.ui.Process( function () {
7686 this.close( { action: action } );
7687 }, this );
7688 }
7689 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7690 };
7691
7692 /**
7693 * @inheritdoc
7694 *
7695 * @param {Object} [data] Dialog opening data
7696 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7697 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7698 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7699 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7700 * action item
7701 */
7702 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7703 data = data || {};
7704
7705 // Parent method
7706 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7707 .next( function () {
7708 this.title.setLabel(
7709 data.title !== undefined ? data.title : this.constructor.static.title
7710 );
7711 this.message.setLabel(
7712 data.message !== undefined ? data.message : this.constructor.static.message
7713 );
7714 this.message.$element.toggleClass(
7715 'oo-ui-messageDialog-message-verbose',
7716 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7717 );
7718 }, this );
7719 };
7720
7721 /**
7722 * @inheritdoc
7723 */
7724 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7725 var bodyHeight, oldOverflow,
7726 $scrollable = this.container.$element;
7727
7728 oldOverflow = $scrollable[ 0 ].style.overflow;
7729 $scrollable[ 0 ].style.overflow = 'hidden';
7730
7731 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7732
7733 bodyHeight = this.text.$element.outerHeight( true );
7734 $scrollable[ 0 ].style.overflow = oldOverflow;
7735
7736 return bodyHeight;
7737 };
7738
7739 /**
7740 * @inheritdoc
7741 */
7742 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7743 var $scrollable = this.container.$element;
7744 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7745
7746 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7747 // Need to do it after transition completes (250ms), add 50ms just in case.
7748 setTimeout( function () {
7749 var oldOverflow = $scrollable[ 0 ].style.overflow;
7750 $scrollable[ 0 ].style.overflow = 'hidden';
7751
7752 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7753
7754 $scrollable[ 0 ].style.overflow = oldOverflow;
7755 }, 300 );
7756
7757 return this;
7758 };
7759
7760 /**
7761 * @inheritdoc
7762 */
7763 OO.ui.MessageDialog.prototype.initialize = function () {
7764 // Parent method
7765 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7766
7767 // Properties
7768 this.$actions = $( '<div>' );
7769 this.container = new OO.ui.PanelLayout( {
7770 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7771 } );
7772 this.text = new OO.ui.PanelLayout( {
7773 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7774 } );
7775 this.message = new OO.ui.LabelWidget( {
7776 classes: [ 'oo-ui-messageDialog-message' ]
7777 } );
7778
7779 // Initialization
7780 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7781 this.$content.addClass( 'oo-ui-messageDialog-content' );
7782 this.container.$element.append( this.text.$element );
7783 this.text.$element.append( this.title.$element, this.message.$element );
7784 this.$body.append( this.container.$element );
7785 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7786 this.$foot.append( this.$actions );
7787 };
7788
7789 /**
7790 * @inheritdoc
7791 */
7792 OO.ui.MessageDialog.prototype.attachActions = function () {
7793 var i, len, other, special, others;
7794
7795 // Parent method
7796 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7797
7798 special = this.actions.getSpecial();
7799 others = this.actions.getOthers();
7800 if ( special.safe ) {
7801 this.$actions.append( special.safe.$element );
7802 special.safe.toggleFramed( false );
7803 }
7804 if ( others.length ) {
7805 for ( i = 0, len = others.length; i < len; i++ ) {
7806 other = others[ i ];
7807 this.$actions.append( other.$element );
7808 other.toggleFramed( false );
7809 }
7810 }
7811 if ( special.primary ) {
7812 this.$actions.append( special.primary.$element );
7813 special.primary.toggleFramed( false );
7814 }
7815
7816 if ( !this.isOpening() ) {
7817 // If the dialog is currently opening, this will be called automatically soon.
7818 // This also calls #fitActions.
7819 this.updateSize();
7820 }
7821 };
7822
7823 /**
7824 * Fit action actions into columns or rows.
7825 *
7826 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7827 *
7828 * @private
7829 */
7830 OO.ui.MessageDialog.prototype.fitActions = function () {
7831 var i, len, action,
7832 previous = this.verticalActionLayout,
7833 actions = this.actions.get();
7834
7835 // Detect clipping
7836 this.toggleVerticalActionLayout( false );
7837 for ( i = 0, len = actions.length; i < len; i++ ) {
7838 action = actions[ i ];
7839 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7840 this.toggleVerticalActionLayout( true );
7841 break;
7842 }
7843 }
7844
7845 // Move the body out of the way of the foot
7846 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7847
7848 if ( this.verticalActionLayout !== previous ) {
7849 // We changed the layout, window height might need to be updated.
7850 this.updateSize();
7851 }
7852 };
7853
7854 /**
7855 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7856 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7857 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7858 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7859 * required for each process.
7860 *
7861 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7862 * processes with an animation. The header contains the dialog title as well as
7863 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7864 * a ‘primary’ action on the right (e.g., ‘Done’).
7865 *
7866 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7867 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7868 *
7869 * @example
7870 * // Example: Creating and opening a process dialog window.
7871 * function MyProcessDialog( config ) {
7872 * MyProcessDialog.super.call( this, config );
7873 * }
7874 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7875 *
7876 * MyProcessDialog.static.title = 'Process dialog';
7877 * MyProcessDialog.static.actions = [
7878 * { action: 'save', label: 'Done', flags: 'primary' },
7879 * { label: 'Cancel', flags: 'safe' }
7880 * ];
7881 *
7882 * MyProcessDialog.prototype.initialize = function () {
7883 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7884 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7885 * 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>' );
7886 * this.$body.append( this.content.$element );
7887 * };
7888 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7889 * var dialog = this;
7890 * if ( action ) {
7891 * return new OO.ui.Process( function () {
7892 * dialog.close( { action: action } );
7893 * } );
7894 * }
7895 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7896 * };
7897 *
7898 * var windowManager = new OO.ui.WindowManager();
7899 * $( 'body' ).append( windowManager.$element );
7900 *
7901 * var dialog = new MyProcessDialog();
7902 * windowManager.addWindows( [ dialog ] );
7903 * windowManager.openWindow( dialog );
7904 *
7905 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7906 *
7907 * @abstract
7908 * @class
7909 * @extends OO.ui.Dialog
7910 *
7911 * @constructor
7912 * @param {Object} [config] Configuration options
7913 */
7914 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7915 // Parent constructor
7916 OO.ui.ProcessDialog.super.call( this, config );
7917
7918 // Initialization
7919 this.$element.addClass( 'oo-ui-processDialog' );
7920 };
7921
7922 /* Setup */
7923
7924 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7925
7926 /* Methods */
7927
7928 /**
7929 * Handle dismiss button click events.
7930 *
7931 * Hides errors.
7932 *
7933 * @private
7934 */
7935 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7936 this.hideErrors();
7937 };
7938
7939 /**
7940 * Handle retry button click events.
7941 *
7942 * Hides errors and then tries again.
7943 *
7944 * @private
7945 */
7946 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7947 this.hideErrors();
7948 this.executeAction( this.currentAction );
7949 };
7950
7951 /**
7952 * @inheritdoc
7953 */
7954 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7955 if ( this.actions.isSpecial( action ) ) {
7956 this.fitLabel();
7957 }
7958 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7959 };
7960
7961 /**
7962 * @inheritdoc
7963 */
7964 OO.ui.ProcessDialog.prototype.initialize = function () {
7965 // Parent method
7966 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7967
7968 // Properties
7969 this.$navigation = $( '<div>' );
7970 this.$location = $( '<div>' );
7971 this.$safeActions = $( '<div>' );
7972 this.$primaryActions = $( '<div>' );
7973 this.$otherActions = $( '<div>' );
7974 this.dismissButton = new OO.ui.ButtonWidget( {
7975 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7976 } );
7977 this.retryButton = new OO.ui.ButtonWidget();
7978 this.$errors = $( '<div>' );
7979 this.$errorsTitle = $( '<div>' );
7980
7981 // Events
7982 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7983 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7984
7985 // Initialization
7986 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7987 this.$location
7988 .append( this.title.$element )
7989 .addClass( 'oo-ui-processDialog-location' );
7990 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7991 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7992 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7993 this.$errorsTitle
7994 .addClass( 'oo-ui-processDialog-errors-title' )
7995 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7996 this.$errors
7997 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7998 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7999 this.$content
8000 .addClass( 'oo-ui-processDialog-content' )
8001 .append( this.$errors );
8002 this.$navigation
8003 .addClass( 'oo-ui-processDialog-navigation' )
8004 .append( this.$safeActions, this.$location, this.$primaryActions );
8005 this.$head.append( this.$navigation );
8006 this.$foot.append( this.$otherActions );
8007 };
8008
8009 /**
8010 * @inheritdoc
8011 */
8012 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
8013 var i, len, widgets = [];
8014 for ( i = 0, len = actions.length; i < len; i++ ) {
8015 widgets.push(
8016 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
8017 );
8018 }
8019 return widgets;
8020 };
8021
8022 /**
8023 * @inheritdoc
8024 */
8025 OO.ui.ProcessDialog.prototype.attachActions = function () {
8026 var i, len, other, special, others;
8027
8028 // Parent method
8029 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
8030
8031 special = this.actions.getSpecial();
8032 others = this.actions.getOthers();
8033 if ( special.primary ) {
8034 this.$primaryActions.append( special.primary.$element );
8035 }
8036 for ( i = 0, len = others.length; i < len; i++ ) {
8037 other = others[ i ];
8038 this.$otherActions.append( other.$element );
8039 }
8040 if ( special.safe ) {
8041 this.$safeActions.append( special.safe.$element );
8042 }
8043
8044 this.fitLabel();
8045 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
8046 };
8047
8048 /**
8049 * @inheritdoc
8050 */
8051 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
8052 var process = this;
8053 return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
8054 .fail( function ( errors ) {
8055 process.showErrors( errors || [] );
8056 } );
8057 };
8058
8059 /**
8060 * Fit label between actions.
8061 *
8062 * @private
8063 * @chainable
8064 */
8065 OO.ui.ProcessDialog.prototype.fitLabel = function () {
8066 var width = Math.max(
8067 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
8068 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
8069 );
8070 this.$location.css( { paddingLeft: width, paddingRight: width } );
8071
8072 return this;
8073 };
8074
8075 /**
8076 * Handle errors that occurred during accept or reject processes.
8077 *
8078 * @private
8079 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8080 */
8081 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
8082 var i, len, $item, actions,
8083 items = [],
8084 abilities = {},
8085 recoverable = true,
8086 warning = false;
8087
8088 if ( errors instanceof OO.ui.Error ) {
8089 errors = [ errors ];
8090 }
8091
8092 for ( i = 0, len = errors.length; i < len; i++ ) {
8093 if ( !errors[ i ].isRecoverable() ) {
8094 recoverable = false;
8095 }
8096 if ( errors[ i ].isWarning() ) {
8097 warning = true;
8098 }
8099 $item = $( '<div>' )
8100 .addClass( 'oo-ui-processDialog-error' )
8101 .append( errors[ i ].getMessage() );
8102 items.push( $item[ 0 ] );
8103 }
8104 this.$errorItems = $( items );
8105 if ( recoverable ) {
8106 abilities[this.currentAction] = true;
8107 // Copy the flags from the first matching action
8108 actions = this.actions.get( { actions: this.currentAction } );
8109 if ( actions.length ) {
8110 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
8111 }
8112 } else {
8113 abilities[this.currentAction] = false;
8114 this.actions.setAbilities( abilities );
8115 }
8116 if ( warning ) {
8117 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
8118 } else {
8119 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
8120 }
8121 this.retryButton.toggle( recoverable );
8122 this.$errorsTitle.after( this.$errorItems );
8123 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8124 };
8125
8126 /**
8127 * Hide errors.
8128 *
8129 * @private
8130 */
8131 OO.ui.ProcessDialog.prototype.hideErrors = function () {
8132 this.$errors.addClass( 'oo-ui-element-hidden' );
8133 if ( this.$errorItems ) {
8134 this.$errorItems.remove();
8135 this.$errorItems = null;
8136 }
8137 };
8138
8139 /**
8140 * @inheritdoc
8141 */
8142 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
8143 // Parent method
8144 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
8145 .first( function () {
8146 // Make sure to hide errors
8147 this.hideErrors();
8148 }, this );
8149 };
8150
8151 /**
8152 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8153 * which is a widget that is specified by reference before any optional configuration settings.
8154 *
8155 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8156 *
8157 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8158 * A left-alignment is used for forms with many fields.
8159 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8160 * A right-alignment is used for long but familiar forms which users tab through,
8161 * verifying the current field with a quick glance at the label.
8162 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8163 * that users fill out from top to bottom.
8164 * - **inline**: The label is placed after the field-widget and aligned to the left.
8165 * An inline-alignment is best used with checkboxes or radio buttons.
8166 *
8167 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8168 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8169 *
8170 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8171 * @class
8172 * @extends OO.ui.Layout
8173 * @mixins OO.ui.LabelElement
8174 *
8175 * @constructor
8176 * @param {OO.ui.Widget} fieldWidget Field widget
8177 * @param {Object} [config] Configuration options
8178 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8179 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8180 * in the upper-right corner of the rendered field.
8181 */
8182 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8183 // Allow passing positional parameters inside the config object
8184 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8185 config = fieldWidget;
8186 fieldWidget = config.fieldWidget;
8187 }
8188
8189 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
8190
8191 // Configuration initialization
8192 config = $.extend( { align: 'left' }, config );
8193
8194 // Parent constructor
8195 OO.ui.FieldLayout.super.call( this, config );
8196
8197 // Mixin constructors
8198 OO.ui.LabelElement.call( this, config );
8199
8200 // Properties
8201 this.fieldWidget = fieldWidget;
8202 this.$field = $( '<div>' );
8203 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8204 this.align = null;
8205 if ( config.help ) {
8206 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8207 classes: [ 'oo-ui-fieldLayout-help' ],
8208 framed: false,
8209 icon: 'info'
8210 } );
8211
8212 this.popupButtonWidget.getPopup().$body.append(
8213 $( '<div>' )
8214 .text( config.help )
8215 .addClass( 'oo-ui-fieldLayout-help-content' )
8216 );
8217 this.$help = this.popupButtonWidget.$element;
8218 } else {
8219 this.$help = $( [] );
8220 }
8221
8222 // Events
8223 if ( hasInputWidget ) {
8224 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8225 }
8226 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8227
8228 // Initialization
8229 this.$element
8230 .addClass( 'oo-ui-fieldLayout' )
8231 .append( this.$help, this.$body );
8232 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8233 this.$field
8234 .addClass( 'oo-ui-fieldLayout-field' )
8235 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8236 .append( this.fieldWidget.$element );
8237
8238 this.setAlignment( config.align );
8239 };
8240
8241 /* Setup */
8242
8243 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8244 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
8245
8246 /* Methods */
8247
8248 /**
8249 * Handle field disable events.
8250 *
8251 * @private
8252 * @param {boolean} value Field is disabled
8253 */
8254 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8255 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8256 };
8257
8258 /**
8259 * Handle label mouse click events.
8260 *
8261 * @private
8262 * @param {jQuery.Event} e Mouse click event
8263 */
8264 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8265 this.fieldWidget.simulateLabelClick();
8266 return false;
8267 };
8268
8269 /**
8270 * Get the widget contained by the field.
8271 *
8272 * @return {OO.ui.Widget} Field widget
8273 */
8274 OO.ui.FieldLayout.prototype.getField = function () {
8275 return this.fieldWidget;
8276 };
8277
8278 /**
8279 * Set the field alignment mode.
8280 *
8281 * @private
8282 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8283 * @chainable
8284 */
8285 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8286 if ( value !== this.align ) {
8287 // Default to 'left'
8288 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8289 value = 'left';
8290 }
8291 // Reorder elements
8292 if ( value === 'inline' ) {
8293 this.$body.append( this.$field, this.$label );
8294 } else {
8295 this.$body.append( this.$label, this.$field );
8296 }
8297 // Set classes. The following classes can be used here:
8298 // * oo-ui-fieldLayout-align-left
8299 // * oo-ui-fieldLayout-align-right
8300 // * oo-ui-fieldLayout-align-top
8301 // * oo-ui-fieldLayout-align-inline
8302 if ( this.align ) {
8303 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8304 }
8305 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8306 this.align = value;
8307 }
8308
8309 return this;
8310 };
8311
8312 /**
8313 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8314 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8315 * is required and is specified before any optional configuration settings.
8316 *
8317 * Labels can be aligned in one of four ways:
8318 *
8319 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8320 * A left-alignment is used for forms with many fields.
8321 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8322 * A right-alignment is used for long but familiar forms which users tab through,
8323 * verifying the current field with a quick glance at the label.
8324 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8325 * that users fill out from top to bottom.
8326 * - **inline**: The label is placed after the field-widget and aligned to the left.
8327 * An inline-alignment is best used with checkboxes or radio buttons.
8328 *
8329 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8330 * text is specified.
8331 *
8332 * @example
8333 * // Example of an ActionFieldLayout
8334 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8335 * new OO.ui.TextInputWidget( {
8336 * placeholder: 'Field widget'
8337 * } ),
8338 * new OO.ui.ButtonWidget( {
8339 * label: 'Button'
8340 * } ),
8341 * {
8342 * label: 'An ActionFieldLayout. This label is aligned top',
8343 * align: 'top',
8344 * help: 'This is help text'
8345 * }
8346 * );
8347 *
8348 * $( 'body' ).append( actionFieldLayout.$element );
8349 *
8350 *
8351 * @class
8352 * @extends OO.ui.FieldLayout
8353 *
8354 * @constructor
8355 * @param {OO.ui.Widget} fieldWidget Field widget
8356 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8357 * @param {Object} [config] Configuration options
8358 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8359 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8360 * upper-right corner of the rendered field.
8361 */
8362 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8363 // Allow passing positional parameters inside the config object
8364 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8365 config = fieldWidget;
8366 fieldWidget = config.fieldWidget;
8367 buttonWidget = config.buttonWidget;
8368 }
8369
8370 // Configuration initialization
8371 config = $.extend( { align: 'left' }, config );
8372
8373 // Parent constructor
8374 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
8375
8376 // Properties
8377 this.fieldWidget = fieldWidget;
8378 this.buttonWidget = buttonWidget;
8379 this.$button = $( '<div>' )
8380 .addClass( 'oo-ui-actionFieldLayout-button' )
8381 .append( this.buttonWidget.$element );
8382 this.$input = $( '<div>' )
8383 .addClass( 'oo-ui-actionFieldLayout-input' )
8384 .append( this.fieldWidget.$element );
8385 this.$field
8386 .addClass( 'oo-ui-actionFieldLayout' )
8387 .append( this.$input, this.$button );
8388 };
8389
8390 /* Setup */
8391
8392 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8393
8394 /**
8395 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8396 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8397 * configured with a label as well. For more information and examples,
8398 * please see the [OOjs UI documentation on MediaWiki][1].
8399 *
8400 * @example
8401 * // Example of a fieldset layout
8402 * var input1 = new OO.ui.TextInputWidget( {
8403 * placeholder: 'A text input field'
8404 * } );
8405 *
8406 * var input2 = new OO.ui.TextInputWidget( {
8407 * placeholder: 'A text input field'
8408 * } );
8409 *
8410 * var fieldset = new OO.ui.FieldsetLayout( {
8411 * label: 'Example of a fieldset layout'
8412 * } );
8413 *
8414 * fieldset.addItems( [
8415 * new OO.ui.FieldLayout( input1, {
8416 * label: 'Field One'
8417 * } ),
8418 * new OO.ui.FieldLayout( input2, {
8419 * label: 'Field Two'
8420 * } )
8421 * ] );
8422 * $( 'body' ).append( fieldset.$element );
8423 *
8424 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8425 *
8426 * @class
8427 * @extends OO.ui.Layout
8428 * @mixins OO.ui.IconElement
8429 * @mixins OO.ui.LabelElement
8430 * @mixins OO.ui.GroupElement
8431 *
8432 * @constructor
8433 * @param {Object} [config] Configuration options
8434 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8435 */
8436 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8437 // Configuration initialization
8438 config = config || {};
8439
8440 // Parent constructor
8441 OO.ui.FieldsetLayout.super.call( this, config );
8442
8443 // Mixin constructors
8444 OO.ui.IconElement.call( this, config );
8445 OO.ui.LabelElement.call( this, config );
8446 OO.ui.GroupElement.call( this, config );
8447
8448 if ( config.help ) {
8449 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8450 classes: [ 'oo-ui-fieldsetLayout-help' ],
8451 framed: false,
8452 icon: 'info'
8453 } );
8454
8455 this.popupButtonWidget.getPopup().$body.append(
8456 $( '<div>' )
8457 .text( config.help )
8458 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8459 );
8460 this.$help = this.popupButtonWidget.$element;
8461 } else {
8462 this.$help = $( [] );
8463 }
8464
8465 // Initialization
8466 this.$element
8467 .addClass( 'oo-ui-fieldsetLayout' )
8468 .prepend( this.$help, this.$icon, this.$label, this.$group );
8469 if ( Array.isArray( config.items ) ) {
8470 this.addItems( config.items );
8471 }
8472 };
8473
8474 /* Setup */
8475
8476 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8477 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
8478 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
8479 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
8480
8481 /**
8482 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8483 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8484 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8485 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8486 *
8487 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8488 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8489 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8490 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8491 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8492 * often have simplified APIs to match the capabilities of HTML forms.
8493 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8494 *
8495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8496 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8497 *
8498 * @example
8499 * // Example of a form layout that wraps a fieldset layout
8500 * var input1 = new OO.ui.TextInputWidget( {
8501 * placeholder: 'Username'
8502 * } );
8503 * var input2 = new OO.ui.TextInputWidget( {
8504 * placeholder: 'Password',
8505 * type: 'password'
8506 * } );
8507 * var submit = new OO.ui.ButtonInputWidget( {
8508 * label: 'Submit'
8509 * } );
8510 *
8511 * var fieldset = new OO.ui.FieldsetLayout( {
8512 * label: 'A form layout'
8513 * } );
8514 * fieldset.addItems( [
8515 * new OO.ui.FieldLayout( input1, {
8516 * label: 'Username',
8517 * align: 'top'
8518 * } ),
8519 * new OO.ui.FieldLayout( input2, {
8520 * label: 'Password',
8521 * align: 'top'
8522 * } ),
8523 * new OO.ui.FieldLayout( submit )
8524 * ] );
8525 * var form = new OO.ui.FormLayout( {
8526 * items: [ fieldset ],
8527 * action: '/api/formhandler',
8528 * method: 'get'
8529 * } )
8530 * $( 'body' ).append( form.$element );
8531 *
8532 * @class
8533 * @extends OO.ui.Layout
8534 * @mixins OO.ui.GroupElement
8535 *
8536 * @constructor
8537 * @param {Object} [config] Configuration options
8538 * @cfg {string} [method] HTML form `method` attribute
8539 * @cfg {string} [action] HTML form `action` attribute
8540 * @cfg {string} [enctype] HTML form `enctype` attribute
8541 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8542 */
8543 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8544 // Configuration initialization
8545 config = config || {};
8546
8547 // Parent constructor
8548 OO.ui.FormLayout.super.call( this, config );
8549
8550 // Mixin constructors
8551 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8552
8553 // Events
8554 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8555
8556 // Initialization
8557 this.$element
8558 .addClass( 'oo-ui-formLayout' )
8559 .attr( {
8560 method: config.method,
8561 action: config.action,
8562 enctype: config.enctype
8563 } );
8564 if ( Array.isArray( config.items ) ) {
8565 this.addItems( config.items );
8566 }
8567 };
8568
8569 /* Setup */
8570
8571 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8572 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8573
8574 /* Events */
8575
8576 /**
8577 * A 'submit' event is emitted when the form is submitted.
8578 *
8579 * @event submit
8580 */
8581
8582 /* Static Properties */
8583
8584 OO.ui.FormLayout.static.tagName = 'form';
8585
8586 /* Methods */
8587
8588 /**
8589 * Handle form submit events.
8590 *
8591 * @private
8592 * @param {jQuery.Event} e Submit event
8593 * @fires submit
8594 */
8595 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8596 if ( this.emit( 'submit' ) ) {
8597 return false;
8598 }
8599 };
8600
8601 /**
8602 * 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)
8603 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8604 *
8605 * @example
8606 * var menuLayout = new OO.ui.MenuLayout( {
8607 * position: 'top'
8608 * } ),
8609 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8610 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8611 * select = new OO.ui.SelectWidget( {
8612 * items: [
8613 * new OO.ui.OptionWidget( {
8614 * data: 'before',
8615 * label: 'Before',
8616 * } ),
8617 * new OO.ui.OptionWidget( {
8618 * data: 'after',
8619 * label: 'After',
8620 * } ),
8621 * new OO.ui.OptionWidget( {
8622 * data: 'top',
8623 * label: 'Top',
8624 * } ),
8625 * new OO.ui.OptionWidget( {
8626 * data: 'bottom',
8627 * label: 'Bottom',
8628 * } )
8629 * ]
8630 * } ).on( 'select', function ( item ) {
8631 * menuLayout.setMenuPosition( item.getData() );
8632 * } );
8633 *
8634 * menuLayout.$menu.append(
8635 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8636 * );
8637 * menuLayout.$content.append(
8638 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8639 * );
8640 * $( 'body' ).append( menuLayout.$element );
8641 *
8642 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8643 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8644 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8645 * may be omitted.
8646 *
8647 * .oo-ui-menuLayout-menu {
8648 * height: 200px;
8649 * width: 200px;
8650 * }
8651 * .oo-ui-menuLayout-content {
8652 * top: 200px;
8653 * left: 200px;
8654 * right: 200px;
8655 * bottom: 200px;
8656 * }
8657 *
8658 * @class
8659 * @extends OO.ui.Layout
8660 *
8661 * @constructor
8662 * @param {Object} [config] Configuration options
8663 * @cfg {boolean} [showMenu=true] Show menu
8664 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8665 */
8666 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8667 // Configuration initialization
8668 config = $.extend( {
8669 showMenu: true,
8670 menuPosition: 'before'
8671 }, config );
8672
8673 // Parent constructor
8674 OO.ui.MenuLayout.super.call( this, config );
8675
8676 /**
8677 * Menu DOM node
8678 *
8679 * @property {jQuery}
8680 */
8681 this.$menu = $( '<div>' );
8682 /**
8683 * Content DOM node
8684 *
8685 * @property {jQuery}
8686 */
8687 this.$content = $( '<div>' );
8688
8689 // Initialization
8690 this.$menu
8691 .addClass( 'oo-ui-menuLayout-menu' );
8692 this.$content.addClass( 'oo-ui-menuLayout-content' );
8693 this.$element
8694 .addClass( 'oo-ui-menuLayout' )
8695 .append( this.$content, this.$menu );
8696 this.setMenuPosition( config.menuPosition );
8697 this.toggleMenu( config.showMenu );
8698 };
8699
8700 /* Setup */
8701
8702 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8703
8704 /* Methods */
8705
8706 /**
8707 * Toggle menu.
8708 *
8709 * @param {boolean} showMenu Show menu, omit to toggle
8710 * @chainable
8711 */
8712 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8713 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8714
8715 if ( this.showMenu !== showMenu ) {
8716 this.showMenu = showMenu;
8717 this.$element
8718 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
8719 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
8720 }
8721
8722 return this;
8723 };
8724
8725 /**
8726 * Check if menu is visible
8727 *
8728 * @return {boolean} Menu is visible
8729 */
8730 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8731 return this.showMenu;
8732 };
8733
8734 /**
8735 * Set menu position.
8736 *
8737 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8738 * @throws {Error} If position value is not supported
8739 * @chainable
8740 */
8741 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8742 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
8743 this.menuPosition = position;
8744 this.$element.addClass( 'oo-ui-menuLayout-' + position );
8745
8746 return this;
8747 };
8748
8749 /**
8750 * Get menu position.
8751 *
8752 * @return {string} Menu position
8753 */
8754 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8755 return this.menuPosition;
8756 };
8757
8758 /**
8759 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8760 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8761 * through the pages and select which one to display. By default, only one page is
8762 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8763 * the booklet layout automatically focuses on the first focusable element, unless the
8764 * default setting is changed. Optionally, booklets can be configured to show
8765 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8766 *
8767 * @example
8768 * // Example of a BookletLayout that contains two PageLayouts.
8769 *
8770 * function PageOneLayout( name, config ) {
8771 * PageOneLayout.super.call( this, name, config );
8772 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8773 * }
8774 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8775 * PageOneLayout.prototype.setupOutlineItem = function () {
8776 * this.outlineItem.setLabel( 'Page One' );
8777 * };
8778 *
8779 * function PageTwoLayout( name, config ) {
8780 * PageTwoLayout.super.call( this, name, config );
8781 * this.$element.append( '<p>Second page</p>' );
8782 * }
8783 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8784 * PageTwoLayout.prototype.setupOutlineItem = function () {
8785 * this.outlineItem.setLabel( 'Page Two' );
8786 * };
8787 *
8788 * var page1 = new PageOneLayout( 'one' ),
8789 * page2 = new PageTwoLayout( 'two' );
8790 *
8791 * var booklet = new OO.ui.BookletLayout( {
8792 * outlined: true
8793 * } );
8794 *
8795 * booklet.addPages ( [ page1, page2 ] );
8796 * $( 'body' ).append( booklet.$element );
8797 *
8798 * @class
8799 * @extends OO.ui.MenuLayout
8800 *
8801 * @constructor
8802 * @param {Object} [config] Configuration options
8803 * @cfg {boolean} [continuous=false] Show all pages, one after another
8804 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8805 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8806 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8807 */
8808 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8809 // Configuration initialization
8810 config = config || {};
8811
8812 // Parent constructor
8813 OO.ui.BookletLayout.super.call( this, config );
8814
8815 // Properties
8816 this.currentPageName = null;
8817 this.pages = {};
8818 this.ignoreFocus = false;
8819 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8820 this.$content.append( this.stackLayout.$element );
8821 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8822 this.outlineVisible = false;
8823 this.outlined = !!config.outlined;
8824 if ( this.outlined ) {
8825 this.editable = !!config.editable;
8826 this.outlineControlsWidget = null;
8827 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8828 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8829 this.$menu.append( this.outlinePanel.$element );
8830 this.outlineVisible = true;
8831 if ( this.editable ) {
8832 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8833 this.outlineSelectWidget
8834 );
8835 }
8836 }
8837 this.toggleMenu( this.outlined );
8838
8839 // Events
8840 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8841 if ( this.outlined ) {
8842 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8843 }
8844 if ( this.autoFocus ) {
8845 // Event 'focus' does not bubble, but 'focusin' does
8846 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8847 }
8848
8849 // Initialization
8850 this.$element.addClass( 'oo-ui-bookletLayout' );
8851 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8852 if ( this.outlined ) {
8853 this.outlinePanel.$element
8854 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8855 .append( this.outlineSelectWidget.$element );
8856 if ( this.editable ) {
8857 this.outlinePanel.$element
8858 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8859 .append( this.outlineControlsWidget.$element );
8860 }
8861 }
8862 };
8863
8864 /* Setup */
8865
8866 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8867
8868 /* Events */
8869
8870 /**
8871 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8872 * @event set
8873 * @param {OO.ui.PageLayout} page Current page
8874 */
8875
8876 /**
8877 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8878 *
8879 * @event add
8880 * @param {OO.ui.PageLayout[]} page Added pages
8881 * @param {number} index Index pages were added at
8882 */
8883
8884 /**
8885 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8886 * {@link #removePages removed} from the booklet.
8887 *
8888 * @event remove
8889 * @param {OO.ui.PageLayout[]} pages Removed pages
8890 */
8891
8892 /* Methods */
8893
8894 /**
8895 * Handle stack layout focus.
8896 *
8897 * @private
8898 * @param {jQuery.Event} e Focusin event
8899 */
8900 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8901 var name, $target;
8902
8903 // Find the page that an element was focused within
8904 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8905 for ( name in this.pages ) {
8906 // Check for page match, exclude current page to find only page changes
8907 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8908 this.setPage( name );
8909 break;
8910 }
8911 }
8912 };
8913
8914 /**
8915 * Handle stack layout set events.
8916 *
8917 * @private
8918 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8919 */
8920 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8921 var layout = this;
8922 if ( page ) {
8923 page.scrollElementIntoView( { complete: function () {
8924 if ( layout.autoFocus ) {
8925 layout.focus();
8926 }
8927 } } );
8928 }
8929 };
8930
8931 /**
8932 * Focus the first input in the current page.
8933 *
8934 * If no page is selected, the first selectable page will be selected.
8935 * If the focus is already in an element on the current page, nothing will happen.
8936 * @param {number} [itemIndex] A specific item to focus on
8937 */
8938 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
8939 var $input, page,
8940 items = this.stackLayout.getItems();
8941
8942 if ( itemIndex !== undefined && items[ itemIndex ] ) {
8943 page = items[ itemIndex ];
8944 } else {
8945 page = this.stackLayout.getCurrentItem();
8946 }
8947
8948 if ( !page && this.outlined ) {
8949 this.selectFirstSelectablePage();
8950 page = this.stackLayout.getCurrentItem();
8951 }
8952 if ( !page ) {
8953 return;
8954 }
8955 // Only change the focus if is not already in the current page
8956 if ( !page.$element.find( ':focus' ).length ) {
8957 $input = page.$element.find( ':input:first' );
8958 if ( $input.length ) {
8959 $input[ 0 ].focus();
8960 }
8961 }
8962 };
8963
8964 /**
8965 * Find the first focusable input in the booklet layout and focus
8966 * on it.
8967 */
8968 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
8969 var i, len,
8970 found = false,
8971 items = this.stackLayout.getItems(),
8972 checkAndFocus = function () {
8973 if ( OO.ui.isFocusableElement( $( this ) ) ) {
8974 $( this ).focus();
8975 found = true;
8976 return false;
8977 }
8978 };
8979
8980 for ( i = 0, len = items.length; i < len; i++ ) {
8981 if ( found ) {
8982 break;
8983 }
8984 // Find all potentially focusable elements in the item
8985 // and check if they are focusable
8986 items[i].$element
8987 .find( 'input, select, textarea, button, object' )
8988 /* jshint loopfunc:true */
8989 .each( checkAndFocus );
8990 }
8991 };
8992
8993 /**
8994 * Handle outline widget select events.
8995 *
8996 * @private
8997 * @param {OO.ui.OptionWidget|null} item Selected item
8998 */
8999 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
9000 if ( item ) {
9001 this.setPage( item.getData() );
9002 }
9003 };
9004
9005 /**
9006 * Check if booklet has an outline.
9007 *
9008 * @return {boolean} Booklet has an outline
9009 */
9010 OO.ui.BookletLayout.prototype.isOutlined = function () {
9011 return this.outlined;
9012 };
9013
9014 /**
9015 * Check if booklet has editing controls.
9016 *
9017 * @return {boolean} Booklet is editable
9018 */
9019 OO.ui.BookletLayout.prototype.isEditable = function () {
9020 return this.editable;
9021 };
9022
9023 /**
9024 * Check if booklet has a visible outline.
9025 *
9026 * @return {boolean} Outline is visible
9027 */
9028 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
9029 return this.outlined && this.outlineVisible;
9030 };
9031
9032 /**
9033 * Hide or show the outline.
9034 *
9035 * @param {boolean} [show] Show outline, omit to invert current state
9036 * @chainable
9037 */
9038 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
9039 if ( this.outlined ) {
9040 show = show === undefined ? !this.outlineVisible : !!show;
9041 this.outlineVisible = show;
9042 this.toggleMenu( show );
9043 }
9044
9045 return this;
9046 };
9047
9048 /**
9049 * Get the page closest to the specified page.
9050 *
9051 * @param {OO.ui.PageLayout} page Page to use as a reference point
9052 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9053 */
9054 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
9055 var next, prev, level,
9056 pages = this.stackLayout.getItems(),
9057 index = $.inArray( page, pages );
9058
9059 if ( index !== -1 ) {
9060 next = pages[ index + 1 ];
9061 prev = pages[ index - 1 ];
9062 // Prefer adjacent pages at the same level
9063 if ( this.outlined ) {
9064 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
9065 if (
9066 prev &&
9067 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
9068 ) {
9069 return prev;
9070 }
9071 if (
9072 next &&
9073 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
9074 ) {
9075 return next;
9076 }
9077 }
9078 }
9079 return prev || next || null;
9080 };
9081
9082 /**
9083 * Get the outline widget.
9084 *
9085 * If the booklet is not outlined, the method will return `null`.
9086 *
9087 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9088 */
9089 OO.ui.BookletLayout.prototype.getOutline = function () {
9090 return this.outlineSelectWidget;
9091 };
9092
9093 /**
9094 * Get the outline controls widget.
9095 *
9096 * If the outline is not editable, the method will return `null`.
9097 *
9098 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9099 */
9100 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
9101 return this.outlineControlsWidget;
9102 };
9103
9104 /**
9105 * Get a page by its symbolic name.
9106 *
9107 * @param {string} name Symbolic name of page
9108 * @return {OO.ui.PageLayout|undefined} Page, if found
9109 */
9110 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
9111 return this.pages[ name ];
9112 };
9113
9114 /**
9115 * Get the current page.
9116 *
9117 * @return {OO.ui.PageLayout|undefined} Current page, if found
9118 */
9119 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
9120 var name = this.getCurrentPageName();
9121 return name ? this.getPage( name ) : undefined;
9122 };
9123
9124 /**
9125 * Get the symbolic name of the current page.
9126 *
9127 * @return {string|null} Symbolic name of the current page
9128 */
9129 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
9130 return this.currentPageName;
9131 };
9132
9133 /**
9134 * Add pages to the booklet layout
9135 *
9136 * When pages are added with the same names as existing pages, the existing pages will be
9137 * automatically removed before the new pages are added.
9138 *
9139 * @param {OO.ui.PageLayout[]} pages Pages to add
9140 * @param {number} index Index of the insertion point
9141 * @fires add
9142 * @chainable
9143 */
9144 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
9145 var i, len, name, page, item, currentIndex,
9146 stackLayoutPages = this.stackLayout.getItems(),
9147 remove = [],
9148 items = [];
9149
9150 // Remove pages with same names
9151 for ( i = 0, len = pages.length; i < len; i++ ) {
9152 page = pages[ i ];
9153 name = page.getName();
9154
9155 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
9156 // Correct the insertion index
9157 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
9158 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9159 index--;
9160 }
9161 remove.push( this.pages[ name ] );
9162 }
9163 }
9164 if ( remove.length ) {
9165 this.removePages( remove );
9166 }
9167
9168 // Add new pages
9169 for ( i = 0, len = pages.length; i < len; i++ ) {
9170 page = pages[ i ];
9171 name = page.getName();
9172 this.pages[ page.getName() ] = page;
9173 if ( this.outlined ) {
9174 item = new OO.ui.OutlineOptionWidget( { data: name } );
9175 page.setOutlineItem( item );
9176 items.push( item );
9177 }
9178 }
9179
9180 if ( this.outlined && items.length ) {
9181 this.outlineSelectWidget.addItems( items, index );
9182 this.selectFirstSelectablePage();
9183 }
9184 this.stackLayout.addItems( pages, index );
9185 this.emit( 'add', pages, index );
9186
9187 return this;
9188 };
9189
9190 /**
9191 * Remove the specified pages from the booklet layout.
9192 *
9193 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9194 *
9195 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9196 * @fires remove
9197 * @chainable
9198 */
9199 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9200 var i, len, name, page,
9201 items = [];
9202
9203 for ( i = 0, len = pages.length; i < len; i++ ) {
9204 page = pages[ i ];
9205 name = page.getName();
9206 delete this.pages[ name ];
9207 if ( this.outlined ) {
9208 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9209 page.setOutlineItem( null );
9210 }
9211 }
9212 if ( this.outlined && items.length ) {
9213 this.outlineSelectWidget.removeItems( items );
9214 this.selectFirstSelectablePage();
9215 }
9216 this.stackLayout.removeItems( pages );
9217 this.emit( 'remove', pages );
9218
9219 return this;
9220 };
9221
9222 /**
9223 * Clear all pages from the booklet layout.
9224 *
9225 * To remove only a subset of pages from the booklet, use the #removePages method.
9226 *
9227 * @fires remove
9228 * @chainable
9229 */
9230 OO.ui.BookletLayout.prototype.clearPages = function () {
9231 var i, len,
9232 pages = this.stackLayout.getItems();
9233
9234 this.pages = {};
9235 this.currentPageName = null;
9236 if ( this.outlined ) {
9237 this.outlineSelectWidget.clearItems();
9238 for ( i = 0, len = pages.length; i < len; i++ ) {
9239 pages[ i ].setOutlineItem( null );
9240 }
9241 }
9242 this.stackLayout.clearItems();
9243
9244 this.emit( 'remove', pages );
9245
9246 return this;
9247 };
9248
9249 /**
9250 * Set the current page by symbolic name.
9251 *
9252 * @fires set
9253 * @param {string} name Symbolic name of page
9254 */
9255 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9256 var selectedItem,
9257 $focused,
9258 page = this.pages[ name ];
9259
9260 if ( name !== this.currentPageName ) {
9261 if ( this.outlined ) {
9262 selectedItem = this.outlineSelectWidget.getSelectedItem();
9263 if ( selectedItem && selectedItem.getData() !== name ) {
9264 this.outlineSelectWidget.selectItemByData( name );
9265 }
9266 }
9267 if ( page ) {
9268 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9269 this.pages[ this.currentPageName ].setActive( false );
9270 // Blur anything focused if the next page doesn't have anything focusable - this
9271 // is not needed if the next page has something focusable because once it is focused
9272 // this blur happens automatically
9273 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9274 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9275 if ( $focused.length ) {
9276 $focused[ 0 ].blur();
9277 }
9278 }
9279 }
9280 this.currentPageName = name;
9281 this.stackLayout.setItem( page );
9282 page.setActive( true );
9283 this.emit( 'set', page );
9284 }
9285 }
9286 };
9287
9288 /**
9289 * Select the first selectable page.
9290 *
9291 * @chainable
9292 */
9293 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9294 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9295 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9296 }
9297
9298 return this;
9299 };
9300
9301 /**
9302 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9303 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9304 * select which one to display. By default, only one card is displayed at a time. When a user
9305 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9306 * unless the default setting is changed.
9307 *
9308 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9309 *
9310 * @example
9311 * // Example of a IndexLayout that contains two CardLayouts.
9312 *
9313 * function CardOneLayout( name, config ) {
9314 * CardOneLayout.super.call( this, name, config );
9315 * this.$element.append( '<p>First card</p>' );
9316 * }
9317 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9318 * CardOneLayout.prototype.setupTabItem = function () {
9319 * this.tabItem.setLabel( 'Card One' );
9320 * };
9321 *
9322 * function CardTwoLayout( name, config ) {
9323 * CardTwoLayout.super.call( this, name, config );
9324 * this.$element.append( '<p>Second card</p>' );
9325 * }
9326 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9327 * CardTwoLayout.prototype.setupTabItem = function () {
9328 * this.tabItem.setLabel( 'Card Two' );
9329 * };
9330 *
9331 * var card1 = new CardOneLayout( 'one' ),
9332 * card2 = new CardTwoLayout( 'two' );
9333 *
9334 * var index = new OO.ui.IndexLayout();
9335 *
9336 * index.addCards ( [ card1, card2 ] );
9337 * $( 'body' ).append( index.$element );
9338 *
9339 * @class
9340 * @extends OO.ui.MenuLayout
9341 *
9342 * @constructor
9343 * @param {Object} [config] Configuration options
9344 * @cfg {boolean} [continuous=false] Show all cards, one after another
9345 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
9346 */
9347 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
9348 // Configuration initialization
9349 config = $.extend( {}, config, { menuPosition: 'top' } );
9350
9351 // Parent constructor
9352 OO.ui.IndexLayout.super.call( this, config );
9353
9354 // Properties
9355 this.currentCardName = null;
9356 this.cards = {};
9357 this.ignoreFocus = false;
9358 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
9359 this.$content.append( this.stackLayout.$element );
9360 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
9361
9362 this.tabSelectWidget = new OO.ui.TabSelectWidget();
9363 this.tabPanel = new OO.ui.PanelLayout();
9364 this.$menu.append( this.tabPanel.$element );
9365
9366 this.toggleMenu( true );
9367
9368 // Events
9369 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
9370 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
9371 if ( this.autoFocus ) {
9372 // Event 'focus' does not bubble, but 'focusin' does
9373 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
9374 }
9375
9376 // Initialization
9377 this.$element.addClass( 'oo-ui-indexLayout' );
9378 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
9379 this.tabPanel.$element
9380 .addClass( 'oo-ui-indexLayout-tabPanel' )
9381 .append( this.tabSelectWidget.$element );
9382 };
9383
9384 /* Setup */
9385
9386 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
9387
9388 /* Events */
9389
9390 /**
9391 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
9392 * @event set
9393 * @param {OO.ui.CardLayout} card Current card
9394 */
9395
9396 /**
9397 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
9398 *
9399 * @event add
9400 * @param {OO.ui.CardLayout[]} card Added cards
9401 * @param {number} index Index cards were added at
9402 */
9403
9404 /**
9405 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
9406 * {@link #removeCards removed} from the index.
9407 *
9408 * @event remove
9409 * @param {OO.ui.CardLayout[]} cards Removed cards
9410 */
9411
9412 /* Methods */
9413
9414 /**
9415 * Handle stack layout focus.
9416 *
9417 * @private
9418 * @param {jQuery.Event} e Focusin event
9419 */
9420 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
9421 var name, $target;
9422
9423 // Find the card that an element was focused within
9424 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
9425 for ( name in this.cards ) {
9426 // Check for card match, exclude current card to find only card changes
9427 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
9428 this.setCard( name );
9429 break;
9430 }
9431 }
9432 };
9433
9434 /**
9435 * Handle stack layout set events.
9436 *
9437 * @private
9438 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
9439 */
9440 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
9441 var layout = this;
9442 if ( card ) {
9443 card.scrollElementIntoView( { complete: function () {
9444 if ( layout.autoFocus ) {
9445 layout.focus();
9446 }
9447 } } );
9448 }
9449 };
9450
9451 /**
9452 * Focus the first input in the current card.
9453 *
9454 * If no card is selected, the first selectable card will be selected.
9455 * If the focus is already in an element on the current card, nothing will happen.
9456 * @param {number} [itemIndex] A specific item to focus on
9457 */
9458 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
9459 var $input, card,
9460 items = this.stackLayout.getItems();
9461
9462 if ( itemIndex !== undefined && items[ itemIndex ] ) {
9463 card = items[ itemIndex ];
9464 } else {
9465 card = this.stackLayout.getCurrentItem();
9466 }
9467
9468 if ( !card ) {
9469 this.selectFirstSelectableCard();
9470 card = this.stackLayout.getCurrentItem();
9471 }
9472 if ( !card ) {
9473 return;
9474 }
9475 // Only change the focus if is not already in the current card
9476 if ( !card.$element.find( ':focus' ).length ) {
9477 $input = card.$element.find( ':input:first' );
9478 if ( $input.length ) {
9479 $input[ 0 ].focus();
9480 }
9481 }
9482 };
9483
9484 /**
9485 * Find the first focusable input in the index layout and focus
9486 * on it.
9487 */
9488 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
9489 var i, len,
9490 found = false,
9491 items = this.stackLayout.getItems(),
9492 checkAndFocus = function () {
9493 if ( OO.ui.isFocusableElement( $( this ) ) ) {
9494 $( this ).focus();
9495 found = true;
9496 return false;
9497 }
9498 };
9499
9500 for ( i = 0, len = items.length; i < len; i++ ) {
9501 if ( found ) {
9502 break;
9503 }
9504 // Find all potentially focusable elements in the item
9505 // and check if they are focusable
9506 items[i].$element
9507 .find( 'input, select, textarea, button, object' )
9508 .each( checkAndFocus );
9509 }
9510 };
9511
9512 /**
9513 * Handle tab widget select events.
9514 *
9515 * @private
9516 * @param {OO.ui.OptionWidget|null} item Selected item
9517 */
9518 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
9519 if ( item ) {
9520 this.setCard( item.getData() );
9521 }
9522 };
9523
9524 /**
9525 * Get the card closest to the specified card.
9526 *
9527 * @param {OO.ui.CardLayout} card Card to use as a reference point
9528 * @return {OO.ui.CardLayout|null} Card closest to the specified card
9529 */
9530 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
9531 var next, prev, level,
9532 cards = this.stackLayout.getItems(),
9533 index = $.inArray( card, cards );
9534
9535 if ( index !== -1 ) {
9536 next = cards[ index + 1 ];
9537 prev = cards[ index - 1 ];
9538 // Prefer adjacent cards at the same level
9539 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
9540 if (
9541 prev &&
9542 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
9543 ) {
9544 return prev;
9545 }
9546 if (
9547 next &&
9548 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
9549 ) {
9550 return next;
9551 }
9552 }
9553 return prev || next || null;
9554 };
9555
9556 /**
9557 * Get the tabs widget.
9558 *
9559 * @return {OO.ui.TabSelectWidget} Tabs widget
9560 */
9561 OO.ui.IndexLayout.prototype.getTabs = function () {
9562 return this.tabSelectWidget;
9563 };
9564
9565 /**
9566 * Get a card by its symbolic name.
9567 *
9568 * @param {string} name Symbolic name of card
9569 * @return {OO.ui.CardLayout|undefined} Card, if found
9570 */
9571 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
9572 return this.cards[ name ];
9573 };
9574
9575 /**
9576 * Get the current card.
9577 *
9578 * @return {OO.ui.CardLayout|undefined} Current card, if found
9579 */
9580 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
9581 var name = this.getCurrentCardName();
9582 return name ? this.getCard( name ) : undefined;
9583 };
9584
9585 /**
9586 * Get the symbolic name of the current card.
9587 *
9588 * @return {string|null} Symbolic name of the current card
9589 */
9590 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
9591 return this.currentCardName;
9592 };
9593
9594 /**
9595 * Add cards to the index layout
9596 *
9597 * When cards are added with the same names as existing cards, the existing cards will be
9598 * automatically removed before the new cards are added.
9599 *
9600 * @param {OO.ui.CardLayout[]} cards Cards to add
9601 * @param {number} index Index of the insertion point
9602 * @fires add
9603 * @chainable
9604 */
9605 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
9606 var i, len, name, card, item, currentIndex,
9607 stackLayoutCards = this.stackLayout.getItems(),
9608 remove = [],
9609 items = [];
9610
9611 // Remove cards with same names
9612 for ( i = 0, len = cards.length; i < len; i++ ) {
9613 card = cards[ i ];
9614 name = card.getName();
9615
9616 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
9617 // Correct the insertion index
9618 currentIndex = $.inArray( this.cards[ name ], stackLayoutCards );
9619 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
9620 index--;
9621 }
9622 remove.push( this.cards[ name ] );
9623 }
9624 }
9625 if ( remove.length ) {
9626 this.removeCards( remove );
9627 }
9628
9629 // Add new cards
9630 for ( i = 0, len = cards.length; i < len; i++ ) {
9631 card = cards[ i ];
9632 name = card.getName();
9633 this.cards[ card.getName() ] = card;
9634 item = new OO.ui.TabOptionWidget( { data: name } );
9635 card.setTabItem( item );
9636 items.push( item );
9637 }
9638
9639 if ( items.length ) {
9640 this.tabSelectWidget.addItems( items, index );
9641 this.selectFirstSelectableCard();
9642 }
9643 this.stackLayout.addItems( cards, index );
9644 this.emit( 'add', cards, index );
9645
9646 return this;
9647 };
9648
9649 /**
9650 * Remove the specified cards from the index layout.
9651 *
9652 * To remove all cards from the index, you may wish to use the #clearCards method instead.
9653 *
9654 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
9655 * @fires remove
9656 * @chainable
9657 */
9658 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
9659 var i, len, name, card,
9660 items = [];
9661
9662 for ( i = 0, len = cards.length; i < len; i++ ) {
9663 card = cards[ i ];
9664 name = card.getName();
9665 delete this.cards[ name ];
9666 items.push( this.tabSelectWidget.getItemFromData( name ) );
9667 card.setTabItem( null );
9668 }
9669 if ( items.length ) {
9670 this.tabSelectWidget.removeItems( items );
9671 this.selectFirstSelectableCard();
9672 }
9673 this.stackLayout.removeItems( cards );
9674 this.emit( 'remove', cards );
9675
9676 return this;
9677 };
9678
9679 /**
9680 * Clear all cards from the index layout.
9681 *
9682 * To remove only a subset of cards from the index, use the #removeCards method.
9683 *
9684 * @fires remove
9685 * @chainable
9686 */
9687 OO.ui.IndexLayout.prototype.clearCards = function () {
9688 var i, len,
9689 cards = this.stackLayout.getItems();
9690
9691 this.cards = {};
9692 this.currentCardName = null;
9693 this.tabSelectWidget.clearItems();
9694 for ( i = 0, len = cards.length; i < len; i++ ) {
9695 cards[ i ].setTabItem( null );
9696 }
9697 this.stackLayout.clearItems();
9698
9699 this.emit( 'remove', cards );
9700
9701 return this;
9702 };
9703
9704 /**
9705 * Set the current card by symbolic name.
9706 *
9707 * @fires set
9708 * @param {string} name Symbolic name of card
9709 */
9710 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
9711 var selectedItem,
9712 $focused,
9713 card = this.cards[ name ];
9714
9715 if ( name !== this.currentCardName ) {
9716 selectedItem = this.tabSelectWidget.getSelectedItem();
9717 if ( selectedItem && selectedItem.getData() !== name ) {
9718 this.tabSelectWidget.selectItemByData( name );
9719 }
9720 if ( card ) {
9721 if ( this.currentCardName && this.cards[ this.currentCardName ] ) {
9722 this.cards[ this.currentCardName ].setActive( false );
9723 // Blur anything focused if the next card doesn't have anything focusable - this
9724 // is not needed if the next card has something focusable because once it is focused
9725 // this blur happens automatically
9726 if ( this.autoFocus && !card.$element.find( ':input' ).length ) {
9727 $focused = this.cards[ this.currentCardName ].$element.find( ':focus' );
9728 if ( $focused.length ) {
9729 $focused[ 0 ].blur();
9730 }
9731 }
9732 }
9733 this.currentCardName = name;
9734 this.stackLayout.setItem( card );
9735 card.setActive( true );
9736 this.emit( 'set', card );
9737 }
9738 }
9739 };
9740
9741 /**
9742 * Select the first selectable card.
9743 *
9744 * @chainable
9745 */
9746 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
9747 if ( !this.tabSelectWidget.getSelectedItem() ) {
9748 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
9749 }
9750
9751 return this;
9752 };
9753
9754 /**
9755 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9756 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9757 *
9758 * @example
9759 * // Example of a panel layout
9760 * var panel = new OO.ui.PanelLayout( {
9761 * expanded: false,
9762 * framed: true,
9763 * padded: true,
9764 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9765 * } );
9766 * $( 'body' ).append( panel.$element );
9767 *
9768 * @class
9769 * @extends OO.ui.Layout
9770 *
9771 * @constructor
9772 * @param {Object} [config] Configuration options
9773 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9774 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9775 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9776 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9777 */
9778 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
9779 // Configuration initialization
9780 config = $.extend( {
9781 scrollable: false,
9782 padded: false,
9783 expanded: true,
9784 framed: false
9785 }, config );
9786
9787 // Parent constructor
9788 OO.ui.PanelLayout.super.call( this, config );
9789
9790 // Initialization
9791 this.$element.addClass( 'oo-ui-panelLayout' );
9792 if ( config.scrollable ) {
9793 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
9794 }
9795 if ( config.padded ) {
9796 this.$element.addClass( 'oo-ui-panelLayout-padded' );
9797 }
9798 if ( config.expanded ) {
9799 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
9800 }
9801 if ( config.framed ) {
9802 this.$element.addClass( 'oo-ui-panelLayout-framed' );
9803 }
9804 };
9805
9806 /* Setup */
9807
9808 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
9809
9810 /**
9811 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
9812 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
9813 * rather extended to include the required content and functionality.
9814 *
9815 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
9816 * item is customized (with a label) using the #setupTabItem method. See
9817 * {@link OO.ui.IndexLayout IndexLayout} for an example.
9818 *
9819 * @class
9820 * @extends OO.ui.PanelLayout
9821 *
9822 * @constructor
9823 * @param {string} name Unique symbolic name of card
9824 * @param {Object} [config] Configuration options
9825 */
9826 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
9827 // Allow passing positional parameters inside the config object
9828 if ( OO.isPlainObject( name ) && config === undefined ) {
9829 config = name;
9830 name = config.name;
9831 }
9832
9833 // Configuration initialization
9834 config = $.extend( { scrollable: true }, config );
9835
9836 // Parent constructor
9837 OO.ui.CardLayout.super.call( this, config );
9838
9839 // Properties
9840 this.name = name;
9841 this.tabItem = null;
9842 this.active = false;
9843
9844 // Initialization
9845 this.$element.addClass( 'oo-ui-cardLayout' );
9846 };
9847
9848 /* Setup */
9849
9850 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
9851
9852 /* Events */
9853
9854 /**
9855 * An 'active' event is emitted when the card becomes active. Cards become active when they are
9856 * shown in a index layout that is configured to display only one card at a time.
9857 *
9858 * @event active
9859 * @param {boolean} active Card is active
9860 */
9861
9862 /* Methods */
9863
9864 /**
9865 * Get the symbolic name of the card.
9866 *
9867 * @return {string} Symbolic name of card
9868 */
9869 OO.ui.CardLayout.prototype.getName = function () {
9870 return this.name;
9871 };
9872
9873 /**
9874 * Check if card is active.
9875 *
9876 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
9877 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
9878 *
9879 * @return {boolean} Card is active
9880 */
9881 OO.ui.CardLayout.prototype.isActive = function () {
9882 return this.active;
9883 };
9884
9885 /**
9886 * Get tab item.
9887 *
9888 * The tab item allows users to access the card from the index's tab
9889 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
9890 *
9891 * @return {OO.ui.TabOptionWidget|null} Tab option widget
9892 */
9893 OO.ui.CardLayout.prototype.getTabItem = function () {
9894 return this.tabItem;
9895 };
9896
9897 /**
9898 * Set or unset the tab item.
9899 *
9900 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
9901 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
9902 * level), use #setupTabItem instead of this method.
9903 *
9904 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
9905 * @chainable
9906 */
9907 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
9908 this.tabItem = tabItem || null;
9909 if ( tabItem ) {
9910 this.setupTabItem();
9911 }
9912 return this;
9913 };
9914
9915 /**
9916 * Set up the tab item.
9917 *
9918 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
9919 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
9920 * the #setTabItem method instead.
9921 *
9922 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
9923 * @chainable
9924 */
9925 OO.ui.CardLayout.prototype.setupTabItem = function () {
9926 return this;
9927 };
9928
9929 /**
9930 * Set the card to its 'active' state.
9931 *
9932 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
9933 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
9934 * context, setting the active state on a card does nothing.
9935 *
9936 * @param {boolean} value Card is active
9937 * @fires active
9938 */
9939 OO.ui.CardLayout.prototype.setActive = function ( active ) {
9940 active = !!active;
9941
9942 if ( active !== this.active ) {
9943 this.active = active;
9944 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
9945 this.emit( 'active', this.active );
9946 }
9947 };
9948
9949 /**
9950 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9951 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9952 * rather extended to include the required content and functionality.
9953 *
9954 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9955 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9956 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9957 *
9958 * @class
9959 * @extends OO.ui.PanelLayout
9960 *
9961 * @constructor
9962 * @param {string} name Unique symbolic name of page
9963 * @param {Object} [config] Configuration options
9964 */
9965 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
9966 // Allow passing positional parameters inside the config object
9967 if ( OO.isPlainObject( name ) && config === undefined ) {
9968 config = name;
9969 name = config.name;
9970 }
9971
9972 // Configuration initialization
9973 config = $.extend( { scrollable: true }, config );
9974
9975 // Parent constructor
9976 OO.ui.PageLayout.super.call( this, config );
9977
9978 // Properties
9979 this.name = name;
9980 this.outlineItem = null;
9981 this.active = false;
9982
9983 // Initialization
9984 this.$element.addClass( 'oo-ui-pageLayout' );
9985 };
9986
9987 /* Setup */
9988
9989 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
9990
9991 /* Events */
9992
9993 /**
9994 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9995 * shown in a booklet layout that is configured to display only one page at a time.
9996 *
9997 * @event active
9998 * @param {boolean} active Page is active
9999 */
10000
10001 /* Methods */
10002
10003 /**
10004 * Get the symbolic name of the page.
10005 *
10006 * @return {string} Symbolic name of page
10007 */
10008 OO.ui.PageLayout.prototype.getName = function () {
10009 return this.name;
10010 };
10011
10012 /**
10013 * Check if page is active.
10014 *
10015 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10016 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10017 *
10018 * @return {boolean} Page is active
10019 */
10020 OO.ui.PageLayout.prototype.isActive = function () {
10021 return this.active;
10022 };
10023
10024 /**
10025 * Get outline item.
10026 *
10027 * The outline item allows users to access the page from the booklet's outline
10028 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10029 *
10030 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10031 */
10032 OO.ui.PageLayout.prototype.getOutlineItem = function () {
10033 return this.outlineItem;
10034 };
10035
10036 /**
10037 * Set or unset the outline item.
10038 *
10039 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10040 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10041 * level), use #setupOutlineItem instead of this method.
10042 *
10043 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10044 * @chainable
10045 */
10046 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
10047 this.outlineItem = outlineItem || null;
10048 if ( outlineItem ) {
10049 this.setupOutlineItem();
10050 }
10051 return this;
10052 };
10053
10054 /**
10055 * Set up the outline item.
10056 *
10057 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10058 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10059 * the #setOutlineItem method instead.
10060 *
10061 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10062 * @chainable
10063 */
10064 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
10065 return this;
10066 };
10067
10068 /**
10069 * Set the page to its 'active' state.
10070 *
10071 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10072 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10073 * context, setting the active state on a page does nothing.
10074 *
10075 * @param {boolean} value Page is active
10076 * @fires active
10077 */
10078 OO.ui.PageLayout.prototype.setActive = function ( active ) {
10079 active = !!active;
10080
10081 if ( active !== this.active ) {
10082 this.active = active;
10083 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
10084 this.emit( 'active', this.active );
10085 }
10086 };
10087
10088 /**
10089 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10090 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10091 * by setting the #continuous option to 'true'.
10092 *
10093 * @example
10094 * // A stack layout with two panels, configured to be displayed continously
10095 * var myStack = new OO.ui.StackLayout( {
10096 * items: [
10097 * new OO.ui.PanelLayout( {
10098 * $content: $( '<p>Panel One</p>' ),
10099 * padded: true,
10100 * framed: true
10101 * } ),
10102 * new OO.ui.PanelLayout( {
10103 * $content: $( '<p>Panel Two</p>' ),
10104 * padded: true,
10105 * framed: true
10106 * } )
10107 * ],
10108 * continuous: true
10109 * } );
10110 * $( 'body' ).append( myStack.$element );
10111 *
10112 * @class
10113 * @extends OO.ui.PanelLayout
10114 * @mixins OO.ui.GroupElement
10115 *
10116 * @constructor
10117 * @param {Object} [config] Configuration options
10118 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10119 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10120 */
10121 OO.ui.StackLayout = function OoUiStackLayout( config ) {
10122 // Configuration initialization
10123 config = $.extend( { scrollable: true }, config );
10124
10125 // Parent constructor
10126 OO.ui.StackLayout.super.call( this, config );
10127
10128 // Mixin constructors
10129 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10130
10131 // Properties
10132 this.currentItem = null;
10133 this.continuous = !!config.continuous;
10134
10135 // Initialization
10136 this.$element.addClass( 'oo-ui-stackLayout' );
10137 if ( this.continuous ) {
10138 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
10139 }
10140 if ( Array.isArray( config.items ) ) {
10141 this.addItems( config.items );
10142 }
10143 };
10144
10145 /* Setup */
10146
10147 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
10148 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
10149
10150 /* Events */
10151
10152 /**
10153 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10154 * {@link #clearItems cleared} or {@link #setItem displayed}.
10155 *
10156 * @event set
10157 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10158 */
10159
10160 /* Methods */
10161
10162 /**
10163 * Get the current panel.
10164 *
10165 * @return {OO.ui.Layout|null}
10166 */
10167 OO.ui.StackLayout.prototype.getCurrentItem = function () {
10168 return this.currentItem;
10169 };
10170
10171 /**
10172 * Unset the current item.
10173 *
10174 * @private
10175 * @param {OO.ui.StackLayout} layout
10176 * @fires set
10177 */
10178 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
10179 var prevItem = this.currentItem;
10180 if ( prevItem === null ) {
10181 return;
10182 }
10183
10184 this.currentItem = null;
10185 this.emit( 'set', null );
10186 };
10187
10188 /**
10189 * Add panel layouts to the stack layout.
10190 *
10191 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10192 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10193 * by the index.
10194 *
10195 * @param {OO.ui.Layout[]} items Panels to add
10196 * @param {number} [index] Index of the insertion point
10197 * @chainable
10198 */
10199 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
10200 // Update the visibility
10201 this.updateHiddenState( items, this.currentItem );
10202
10203 // Mixin method
10204 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
10205
10206 if ( !this.currentItem && items.length ) {
10207 this.setItem( items[ 0 ] );
10208 }
10209
10210 return this;
10211 };
10212
10213 /**
10214 * Remove the specified panels from the stack layout.
10215 *
10216 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10217 * you may wish to use the #clearItems method instead.
10218 *
10219 * @param {OO.ui.Layout[]} items Panels to remove
10220 * @chainable
10221 * @fires set
10222 */
10223 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
10224 // Mixin method
10225 OO.ui.GroupElement.prototype.removeItems.call( this, items );
10226
10227 if ( $.inArray( this.currentItem, items ) !== -1 ) {
10228 if ( this.items.length ) {
10229 this.setItem( this.items[ 0 ] );
10230 } else {
10231 this.unsetCurrentItem();
10232 }
10233 }
10234
10235 return this;
10236 };
10237
10238 /**
10239 * Clear all panels from the stack layout.
10240 *
10241 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10242 * a subset of panels, use the #removeItems method.
10243 *
10244 * @chainable
10245 * @fires set
10246 */
10247 OO.ui.StackLayout.prototype.clearItems = function () {
10248 this.unsetCurrentItem();
10249 OO.ui.GroupElement.prototype.clearItems.call( this );
10250
10251 return this;
10252 };
10253
10254 /**
10255 * Show the specified panel.
10256 *
10257 * If another panel is currently displayed, it will be hidden.
10258 *
10259 * @param {OO.ui.Layout} item Panel to show
10260 * @chainable
10261 * @fires set
10262 */
10263 OO.ui.StackLayout.prototype.setItem = function ( item ) {
10264 if ( item !== this.currentItem ) {
10265 this.updateHiddenState( this.items, item );
10266
10267 if ( $.inArray( item, this.items ) !== -1 ) {
10268 this.currentItem = item;
10269 this.emit( 'set', item );
10270 } else {
10271 this.unsetCurrentItem();
10272 }
10273 }
10274
10275 return this;
10276 };
10277
10278 /**
10279 * Update the visibility of all items in case of non-continuous view.
10280 *
10281 * Ensure all items are hidden except for the selected one.
10282 * This method does nothing when the stack is continuous.
10283 *
10284 * @private
10285 * @param {OO.ui.Layout[]} items Item list iterate over
10286 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10287 */
10288 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
10289 var i, len;
10290
10291 if ( !this.continuous ) {
10292 for ( i = 0, len = items.length; i < len; i++ ) {
10293 if ( !selectedItem || selectedItem !== items[ i ] ) {
10294 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
10295 }
10296 }
10297 if ( selectedItem ) {
10298 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
10299 }
10300 }
10301 };
10302
10303 /**
10304 * Horizontal bar layout of tools as icon buttons.
10305 *
10306 * @class
10307 * @extends OO.ui.ToolGroup
10308 *
10309 * @constructor
10310 * @param {OO.ui.Toolbar} toolbar
10311 * @param {Object} [config] Configuration options
10312 */
10313 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
10314 // Allow passing positional parameters inside the config object
10315 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10316 config = toolbar;
10317 toolbar = config.toolbar;
10318 }
10319
10320 // Parent constructor
10321 OO.ui.BarToolGroup.super.call( this, toolbar, config );
10322
10323 // Initialization
10324 this.$element.addClass( 'oo-ui-barToolGroup' );
10325 };
10326
10327 /* Setup */
10328
10329 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
10330
10331 /* Static Properties */
10332
10333 OO.ui.BarToolGroup.static.titleTooltips = true;
10334
10335 OO.ui.BarToolGroup.static.accelTooltips = true;
10336
10337 OO.ui.BarToolGroup.static.name = 'bar';
10338
10339 /**
10340 * Popup list of tools with an icon and optional label.
10341 *
10342 * @abstract
10343 * @class
10344 * @extends OO.ui.ToolGroup
10345 * @mixins OO.ui.IconElement
10346 * @mixins OO.ui.IndicatorElement
10347 * @mixins OO.ui.LabelElement
10348 * @mixins OO.ui.TitledElement
10349 * @mixins OO.ui.ClippableElement
10350 * @mixins OO.ui.TabIndexedElement
10351 *
10352 * @constructor
10353 * @param {OO.ui.Toolbar} toolbar
10354 * @param {Object} [config] Configuration options
10355 * @cfg {string} [header] Text to display at the top of the pop-up
10356 */
10357 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
10358 // Allow passing positional parameters inside the config object
10359 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10360 config = toolbar;
10361 toolbar = config.toolbar;
10362 }
10363
10364 // Configuration initialization
10365 config = config || {};
10366
10367 // Parent constructor
10368 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
10369
10370 // Properties
10371 this.active = false;
10372 this.dragging = false;
10373 this.onBlurHandler = this.onBlur.bind( this );
10374 this.$handle = $( '<span>' );
10375
10376 // Mixin constructors
10377 OO.ui.IconElement.call( this, config );
10378 OO.ui.IndicatorElement.call( this, config );
10379 OO.ui.LabelElement.call( this, config );
10380 OO.ui.TitledElement.call( this, config );
10381 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
10382 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10383
10384 // Events
10385 this.$handle.on( {
10386 keydown: this.onHandleMouseKeyDown.bind( this ),
10387 keyup: this.onHandleMouseKeyUp.bind( this ),
10388 mousedown: this.onHandleMouseKeyDown.bind( this ),
10389 mouseup: this.onHandleMouseKeyUp.bind( this )
10390 } );
10391
10392 // Initialization
10393 this.$handle
10394 .addClass( 'oo-ui-popupToolGroup-handle' )
10395 .append( this.$icon, this.$label, this.$indicator );
10396 // If the pop-up should have a header, add it to the top of the toolGroup.
10397 // Note: If this feature is useful for other widgets, we could abstract it into an
10398 // OO.ui.HeaderedElement mixin constructor.
10399 if ( config.header !== undefined ) {
10400 this.$group
10401 .prepend( $( '<span>' )
10402 .addClass( 'oo-ui-popupToolGroup-header' )
10403 .text( config.header )
10404 );
10405 }
10406 this.$element
10407 .addClass( 'oo-ui-popupToolGroup' )
10408 .prepend( this.$handle );
10409 };
10410
10411 /* Setup */
10412
10413 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
10414 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
10415 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
10416 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
10417 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
10418 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
10419 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TabIndexedElement );
10420
10421 /* Methods */
10422
10423 /**
10424 * @inheritdoc
10425 */
10426 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
10427 // Parent method
10428 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
10429
10430 if ( this.isDisabled() && this.isElementAttached() ) {
10431 this.setActive( false );
10432 }
10433 };
10434
10435 /**
10436 * Handle focus being lost.
10437 *
10438 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
10439 *
10440 * @param {jQuery.Event} e Mouse up or key up event
10441 */
10442 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
10443 // Only deactivate when clicking outside the dropdown element
10444 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
10445 this.setActive( false );
10446 }
10447 };
10448
10449 /**
10450 * @inheritdoc
10451 */
10452 OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
10453 // Only close toolgroup when a tool was actually selected
10454 if (
10455 !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) &&
10456 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10457 ) {
10458 this.setActive( false );
10459 }
10460 return OO.ui.PopupToolGroup.super.prototype.onMouseKeyUp.call( this, e );
10461 };
10462
10463 /**
10464 * Handle mouse up and key up events.
10465 *
10466 * @param {jQuery.Event} e Mouse up or key up event
10467 */
10468 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
10469 if (
10470 !this.isDisabled() &&
10471 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10472 ) {
10473 return false;
10474 }
10475 };
10476
10477 /**
10478 * Handle mouse down and key down events.
10479 *
10480 * @param {jQuery.Event} e Mouse down or key down event
10481 */
10482 OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
10483 if (
10484 !this.isDisabled() &&
10485 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10486 ) {
10487 this.setActive( !this.active );
10488 return false;
10489 }
10490 };
10491
10492 /**
10493 * Switch into active mode.
10494 *
10495 * When active, mouseup events anywhere in the document will trigger deactivation.
10496 */
10497 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
10498 value = !!value;
10499 if ( this.active !== value ) {
10500 this.active = value;
10501 if ( value ) {
10502 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
10503 this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true );
10504
10505 // Try anchoring the popup to the left first
10506 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
10507 this.toggleClipping( true );
10508 if ( this.isClippedHorizontally() ) {
10509 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
10510 this.toggleClipping( false );
10511 this.$element
10512 .removeClass( 'oo-ui-popupToolGroup-left' )
10513 .addClass( 'oo-ui-popupToolGroup-right' );
10514 this.toggleClipping( true );
10515 }
10516 } else {
10517 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
10518 this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true );
10519 this.$element.removeClass(
10520 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
10521 );
10522 this.toggleClipping( false );
10523 }
10524 }
10525 };
10526
10527 /**
10528 * Drop down list layout of tools as labeled icon buttons.
10529 *
10530 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
10531 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
10532 * may want to use the 'promote' and 'demote' configuration options to achieve this.
10533 *
10534 * @class
10535 * @extends OO.ui.PopupToolGroup
10536 *
10537 * @constructor
10538 * @param {OO.ui.Toolbar} toolbar
10539 * @param {Object} [config] Configuration options
10540 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
10541 * shown.
10542 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
10543 * allowed to be collapsed.
10544 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
10545 */
10546 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
10547 // Allow passing positional parameters inside the config object
10548 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10549 config = toolbar;
10550 toolbar = config.toolbar;
10551 }
10552
10553 // Configuration initialization
10554 config = config || {};
10555
10556 // Properties (must be set before parent constructor, which calls #populate)
10557 this.allowCollapse = config.allowCollapse;
10558 this.forceExpand = config.forceExpand;
10559 this.expanded = config.expanded !== undefined ? config.expanded : false;
10560 this.collapsibleTools = [];
10561
10562 // Parent constructor
10563 OO.ui.ListToolGroup.super.call( this, toolbar, config );
10564
10565 // Initialization
10566 this.$element.addClass( 'oo-ui-listToolGroup' );
10567 };
10568
10569 /* Setup */
10570
10571 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
10572
10573 /* Static Properties */
10574
10575 OO.ui.ListToolGroup.static.name = 'list';
10576
10577 /* Methods */
10578
10579 /**
10580 * @inheritdoc
10581 */
10582 OO.ui.ListToolGroup.prototype.populate = function () {
10583 var i, len, allowCollapse = [];
10584
10585 OO.ui.ListToolGroup.super.prototype.populate.call( this );
10586
10587 // Update the list of collapsible tools
10588 if ( this.allowCollapse !== undefined ) {
10589 allowCollapse = this.allowCollapse;
10590 } else if ( this.forceExpand !== undefined ) {
10591 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
10592 }
10593
10594 this.collapsibleTools = [];
10595 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
10596 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
10597 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
10598 }
10599 }
10600
10601 // Keep at the end, even when tools are added
10602 this.$group.append( this.getExpandCollapseTool().$element );
10603
10604 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
10605 this.updateCollapsibleState();
10606 };
10607
10608 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
10609 if ( this.expandCollapseTool === undefined ) {
10610 var ExpandCollapseTool = function () {
10611 ExpandCollapseTool.super.apply( this, arguments );
10612 };
10613
10614 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
10615
10616 ExpandCollapseTool.prototype.onSelect = function () {
10617 this.toolGroup.expanded = !this.toolGroup.expanded;
10618 this.toolGroup.updateCollapsibleState();
10619 this.setActive( false );
10620 };
10621 ExpandCollapseTool.prototype.onUpdateState = function () {
10622 // Do nothing. Tool interface requires an implementation of this function.
10623 };
10624
10625 ExpandCollapseTool.static.name = 'more-fewer';
10626
10627 this.expandCollapseTool = new ExpandCollapseTool( this );
10628 }
10629 return this.expandCollapseTool;
10630 };
10631
10632 /**
10633 * @inheritdoc
10634 */
10635 OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
10636 // Do not close the popup when the user wants to show more/fewer tools
10637 if (
10638 $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length &&
10639 ( e.which === 1 || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
10640 ) {
10641 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
10642 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
10643 return OO.ui.ListToolGroup.super.super.prototype.onMouseKeyUp.call( this, e );
10644 } else {
10645 return OO.ui.ListToolGroup.super.prototype.onMouseKeyUp.call( this, e );
10646 }
10647 };
10648
10649 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
10650 var i, len;
10651
10652 this.getExpandCollapseTool()
10653 .setIcon( this.expanded ? 'collapse' : 'expand' )
10654 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
10655
10656 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
10657 this.collapsibleTools[ i ].toggle( this.expanded );
10658 }
10659 };
10660
10661 /**
10662 * Drop down menu layout of tools as selectable menu items.
10663 *
10664 * @class
10665 * @extends OO.ui.PopupToolGroup
10666 *
10667 * @constructor
10668 * @param {OO.ui.Toolbar} toolbar
10669 * @param {Object} [config] Configuration options
10670 */
10671 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
10672 // Allow passing positional parameters inside the config object
10673 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
10674 config = toolbar;
10675 toolbar = config.toolbar;
10676 }
10677
10678 // Configuration initialization
10679 config = config || {};
10680
10681 // Parent constructor
10682 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
10683
10684 // Events
10685 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
10686
10687 // Initialization
10688 this.$element.addClass( 'oo-ui-menuToolGroup' );
10689 };
10690
10691 /* Setup */
10692
10693 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
10694
10695 /* Static Properties */
10696
10697 OO.ui.MenuToolGroup.static.name = 'menu';
10698
10699 /* Methods */
10700
10701 /**
10702 * Handle the toolbar state being updated.
10703 *
10704 * When the state changes, the title of each active item in the menu will be joined together and
10705 * used as a label for the group. The label will be empty if none of the items are active.
10706 */
10707 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
10708 var name,
10709 labelTexts = [];
10710
10711 for ( name in this.tools ) {
10712 if ( this.tools[ name ].isActive() ) {
10713 labelTexts.push( this.tools[ name ].getTitle() );
10714 }
10715 }
10716
10717 this.setLabel( labelTexts.join( ', ' ) || ' ' );
10718 };
10719
10720 /**
10721 * Tool that shows a popup when selected.
10722 *
10723 * @abstract
10724 * @class
10725 * @extends OO.ui.Tool
10726 * @mixins OO.ui.PopupElement
10727 *
10728 * @constructor
10729 * @param {OO.ui.ToolGroup} toolGroup
10730 * @param {Object} [config] Configuration options
10731 */
10732 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
10733 // Allow passing positional parameters inside the config object
10734 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
10735 config = toolGroup;
10736 toolGroup = config.toolGroup;
10737 }
10738
10739 // Parent constructor
10740 OO.ui.PopupTool.super.call( this, toolGroup, config );
10741
10742 // Mixin constructors
10743 OO.ui.PopupElement.call( this, config );
10744
10745 // Initialization
10746 this.$element
10747 .addClass( 'oo-ui-popupTool' )
10748 .append( this.popup.$element );
10749 };
10750
10751 /* Setup */
10752
10753 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
10754 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
10755
10756 /* Methods */
10757
10758 /**
10759 * Handle the tool being selected.
10760 *
10761 * @inheritdoc
10762 */
10763 OO.ui.PopupTool.prototype.onSelect = function () {
10764 if ( !this.isDisabled() ) {
10765 this.popup.toggle();
10766 }
10767 this.setActive( false );
10768 return false;
10769 };
10770
10771 /**
10772 * Handle the toolbar state being updated.
10773 *
10774 * @inheritdoc
10775 */
10776 OO.ui.PopupTool.prototype.onUpdateState = function () {
10777 this.setActive( false );
10778 };
10779
10780 /**
10781 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
10782 * menus in toolbars (T74159).
10783 *
10784 * @abstract
10785 * @class
10786 * @extends OO.ui.Tool
10787 *
10788 * @constructor
10789 * @param {OO.ui.ToolGroup} toolGroup
10790 * @param {Object} [config] Configuration options
10791 */
10792 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
10793 // Allow passing positional parameters inside the config object
10794 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
10795 config = toolGroup;
10796 toolGroup = config.toolGroup;
10797 }
10798
10799 // Parent constructor
10800 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
10801
10802 // Properties
10803 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
10804
10805 // Events
10806 this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } );
10807
10808 // Initialization
10809 this.$link.remove();
10810 this.$element
10811 .addClass( 'oo-ui-toolGroupTool' )
10812 .append( this.innerToolGroup.$element );
10813 };
10814
10815 /* Setup */
10816
10817 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
10818
10819 /* Static Properties */
10820
10821 /**
10822 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
10823 *
10824 * @property {Object.<string,Array>}
10825 */
10826 OO.ui.ToolGroupTool.static.groupConfig = {};
10827
10828 /* Methods */
10829
10830 /**
10831 * Handle the tool being selected.
10832 *
10833 * @inheritdoc
10834 */
10835 OO.ui.ToolGroupTool.prototype.onSelect = function () {
10836 this.innerToolGroup.setActive( !this.innerToolGroup.active );
10837 return false;
10838 };
10839
10840 /**
10841 * Synchronize disabledness state of the tool with the inner toolgroup.
10842 *
10843 * @private
10844 * @param {boolean} disabled Element is disabled
10845 */
10846 OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
10847 this.setDisabled( disabled );
10848 };
10849
10850 /**
10851 * Handle the toolbar state being updated.
10852 *
10853 * @inheritdoc
10854 */
10855 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
10856 this.setActive( false );
10857 };
10858
10859 /**
10860 * Build a OO.ui.ToolGroup from the configuration.
10861 *
10862 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
10863 * accepted values.
10864 * @return {OO.ui.ListToolGroup}
10865 */
10866 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
10867 if ( group.include === '*' ) {
10868 // Apply defaults to catch-all groups
10869 if ( group.label === undefined ) {
10870 group.label = OO.ui.msg( 'ooui-toolbar-more' );
10871 }
10872 }
10873
10874 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
10875 };
10876
10877 /**
10878 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
10879 *
10880 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
10881 *
10882 * @private
10883 * @abstract
10884 * @class
10885 * @extends OO.ui.GroupElement
10886 *
10887 * @constructor
10888 * @param {Object} [config] Configuration options
10889 */
10890 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
10891 // Parent constructor
10892 OO.ui.GroupWidget.super.call( this, config );
10893 };
10894
10895 /* Setup */
10896
10897 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
10898
10899 /* Methods */
10900
10901 /**
10902 * Set the disabled state of the widget.
10903 *
10904 * This will also update the disabled state of child widgets.
10905 *
10906 * @param {boolean} disabled Disable widget
10907 * @chainable
10908 */
10909 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
10910 var i, len;
10911
10912 // Parent method
10913 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
10914 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
10915
10916 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
10917 if ( this.items ) {
10918 for ( i = 0, len = this.items.length; i < len; i++ ) {
10919 this.items[ i ].updateDisabled();
10920 }
10921 }
10922
10923 return this;
10924 };
10925
10926 /**
10927 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
10928 *
10929 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
10930 * allows bidirectional communication.
10931 *
10932 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
10933 *
10934 * @private
10935 * @abstract
10936 * @class
10937 *
10938 * @constructor
10939 */
10940 OO.ui.ItemWidget = function OoUiItemWidget() {
10941 //
10942 };
10943
10944 /* Methods */
10945
10946 /**
10947 * Check if widget is disabled.
10948 *
10949 * Checks parent if present, making disabled state inheritable.
10950 *
10951 * @return {boolean} Widget is disabled
10952 */
10953 OO.ui.ItemWidget.prototype.isDisabled = function () {
10954 return this.disabled ||
10955 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
10956 };
10957
10958 /**
10959 * Set group element is in.
10960 *
10961 * @param {OO.ui.GroupElement|null} group Group element, null if none
10962 * @chainable
10963 */
10964 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
10965 // Parent method
10966 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10967 OO.ui.Element.prototype.setElementGroup.call( this, group );
10968
10969 // Initialize item disabled states
10970 this.updateDisabled();
10971
10972 return this;
10973 };
10974
10975 /**
10976 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10977 * Controls include moving items up and down, removing items, and adding different kinds of items.
10978 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
10979 *
10980 * @class
10981 * @extends OO.ui.Widget
10982 * @mixins OO.ui.GroupElement
10983 * @mixins OO.ui.IconElement
10984 *
10985 * @constructor
10986 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10987 * @param {Object} [config] Configuration options
10988 * @cfg {Object} [abilities] List of abilties
10989 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10990 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10991 */
10992 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
10993 // Allow passing positional parameters inside the config object
10994 if ( OO.isPlainObject( outline ) && config === undefined ) {
10995 config = outline;
10996 outline = config.outline;
10997 }
10998
10999 // Configuration initialization
11000 config = $.extend( { icon: 'add' }, config );
11001
11002 // Parent constructor
11003 OO.ui.OutlineControlsWidget.super.call( this, config );
11004
11005 // Mixin constructors
11006 OO.ui.GroupElement.call( this, config );
11007 OO.ui.IconElement.call( this, config );
11008
11009 // Properties
11010 this.outline = outline;
11011 this.$movers = $( '<div>' );
11012 this.upButton = new OO.ui.ButtonWidget( {
11013 framed: false,
11014 icon: 'collapse',
11015 title: OO.ui.msg( 'ooui-outline-control-move-up' )
11016 } );
11017 this.downButton = new OO.ui.ButtonWidget( {
11018 framed: false,
11019 icon: 'expand',
11020 title: OO.ui.msg( 'ooui-outline-control-move-down' )
11021 } );
11022 this.removeButton = new OO.ui.ButtonWidget( {
11023 framed: false,
11024 icon: 'remove',
11025 title: OO.ui.msg( 'ooui-outline-control-remove' )
11026 } );
11027 this.abilities = { move: true, remove: true };
11028
11029 // Events
11030 outline.connect( this, {
11031 select: 'onOutlineChange',
11032 add: 'onOutlineChange',
11033 remove: 'onOutlineChange'
11034 } );
11035 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
11036 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
11037 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
11038
11039 // Initialization
11040 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
11041 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
11042 this.$movers
11043 .addClass( 'oo-ui-outlineControlsWidget-movers' )
11044 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
11045 this.$element.append( this.$icon, this.$group, this.$movers );
11046 this.setAbilities( config.abilities || {} );
11047 };
11048
11049 /* Setup */
11050
11051 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
11052 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
11053 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
11054
11055 /* Events */
11056
11057 /**
11058 * @event move
11059 * @param {number} places Number of places to move
11060 */
11061
11062 /**
11063 * @event remove
11064 */
11065
11066 /* Methods */
11067
11068 /**
11069 * Set abilities.
11070 *
11071 * @param {Object} abilities List of abilties
11072 * @param {boolean} [abilities.move] Allow moving movable items
11073 * @param {boolean} [abilities.remove] Allow removing removable items
11074 */
11075 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
11076 var ability;
11077
11078 for ( ability in this.abilities ) {
11079 if ( abilities[ability] !== undefined ) {
11080 this.abilities[ability] = !!abilities[ability];
11081 }
11082 }
11083
11084 this.onOutlineChange();
11085 };
11086
11087 /**
11088 *
11089 * @private
11090 * Handle outline change events.
11091 */
11092 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
11093 var i, len, firstMovable, lastMovable,
11094 items = this.outline.getItems(),
11095 selectedItem = this.outline.getSelectedItem(),
11096 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
11097 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
11098
11099 if ( movable ) {
11100 i = -1;
11101 len = items.length;
11102 while ( ++i < len ) {
11103 if ( items[ i ].isMovable() ) {
11104 firstMovable = items[ i ];
11105 break;
11106 }
11107 }
11108 i = len;
11109 while ( i-- ) {
11110 if ( items[ i ].isMovable() ) {
11111 lastMovable = items[ i ];
11112 break;
11113 }
11114 }
11115 }
11116 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
11117 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
11118 this.removeButton.setDisabled( !removable );
11119 };
11120
11121 /**
11122 * ToggleWidget implements basic behavior of widgets with an on/off state.
11123 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
11124 *
11125 * @abstract
11126 * @class
11127 * @extends OO.ui.Widget
11128 *
11129 * @constructor
11130 * @param {Object} [config] Configuration options
11131 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
11132 * By default, the toggle is in the 'off' state.
11133 */
11134 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
11135 // Configuration initialization
11136 config = config || {};
11137
11138 // Parent constructor
11139 OO.ui.ToggleWidget.super.call( this, config );
11140
11141 // Properties
11142 this.value = null;
11143
11144 // Initialization
11145 this.$element.addClass( 'oo-ui-toggleWidget' );
11146 this.setValue( !!config.value );
11147 };
11148
11149 /* Setup */
11150
11151 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
11152
11153 /* Events */
11154
11155 /**
11156 * @event change
11157 *
11158 * A change event is emitted when the on/off state of the toggle changes.
11159 *
11160 * @param {boolean} value Value representing the new state of the toggle
11161 */
11162
11163 /* Methods */
11164
11165 /**
11166 * Get the value representing the toggle’s state.
11167 *
11168 * @return {boolean} The on/off state of the toggle
11169 */
11170 OO.ui.ToggleWidget.prototype.getValue = function () {
11171 return this.value;
11172 };
11173
11174 /**
11175 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
11176 *
11177 * @param {boolean} value The state of the toggle
11178 * @fires change
11179 * @chainable
11180 */
11181 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
11182 value = !!value;
11183 if ( this.value !== value ) {
11184 this.value = value;
11185 this.emit( 'change', value );
11186 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
11187 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
11188 this.$element.attr( 'aria-checked', value.toString() );
11189 }
11190 return this;
11191 };
11192
11193 /**
11194 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
11195 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
11196 * removed, and cleared from the group.
11197 *
11198 * @example
11199 * // Example: A ButtonGroupWidget with two buttons
11200 * var button1 = new OO.ui.PopupButtonWidget( {
11201 * label: 'Select a category',
11202 * icon: 'menu',
11203 * popup: {
11204 * $content: $( '<p>List of categories...</p>' ),
11205 * padded: true,
11206 * align: 'left'
11207 * }
11208 * } );
11209 * var button2 = new OO.ui.ButtonWidget( {
11210 * label: 'Add item'
11211 * });
11212 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
11213 * items: [button1, button2]
11214 * } );
11215 * $( 'body' ).append( buttonGroup.$element );
11216 *
11217 * @class
11218 * @extends OO.ui.Widget
11219 * @mixins OO.ui.GroupElement
11220 *
11221 * @constructor
11222 * @param {Object} [config] Configuration options
11223 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
11224 */
11225 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
11226 // Configuration initialization
11227 config = config || {};
11228
11229 // Parent constructor
11230 OO.ui.ButtonGroupWidget.super.call( this, config );
11231
11232 // Mixin constructors
11233 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
11234
11235 // Initialization
11236 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
11237 if ( Array.isArray( config.items ) ) {
11238 this.addItems( config.items );
11239 }
11240 };
11241
11242 /* Setup */
11243
11244 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
11245 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
11246
11247 /**
11248 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
11249 * feels, and functionality can be customized via the class’s configuration options
11250 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11251 * and examples.
11252 *
11253 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
11254 *
11255 * @example
11256 * // A button widget
11257 * var button = new OO.ui.ButtonWidget( {
11258 * label: 'Button with Icon',
11259 * icon: 'remove',
11260 * iconTitle: 'Remove'
11261 * } );
11262 * $( 'body' ).append( button.$element );
11263 *
11264 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
11265 *
11266 * @class
11267 * @extends OO.ui.Widget
11268 * @mixins OO.ui.ButtonElement
11269 * @mixins OO.ui.IconElement
11270 * @mixins OO.ui.IndicatorElement
11271 * @mixins OO.ui.LabelElement
11272 * @mixins OO.ui.TitledElement
11273 * @mixins OO.ui.FlaggedElement
11274 * @mixins OO.ui.TabIndexedElement
11275 *
11276 * @constructor
11277 * @param {Object} [config] Configuration options
11278 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
11279 * @cfg {string} [target] The frame or window in which to open the hyperlink.
11280 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
11281 */
11282 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
11283 // Configuration initialization
11284 config = config || {};
11285
11286 // Parent constructor
11287 OO.ui.ButtonWidget.super.call( this, config );
11288
11289 // Mixin constructors
11290 OO.ui.ButtonElement.call( this, config );
11291 OO.ui.IconElement.call( this, config );
11292 OO.ui.IndicatorElement.call( this, config );
11293 OO.ui.LabelElement.call( this, config );
11294 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
11295 OO.ui.FlaggedElement.call( this, config );
11296 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
11297
11298 // Properties
11299 this.href = null;
11300 this.target = null;
11301 this.noFollow = false;
11302
11303 // Events
11304 this.connect( this, { disable: 'onDisable' } );
11305
11306 // Initialization
11307 this.$button.append( this.$icon, this.$label, this.$indicator );
11308 this.$element
11309 .addClass( 'oo-ui-buttonWidget' )
11310 .append( this.$button );
11311 this.setHref( config.href );
11312 this.setTarget( config.target );
11313 this.setNoFollow( config.noFollow );
11314 };
11315
11316 /* Setup */
11317
11318 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
11319 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
11320 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
11321 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
11322 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
11323 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
11324 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
11325 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
11326
11327 /* Methods */
11328
11329 /**
11330 * @inheritdoc
11331 */
11332 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
11333 if ( !this.isDisabled() ) {
11334 // Remove the tab-index while the button is down to prevent the button from stealing focus
11335 this.$button.removeAttr( 'tabindex' );
11336 }
11337
11338 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
11339 };
11340
11341 /**
11342 * @inheritdoc
11343 */
11344 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
11345 if ( !this.isDisabled() ) {
11346 // Restore the tab-index after the button is up to restore the button's accessibility
11347 this.$button.attr( 'tabindex', this.tabIndex );
11348 }
11349
11350 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
11351 };
11352
11353 /**
11354 * Get hyperlink location.
11355 *
11356 * @return {string} Hyperlink location
11357 */
11358 OO.ui.ButtonWidget.prototype.getHref = function () {
11359 return this.href;
11360 };
11361
11362 /**
11363 * Get hyperlink target.
11364 *
11365 * @return {string} Hyperlink target
11366 */
11367 OO.ui.ButtonWidget.prototype.getTarget = function () {
11368 return this.target;
11369 };
11370
11371 /**
11372 * Get search engine traversal hint.
11373 *
11374 * @return {boolean} Whether search engines should avoid traversing this hyperlink
11375 */
11376 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
11377 return this.noFollow;
11378 };
11379
11380 /**
11381 * Set hyperlink location.
11382 *
11383 * @param {string|null} href Hyperlink location, null to remove
11384 */
11385 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
11386 href = typeof href === 'string' ? href : null;
11387
11388 if ( href !== this.href ) {
11389 this.href = href;
11390 this.updateHref();
11391 }
11392
11393 return this;
11394 };
11395
11396 /**
11397 * Update the `href` attribute, in case of changes to href or
11398 * disabled state.
11399 *
11400 * @private
11401 * @chainable
11402 */
11403 OO.ui.ButtonWidget.prototype.updateHref = function () {
11404 if ( this.href !== null && !this.isDisabled() ) {
11405 this.$button.attr( 'href', this.href );
11406 } else {
11407 this.$button.removeAttr( 'href' );
11408 }
11409
11410 return this;
11411 };
11412
11413 /**
11414 * Handle disable events.
11415 *
11416 * @private
11417 * @param {boolean} disabled Element is disabled
11418 */
11419 OO.ui.ButtonWidget.prototype.onDisable = function () {
11420 this.updateHref();
11421 };
11422
11423 /**
11424 * Set hyperlink target.
11425 *
11426 * @param {string|null} target Hyperlink target, null to remove
11427 */
11428 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
11429 target = typeof target === 'string' ? target : null;
11430
11431 if ( target !== this.target ) {
11432 this.target = target;
11433 if ( target !== null ) {
11434 this.$button.attr( 'target', target );
11435 } else {
11436 this.$button.removeAttr( 'target' );
11437 }
11438 }
11439
11440 return this;
11441 };
11442
11443 /**
11444 * Set search engine traversal hint.
11445 *
11446 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
11447 */
11448 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
11449 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
11450
11451 if ( noFollow !== this.noFollow ) {
11452 this.noFollow = noFollow;
11453 if ( noFollow ) {
11454 this.$button.attr( 'rel', 'nofollow' );
11455 } else {
11456 this.$button.removeAttr( 'rel' );
11457 }
11458 }
11459
11460 return this;
11461 };
11462
11463 /**
11464 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
11465 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
11466 * of the actions.
11467 *
11468 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
11469 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
11470 * and examples.
11471 *
11472 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
11473 *
11474 * @class
11475 * @extends OO.ui.ButtonWidget
11476 * @mixins OO.ui.PendingElement
11477 *
11478 * @constructor
11479 * @param {Object} [config] Configuration options
11480 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
11481 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
11482 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
11483 * for more information about setting modes.
11484 * @cfg {boolean} [framed=false] Render the action button with a frame
11485 */
11486 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
11487 // Configuration initialization
11488 config = $.extend( { framed: false }, config );
11489
11490 // Parent constructor
11491 OO.ui.ActionWidget.super.call( this, config );
11492
11493 // Mixin constructors
11494 OO.ui.PendingElement.call( this, config );
11495
11496 // Properties
11497 this.action = config.action || '';
11498 this.modes = config.modes || [];
11499 this.width = 0;
11500 this.height = 0;
11501
11502 // Initialization
11503 this.$element.addClass( 'oo-ui-actionWidget' );
11504 };
11505
11506 /* Setup */
11507
11508 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
11509 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
11510
11511 /* Events */
11512
11513 /**
11514 * A resize event is emitted when the size of the widget changes.
11515 *
11516 * @event resize
11517 */
11518
11519 /* Methods */
11520
11521 /**
11522 * Check if the action is configured to be available in the specified `mode`.
11523 *
11524 * @param {string} mode Name of mode
11525 * @return {boolean} The action is configured with the mode
11526 */
11527 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
11528 return this.modes.indexOf( mode ) !== -1;
11529 };
11530
11531 /**
11532 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
11533 *
11534 * @return {string}
11535 */
11536 OO.ui.ActionWidget.prototype.getAction = function () {
11537 return this.action;
11538 };
11539
11540 /**
11541 * Get the symbolic name of the mode or modes for which the action is configured to be available.
11542 *
11543 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
11544 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
11545 * are hidden.
11546 *
11547 * @return {string[]}
11548 */
11549 OO.ui.ActionWidget.prototype.getModes = function () {
11550 return this.modes.slice();
11551 };
11552
11553 /**
11554 * Emit a resize event if the size has changed.
11555 *
11556 * @private
11557 * @chainable
11558 */
11559 OO.ui.ActionWidget.prototype.propagateResize = function () {
11560 var width, height;
11561
11562 if ( this.isElementAttached() ) {
11563 width = this.$element.width();
11564 height = this.$element.height();
11565
11566 if ( width !== this.width || height !== this.height ) {
11567 this.width = width;
11568 this.height = height;
11569 this.emit( 'resize' );
11570 }
11571 }
11572
11573 return this;
11574 };
11575
11576 /**
11577 * @inheritdoc
11578 */
11579 OO.ui.ActionWidget.prototype.setIcon = function () {
11580 // Mixin method
11581 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
11582 this.propagateResize();
11583
11584 return this;
11585 };
11586
11587 /**
11588 * @inheritdoc
11589 */
11590 OO.ui.ActionWidget.prototype.setLabel = function () {
11591 // Mixin method
11592 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
11593 this.propagateResize();
11594
11595 return this;
11596 };
11597
11598 /**
11599 * @inheritdoc
11600 */
11601 OO.ui.ActionWidget.prototype.setFlags = function () {
11602 // Mixin method
11603 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
11604 this.propagateResize();
11605
11606 return this;
11607 };
11608
11609 /**
11610 * @inheritdoc
11611 */
11612 OO.ui.ActionWidget.prototype.clearFlags = function () {
11613 // Mixin method
11614 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
11615 this.propagateResize();
11616
11617 return this;
11618 };
11619
11620 /**
11621 * Toggle the visibility of the action button.
11622 *
11623 * @param {boolean} [show] Show button, omit to toggle visibility
11624 * @chainable
11625 */
11626 OO.ui.ActionWidget.prototype.toggle = function () {
11627 // Parent method
11628 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
11629 this.propagateResize();
11630
11631 return this;
11632 };
11633
11634 /**
11635 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
11636 * which is used to display additional information or options.
11637 *
11638 * @example
11639 * // Example of a popup button.
11640 * var popupButton = new OO.ui.PopupButtonWidget( {
11641 * label: 'Popup button with options',
11642 * icon: 'menu',
11643 * popup: {
11644 * $content: $( '<p>Additional options here.</p>' ),
11645 * padded: true,
11646 * align: 'force-left'
11647 * }
11648 * } );
11649 * // Append the button to the DOM.
11650 * $( 'body' ).append( popupButton.$element );
11651 *
11652 * @class
11653 * @extends OO.ui.ButtonWidget
11654 * @mixins OO.ui.PopupElement
11655 *
11656 * @constructor
11657 * @param {Object} [config] Configuration options
11658 */
11659 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
11660 // Parent constructor
11661 OO.ui.PopupButtonWidget.super.call( this, config );
11662
11663 // Mixin constructors
11664 OO.ui.PopupElement.call( this, config );
11665
11666 // Events
11667 this.connect( this, { click: 'onAction' } );
11668
11669 // Initialization
11670 this.$element
11671 .addClass( 'oo-ui-popupButtonWidget' )
11672 .attr( 'aria-haspopup', 'true' )
11673 .append( this.popup.$element );
11674 };
11675
11676 /* Setup */
11677
11678 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
11679 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
11680
11681 /* Methods */
11682
11683 /**
11684 * Handle the button action being triggered.
11685 *
11686 * @private
11687 */
11688 OO.ui.PopupButtonWidget.prototype.onAction = function () {
11689 this.popup.toggle();
11690 };
11691
11692 /**
11693 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
11694 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
11695 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
11696 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
11697 * and {@link OO.ui.LabelElement labels}. Please see
11698 * the [OOjs UI documentation][1] on MediaWiki for more information.
11699 *
11700 * @example
11701 * // Toggle buttons in the 'off' and 'on' state.
11702 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
11703 * label: 'Toggle Button off'
11704 * } );
11705 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
11706 * label: 'Toggle Button on',
11707 * value: true
11708 * } );
11709 * // Append the buttons to the DOM.
11710 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
11711 *
11712 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
11713 *
11714 * @class
11715 * @extends OO.ui.ToggleWidget
11716 * @mixins OO.ui.ButtonElement
11717 * @mixins OO.ui.IconElement
11718 * @mixins OO.ui.IndicatorElement
11719 * @mixins OO.ui.LabelElement
11720 * @mixins OO.ui.TitledElement
11721 * @mixins OO.ui.FlaggedElement
11722 * @mixins OO.ui.TabIndexedElement
11723 *
11724 * @constructor
11725 * @param {Object} [config] Configuration options
11726 * @cfg {boolean} [value=false] The toggle button’s initial on/off
11727 * state. By default, the button is in the 'off' state.
11728 */
11729 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
11730 // Configuration initialization
11731 config = config || {};
11732
11733 // Parent constructor
11734 OO.ui.ToggleButtonWidget.super.call( this, config );
11735
11736 // Mixin constructors
11737 OO.ui.ButtonElement.call( this, config );
11738 OO.ui.IconElement.call( this, config );
11739 OO.ui.IndicatorElement.call( this, config );
11740 OO.ui.LabelElement.call( this, config );
11741 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
11742 OO.ui.FlaggedElement.call( this, config );
11743 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
11744
11745 // Events
11746 this.connect( this, { click: 'onAction' } );
11747
11748 // Initialization
11749 this.$button.append( this.$icon, this.$label, this.$indicator );
11750 this.$element
11751 .addClass( 'oo-ui-toggleButtonWidget' )
11752 .append( this.$button );
11753 };
11754
11755 /* Setup */
11756
11757 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
11758 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonElement );
11759 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.IconElement );
11760 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.IndicatorElement );
11761 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.LabelElement );
11762 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.TitledElement );
11763 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.FlaggedElement );
11764 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.TabIndexedElement );
11765
11766 /* Methods */
11767
11768 /**
11769 * Handle the button action being triggered.
11770 *
11771 * @private
11772 */
11773 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
11774 this.setValue( !this.value );
11775 };
11776
11777 /**
11778 * @inheritdoc
11779 */
11780 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
11781 value = !!value;
11782 if ( value !== this.value ) {
11783 // Might be called from parent constructor before ButtonElement constructor
11784 if ( this.$button ) {
11785 this.$button.attr( 'aria-pressed', value.toString() );
11786 }
11787 this.setActive( value );
11788 }
11789
11790 // Parent method
11791 OO.ui.ToggleButtonWidget.super.prototype.setValue.call( this, value );
11792
11793 return this;
11794 };
11795
11796 /**
11797 * @inheritdoc
11798 */
11799 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
11800 if ( this.$button ) {
11801 this.$button.removeAttr( 'aria-pressed' );
11802 }
11803 OO.ui.ButtonElement.prototype.setButtonElement.call( this, $button );
11804 this.$button.attr( 'aria-pressed', this.value.toString() );
11805 };
11806
11807 /**
11808 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
11809 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
11810 * users can interact with it.
11811 *
11812 * @example
11813 * // Example: A DropdownWidget with a menu that contains three options
11814 * var dropDown = new OO.ui.DropdownWidget( {
11815 * label: 'Dropdown menu: Select a menu option',
11816 * menu: {
11817 * items: [
11818 * new OO.ui.MenuOptionWidget( {
11819 * data: 'a',
11820 * label: 'First'
11821 * } ),
11822 * new OO.ui.MenuOptionWidget( {
11823 * data: 'b',
11824 * label: 'Second'
11825 * } ),
11826 * new OO.ui.MenuOptionWidget( {
11827 * data: 'c',
11828 * label: 'Third'
11829 * } )
11830 * ]
11831 * }
11832 * } );
11833 *
11834 * $( 'body' ).append( dropDown.$element );
11835 *
11836 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
11837 *
11838 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11839 *
11840 * @class
11841 * @extends OO.ui.Widget
11842 * @mixins OO.ui.IconElement
11843 * @mixins OO.ui.IndicatorElement
11844 * @mixins OO.ui.LabelElement
11845 * @mixins OO.ui.TitledElement
11846 * @mixins OO.ui.TabIndexedElement
11847 *
11848 * @constructor
11849 * @param {Object} [config] Configuration options
11850 * @cfg {Object} [menu] Configuration options to pass to menu widget
11851 */
11852 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
11853 // Configuration initialization
11854 config = $.extend( { indicator: 'down' }, config );
11855
11856 // Parent constructor
11857 OO.ui.DropdownWidget.super.call( this, config );
11858
11859 // Properties (must be set before TabIndexedElement constructor call)
11860 this.$handle = this.$( '<span>' );
11861
11862 // Mixin constructors
11863 OO.ui.IconElement.call( this, config );
11864 OO.ui.IndicatorElement.call( this, config );
11865 OO.ui.LabelElement.call( this, config );
11866 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11867 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11868
11869 // Properties
11870 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
11871
11872 // Events
11873 this.$handle.on( {
11874 click: this.onClick.bind( this ),
11875 keypress: this.onKeyPress.bind( this )
11876 } );
11877 this.menu.connect( this, { select: 'onMenuSelect' } );
11878
11879 // Initialization
11880 this.$handle
11881 .addClass( 'oo-ui-dropdownWidget-handle' )
11882 .append( this.$icon, this.$label, this.$indicator );
11883 this.$element
11884 .addClass( 'oo-ui-dropdownWidget' )
11885 .append( this.$handle, this.menu.$element );
11886 };
11887
11888 /* Setup */
11889
11890 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
11891 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
11892 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
11893 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
11894 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
11895 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
11896
11897 /* Methods */
11898
11899 /**
11900 * Get the menu.
11901 *
11902 * @return {OO.ui.MenuSelectWidget} Menu of widget
11903 */
11904 OO.ui.DropdownWidget.prototype.getMenu = function () {
11905 return this.menu;
11906 };
11907
11908 /**
11909 * Handles menu select events.
11910 *
11911 * @private
11912 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11913 */
11914 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
11915 var selectedLabel;
11916
11917 if ( !item ) {
11918 return;
11919 }
11920
11921 selectedLabel = item.getLabel();
11922
11923 // If the label is a DOM element, clone it, because setLabel will append() it
11924 if ( selectedLabel instanceof jQuery ) {
11925 selectedLabel = selectedLabel.clone();
11926 }
11927
11928 this.setLabel( selectedLabel );
11929 };
11930
11931 /**
11932 * Handle mouse click events.
11933 *
11934 * @private
11935 * @param {jQuery.Event} e Mouse click event
11936 */
11937 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
11938 if ( !this.isDisabled() && e.which === 1 ) {
11939 this.menu.toggle();
11940 }
11941 return false;
11942 };
11943
11944 /**
11945 * Handle key press events.
11946 *
11947 * @private
11948 * @param {jQuery.Event} e Key press event
11949 */
11950 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
11951 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
11952 this.menu.toggle();
11953 return false;
11954 }
11955 };
11956
11957 /**
11958 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
11959 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
11960 * for a list of icons included in the library.
11961 *
11962 * @example
11963 * // An icon widget with a label
11964 * var myIcon = new OO.ui.IconWidget( {
11965 * icon: 'help',
11966 * iconTitle: 'Help'
11967 * } );
11968 * // Create a label.
11969 * var iconLabel = new OO.ui.LabelWidget( {
11970 * label: 'Help'
11971 * } );
11972 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
11973 *
11974 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
11975 *
11976 * @class
11977 * @extends OO.ui.Widget
11978 * @mixins OO.ui.IconElement
11979 * @mixins OO.ui.TitledElement
11980 * @mixins OO.ui.FlaggedElement
11981 *
11982 * @constructor
11983 * @param {Object} [config] Configuration options
11984 */
11985 OO.ui.IconWidget = function OoUiIconWidget( config ) {
11986 // Configuration initialization
11987 config = config || {};
11988
11989 // Parent constructor
11990 OO.ui.IconWidget.super.call( this, config );
11991
11992 // Mixin constructors
11993 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
11994 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11995 OO.ui.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
11996
11997 // Initialization
11998 this.$element.addClass( 'oo-ui-iconWidget' );
11999 };
12000
12001 /* Setup */
12002
12003 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
12004 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
12005 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
12006 OO.mixinClass( OO.ui.IconWidget, OO.ui.FlaggedElement );
12007
12008 /* Static Properties */
12009
12010 OO.ui.IconWidget.static.tagName = 'span';
12011
12012 /**
12013 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
12014 * attention to the status of an item or to clarify the function of a control. For a list of
12015 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
12016 *
12017 * @example
12018 * // Example of an indicator widget
12019 * var indicator1 = new OO.ui.IndicatorWidget( {
12020 * indicator: 'alert'
12021 * } );
12022 *
12023 * // Create a fieldset layout to add a label
12024 * var fieldset = new OO.ui.FieldsetLayout();
12025 * fieldset.addItems( [
12026 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
12027 * ] );
12028 * $( 'body' ).append( fieldset.$element );
12029 *
12030 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
12031 *
12032 * @class
12033 * @extends OO.ui.Widget
12034 * @mixins OO.ui.IndicatorElement
12035 * @mixins OO.ui.TitledElement
12036 *
12037 * @constructor
12038 * @param {Object} [config] Configuration options
12039 */
12040 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
12041 // Configuration initialization
12042 config = config || {};
12043
12044 // Parent constructor
12045 OO.ui.IndicatorWidget.super.call( this, config );
12046
12047 // Mixin constructors
12048 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
12049 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
12050
12051 // Initialization
12052 this.$element.addClass( 'oo-ui-indicatorWidget' );
12053 };
12054
12055 /* Setup */
12056
12057 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
12058 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
12059 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
12060
12061 /* Static Properties */
12062
12063 OO.ui.IndicatorWidget.static.tagName = 'span';
12064
12065 /**
12066 * InputWidget is the base class for all input widgets, which
12067 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
12068 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
12069 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12070 *
12071 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12072 *
12073 * @abstract
12074 * @class
12075 * @extends OO.ui.Widget
12076 * @mixins OO.ui.FlaggedElement
12077 * @mixins OO.ui.TabIndexedElement
12078 *
12079 * @constructor
12080 * @param {Object} [config] Configuration options
12081 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
12082 * @cfg {string} [value=''] The value of the input.
12083 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
12084 * before it is accepted.
12085 */
12086 OO.ui.InputWidget = function OoUiInputWidget( config ) {
12087 // Configuration initialization
12088 config = config || {};
12089
12090 // Parent constructor
12091 OO.ui.InputWidget.super.call( this, config );
12092
12093 // Properties
12094 this.$input = this.getInputElement( config );
12095 this.value = '';
12096 this.inputFilter = config.inputFilter;
12097
12098 // Mixin constructors
12099 OO.ui.FlaggedElement.call( this, config );
12100 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
12101
12102 // Events
12103 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
12104
12105 // Initialization
12106 this.$input
12107 .attr( 'name', config.name )
12108 .prop( 'disabled', this.isDisabled() );
12109 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
12110 this.setValue( config.value );
12111 };
12112
12113 /* Setup */
12114
12115 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
12116 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
12117 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
12118
12119 /* Events */
12120
12121 /**
12122 * @event change
12123 *
12124 * A change event is emitted when the value of the input changes.
12125 *
12126 * @param {string} value
12127 */
12128
12129 /* Methods */
12130
12131 /**
12132 * Get input element.
12133 *
12134 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
12135 * different circumstances. The element must have a `value` property (like form elements).
12136 *
12137 * @private
12138 * @param {Object} config Configuration options
12139 * @return {jQuery} Input element
12140 */
12141 OO.ui.InputWidget.prototype.getInputElement = function () {
12142 return $( '<input>' );
12143 };
12144
12145 /**
12146 * Handle potentially value-changing events.
12147 *
12148 * @private
12149 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
12150 */
12151 OO.ui.InputWidget.prototype.onEdit = function () {
12152 var widget = this;
12153 if ( !this.isDisabled() ) {
12154 // Allow the stack to clear so the value will be updated
12155 setTimeout( function () {
12156 widget.setValue( widget.$input.val() );
12157 } );
12158 }
12159 };
12160
12161 /**
12162 * Get the value of the input.
12163 *
12164 * @return {string} Input value
12165 */
12166 OO.ui.InputWidget.prototype.getValue = function () {
12167 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
12168 // it, and we won't know unless they're kind enough to trigger a 'change' event.
12169 var value = this.$input.val();
12170 if ( this.value !== value ) {
12171 this.setValue( value );
12172 }
12173 return this.value;
12174 };
12175
12176 /**
12177 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
12178 *
12179 * @param {boolean} isRTL
12180 * Direction is right-to-left
12181 */
12182 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
12183 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
12184 };
12185
12186 /**
12187 * Set the value of the input.
12188 *
12189 * @param {string} value New value
12190 * @fires change
12191 * @chainable
12192 */
12193 OO.ui.InputWidget.prototype.setValue = function ( value ) {
12194 value = this.cleanUpValue( value );
12195 // Update the DOM if it has changed. Note that with cleanUpValue, it
12196 // is possible for the DOM value to change without this.value changing.
12197 if ( this.$input.val() !== value ) {
12198 this.$input.val( value );
12199 }
12200 if ( this.value !== value ) {
12201 this.value = value;
12202 this.emit( 'change', this.value );
12203 }
12204 return this;
12205 };
12206
12207 /**
12208 * Clean up incoming value.
12209 *
12210 * Ensures value is a string, and converts undefined and null to empty string.
12211 *
12212 * @private
12213 * @param {string} value Original value
12214 * @return {string} Cleaned up value
12215 */
12216 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
12217 if ( value === undefined || value === null ) {
12218 return '';
12219 } else if ( this.inputFilter ) {
12220 return this.inputFilter( String( value ) );
12221 } else {
12222 return String( value );
12223 }
12224 };
12225
12226 /**
12227 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
12228 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
12229 * called directly.
12230 */
12231 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
12232 if ( !this.isDisabled() ) {
12233 if ( this.$input.is( ':checkbox, :radio' ) ) {
12234 this.$input.click();
12235 }
12236 if ( this.$input.is( ':input' ) ) {
12237 this.$input[ 0 ].focus();
12238 }
12239 }
12240 };
12241
12242 /**
12243 * @inheritdoc
12244 */
12245 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
12246 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
12247 if ( this.$input ) {
12248 this.$input.prop( 'disabled', this.isDisabled() );
12249 }
12250 return this;
12251 };
12252
12253 /**
12254 * Focus the input.
12255 *
12256 * @chainable
12257 */
12258 OO.ui.InputWidget.prototype.focus = function () {
12259 this.$input[ 0 ].focus();
12260 return this;
12261 };
12262
12263 /**
12264 * Blur the input.
12265 *
12266 * @chainable
12267 */
12268 OO.ui.InputWidget.prototype.blur = function () {
12269 this.$input[ 0 ].blur();
12270 return this;
12271 };
12272
12273 /**
12274 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
12275 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
12276 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
12277 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
12278 * [OOjs UI documentation on MediaWiki] [1] for more information.
12279 *
12280 * @example
12281 * // A ButtonInputWidget rendered as an HTML button, the default.
12282 * var button = new OO.ui.ButtonInputWidget( {
12283 * label: 'Input button',
12284 * icon: 'check',
12285 * value: 'check'
12286 * } );
12287 * $( 'body' ).append( button.$element );
12288 *
12289 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
12290 *
12291 * @class
12292 * @extends OO.ui.InputWidget
12293 * @mixins OO.ui.ButtonElement
12294 * @mixins OO.ui.IconElement
12295 * @mixins OO.ui.IndicatorElement
12296 * @mixins OO.ui.LabelElement
12297 * @mixins OO.ui.TitledElement
12298 *
12299 * @constructor
12300 * @param {Object} [config] Configuration options
12301 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
12302 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
12303 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
12304 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
12305 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
12306 */
12307 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
12308 // Configuration initialization
12309 config = $.extend( { type: 'button', useInputTag: false }, config );
12310
12311 // Properties (must be set before parent constructor, which calls #setValue)
12312 this.useInputTag = config.useInputTag;
12313
12314 // Parent constructor
12315 OO.ui.ButtonInputWidget.super.call( this, config );
12316
12317 // Mixin constructors
12318 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
12319 OO.ui.IconElement.call( this, config );
12320 OO.ui.IndicatorElement.call( this, config );
12321 OO.ui.LabelElement.call( this, config );
12322 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
12323
12324 // Initialization
12325 if ( !config.useInputTag ) {
12326 this.$input.append( this.$icon, this.$label, this.$indicator );
12327 }
12328 this.$element.addClass( 'oo-ui-buttonInputWidget' );
12329 };
12330
12331 /* Setup */
12332
12333 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
12334 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
12335 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
12336 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
12337 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
12338 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
12339
12340 /* Methods */
12341
12342 /**
12343 * @inheritdoc
12344 * @private
12345 */
12346 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
12347 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
12348 return $( html );
12349 };
12350
12351 /**
12352 * Set label value.
12353 *
12354 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
12355 *
12356 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
12357 * text, or `null` for no label
12358 * @chainable
12359 */
12360 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
12361 OO.ui.LabelElement.prototype.setLabel.call( this, label );
12362
12363 if ( this.useInputTag ) {
12364 if ( typeof label === 'function' ) {
12365 label = OO.ui.resolveMsg( label );
12366 }
12367 if ( label instanceof jQuery ) {
12368 label = label.text();
12369 }
12370 if ( !label ) {
12371 label = '';
12372 }
12373 this.$input.val( label );
12374 }
12375
12376 return this;
12377 };
12378
12379 /**
12380 * Set the value of the input.
12381 *
12382 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
12383 * they do not support {@link #value values}.
12384 *
12385 * @param {string} value New value
12386 * @chainable
12387 */
12388 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
12389 if ( !this.useInputTag ) {
12390 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
12391 }
12392 return this;
12393 };
12394
12395 /**
12396 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
12397 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
12398 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
12399 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
12400 *
12401 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12402 *
12403 * @example
12404 * // An example of selected, unselected, and disabled checkbox inputs
12405 * var checkbox1=new OO.ui.CheckboxInputWidget( {
12406 * value: 'a',
12407 * selected: true
12408 * } );
12409 * var checkbox2=new OO.ui.CheckboxInputWidget( {
12410 * value: 'b'
12411 * } );
12412 * var checkbox3=new OO.ui.CheckboxInputWidget( {
12413 * value:'c',
12414 * disabled: true
12415 * } );
12416 * // Create a fieldset layout with fields for each checkbox.
12417 * var fieldset = new OO.ui.FieldsetLayout( {
12418 * label: 'Checkboxes'
12419 * } );
12420 * fieldset.addItems( [
12421 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
12422 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
12423 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
12424 * ] );
12425 * $( 'body' ).append( fieldset.$element );
12426 *
12427 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12428 *
12429 * @class
12430 * @extends OO.ui.InputWidget
12431 *
12432 * @constructor
12433 * @param {Object} [config] Configuration options
12434 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
12435 */
12436 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
12437 // Configuration initialization
12438 config = config || {};
12439
12440 // Parent constructor
12441 OO.ui.CheckboxInputWidget.super.call( this, config );
12442
12443 // Initialization
12444 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
12445 this.setSelected( config.selected !== undefined ? config.selected : false );
12446 };
12447
12448 /* Setup */
12449
12450 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
12451
12452 /* Methods */
12453
12454 /**
12455 * @inheritdoc
12456 * @private
12457 */
12458 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
12459 return $( '<input type="checkbox" />' );
12460 };
12461
12462 /**
12463 * @inheritdoc
12464 */
12465 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
12466 var widget = this;
12467 if ( !this.isDisabled() ) {
12468 // Allow the stack to clear so the value will be updated
12469 setTimeout( function () {
12470 widget.setSelected( widget.$input.prop( 'checked' ) );
12471 } );
12472 }
12473 };
12474
12475 /**
12476 * Set selection state of this checkbox.
12477 *
12478 * @param {boolean} state `true` for selected
12479 * @chainable
12480 */
12481 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
12482 state = !!state;
12483 if ( this.selected !== state ) {
12484 this.selected = state;
12485 this.$input.prop( 'checked', this.selected );
12486 this.emit( 'change', this.selected );
12487 }
12488 return this;
12489 };
12490
12491 /**
12492 * Check if this checkbox is selected.
12493 *
12494 * @return {boolean} Checkbox is selected
12495 */
12496 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
12497 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
12498 // it, and we won't know unless they're kind enough to trigger a 'change' event.
12499 var selected = this.$input.prop( 'checked' );
12500 if ( this.selected !== selected ) {
12501 this.setSelected( selected );
12502 }
12503 return this.selected;
12504 };
12505
12506 /**
12507 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
12508 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
12509 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
12510 * more information about input widgets.
12511 *
12512 * @example
12513 * // Example: A DropdownInputWidget with three options
12514 * var dropDown = new OO.ui.DropdownInputWidget( {
12515 * label: 'Dropdown menu: Select a menu option',
12516 * options: [
12517 * { data: 'a', label: 'First' } ,
12518 * { data: 'b', label: 'Second'} ,
12519 * { data: 'c', label: 'Third' }
12520 * ]
12521 * } );
12522 * $( 'body' ).append( dropDown.$element );
12523 *
12524 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12525 *
12526 * @class
12527 * @extends OO.ui.InputWidget
12528 *
12529 * @constructor
12530 * @param {Object} [config] Configuration options
12531 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
12532 */
12533 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
12534 // Configuration initialization
12535 config = config || {};
12536
12537 // Properties (must be done before parent constructor which calls #setDisabled)
12538 this.dropdownWidget = new OO.ui.DropdownWidget();
12539
12540 // Parent constructor
12541 OO.ui.DropdownInputWidget.super.call( this, config );
12542
12543 // Events
12544 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
12545
12546 // Initialization
12547 this.setOptions( config.options || [] );
12548 this.$element
12549 .addClass( 'oo-ui-dropdownInputWidget' )
12550 .append( this.dropdownWidget.$element );
12551 };
12552
12553 /* Setup */
12554
12555 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
12556
12557 /* Methods */
12558
12559 /**
12560 * @inheritdoc
12561 * @private
12562 */
12563 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
12564 return $( '<input type="hidden">' );
12565 };
12566
12567 /**
12568 * Handles menu select events.
12569 *
12570 * @private
12571 * @param {OO.ui.MenuOptionWidget} item Selected menu item
12572 */
12573 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
12574 this.setValue( item.getData() );
12575 };
12576
12577 /**
12578 * @inheritdoc
12579 */
12580 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
12581 this.dropdownWidget.getMenu().selectItemByData( value );
12582 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
12583 return this;
12584 };
12585
12586 /**
12587 * @inheritdoc
12588 */
12589 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
12590 this.dropdownWidget.setDisabled( state );
12591 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
12592 return this;
12593 };
12594
12595 /**
12596 * Set the options available for this input.
12597 *
12598 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
12599 * @chainable
12600 */
12601 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
12602 var value = this.getValue();
12603
12604 // Rebuild the dropdown menu
12605 this.dropdownWidget.getMenu()
12606 .clearItems()
12607 .addItems( options.map( function ( opt ) {
12608 return new OO.ui.MenuOptionWidget( {
12609 data: opt.data,
12610 label: opt.label !== undefined ? opt.label : opt.data
12611 } );
12612 } ) );
12613
12614 // Restore the previous value, or reset to something sensible
12615 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
12616 // Previous value is still available, ensure consistency with the dropdown
12617 this.setValue( value );
12618 } else {
12619 // No longer valid, reset
12620 if ( options.length ) {
12621 this.setValue( options[ 0 ].data );
12622 }
12623 }
12624
12625 return this;
12626 };
12627
12628 /**
12629 * @inheritdoc
12630 */
12631 OO.ui.DropdownInputWidget.prototype.focus = function () {
12632 this.dropdownWidget.getMenu().toggle( true );
12633 return this;
12634 };
12635
12636 /**
12637 * @inheritdoc
12638 */
12639 OO.ui.DropdownInputWidget.prototype.blur = function () {
12640 this.dropdownWidget.getMenu().toggle( false );
12641 return this;
12642 };
12643
12644 /**
12645 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
12646 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
12647 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
12648 * please see the [OOjs UI documentation on MediaWiki][1].
12649 *
12650 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12651 *
12652 * @example
12653 * // An example of selected, unselected, and disabled radio inputs
12654 * var radio1 = new OO.ui.RadioInputWidget( {
12655 * value: 'a',
12656 * selected: true
12657 * } );
12658 * var radio2 = new OO.ui.RadioInputWidget( {
12659 * value: 'b'
12660 * } );
12661 * var radio3 = new OO.ui.RadioInputWidget( {
12662 * value: 'c',
12663 * disabled: true
12664 * } );
12665 * // Create a fieldset layout with fields for each radio button.
12666 * var fieldset = new OO.ui.FieldsetLayout( {
12667 * label: 'Radio inputs'
12668 * } );
12669 * fieldset.addItems( [
12670 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
12671 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
12672 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
12673 * ] );
12674 * $( 'body' ).append( fieldset.$element );
12675 *
12676 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12677 *
12678 * @class
12679 * @extends OO.ui.InputWidget
12680 *
12681 * @constructor
12682 * @param {Object} [config] Configuration options
12683 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
12684 */
12685 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
12686 // Configuration initialization
12687 config = config || {};
12688
12689 // Parent constructor
12690 OO.ui.RadioInputWidget.super.call( this, config );
12691
12692 // Initialization
12693 this.$element.addClass( 'oo-ui-radioInputWidget' );
12694 this.setSelected( config.selected !== undefined ? config.selected : false );
12695 };
12696
12697 /* Setup */
12698
12699 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
12700
12701 /* Methods */
12702
12703 /**
12704 * @inheritdoc
12705 * @private
12706 */
12707 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
12708 return $( '<input type="radio" />' );
12709 };
12710
12711 /**
12712 * @inheritdoc
12713 */
12714 OO.ui.RadioInputWidget.prototype.onEdit = function () {
12715 // RadioInputWidget doesn't track its state.
12716 };
12717
12718 /**
12719 * Set selection state of this radio button.
12720 *
12721 * @param {boolean} state `true` for selected
12722 * @chainable
12723 */
12724 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
12725 // RadioInputWidget doesn't track its state.
12726 this.$input.prop( 'checked', state );
12727 return this;
12728 };
12729
12730 /**
12731 * Check if this radio button is selected.
12732 *
12733 * @return {boolean} Radio is selected
12734 */
12735 OO.ui.RadioInputWidget.prototype.isSelected = function () {
12736 return this.$input.prop( 'checked' );
12737 };
12738
12739 /**
12740 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
12741 * size of the field as well as its presentation. In addition, these widgets can be configured
12742 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
12743 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
12744 * which modifies incoming values rather than validating them.
12745 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
12746 *
12747 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
12748 *
12749 * @example
12750 * // Example of a text input widget
12751 * var textInput = new OO.ui.TextInputWidget( {
12752 * value: 'Text input'
12753 * } )
12754 * $( 'body' ).append( textInput.$element );
12755 *
12756 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
12757 *
12758 * @class
12759 * @extends OO.ui.InputWidget
12760 * @mixins OO.ui.IconElement
12761 * @mixins OO.ui.IndicatorElement
12762 * @mixins OO.ui.PendingElement
12763 * @mixins OO.ui.LabelElement
12764 *
12765 * @constructor
12766 * @param {Object} [config] Configuration options
12767 * @cfg {string} [type='text'] The value of the HTML `type` attribute
12768 * @cfg {string} [placeholder] Placeholder text
12769 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
12770 * instruct the browser to focus this widget.
12771 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
12772 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
12773 * @cfg {boolean} [multiline=false] Allow multiple lines of text
12774 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
12775 * Use the #maxRows config to specify a maximum number of displayed rows.
12776 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
12777 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
12778 * the value or placeholder text: `'before'` or `'after'`
12779 * @cfg {boolean} [required=false] Mark the field as required
12780 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
12781 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
12782 * (the value must contain only numbers); when RegExp, a regular expression that must match the
12783 * value for it to be considered valid; when Function, a function receiving the value as parameter
12784 * that must return true, or promise resolving to true, for it to be considered valid.
12785 */
12786 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
12787 // Configuration initialization
12788 config = $.extend( {
12789 type: 'text',
12790 labelPosition: 'after',
12791 maxRows: 10
12792 }, config );
12793
12794 // Parent constructor
12795 OO.ui.TextInputWidget.super.call( this, config );
12796
12797 // Mixin constructors
12798 OO.ui.IconElement.call( this, config );
12799 OO.ui.IndicatorElement.call( this, config );
12800 OO.ui.PendingElement.call( this, config );
12801 OO.ui.LabelElement.call( this, config );
12802
12803 // Properties
12804 this.readOnly = false;
12805 this.multiline = !!config.multiline;
12806 this.autosize = !!config.autosize;
12807 this.maxRows = config.maxRows;
12808 this.validate = null;
12809
12810 // Clone for resizing
12811 if ( this.autosize ) {
12812 this.$clone = this.$input
12813 .clone()
12814 .insertAfter( this.$input )
12815 .attr( 'aria-hidden', 'true' )
12816 .addClass( 'oo-ui-element-hidden' );
12817 }
12818
12819 this.setValidation( config.validate );
12820 this.setLabelPosition( config.labelPosition );
12821
12822 // Events
12823 this.$input.on( {
12824 keypress: this.onKeyPress.bind( this ),
12825 blur: this.onBlur.bind( this )
12826 } );
12827 this.$input.one( {
12828 focus: this.onElementAttach.bind( this )
12829 } );
12830 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
12831 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
12832 this.on( 'labelChange', this.updatePosition.bind( this ) );
12833 this.connect( this, { change: 'onChange' } );
12834
12835 // Initialization
12836 this.$element
12837 .addClass( 'oo-ui-textInputWidget' )
12838 .append( this.$icon, this.$indicator );
12839 this.setReadOnly( !!config.readOnly );
12840 if ( config.placeholder ) {
12841 this.$input.attr( 'placeholder', config.placeholder );
12842 }
12843 if ( config.maxLength !== undefined ) {
12844 this.$input.attr( 'maxlength', config.maxLength );
12845 }
12846 if ( config.autofocus ) {
12847 this.$input.attr( 'autofocus', 'autofocus' );
12848 }
12849 if ( config.required ) {
12850 this.$input.attr( 'required', 'required' );
12851 this.$input.attr( 'aria-required', 'true' );
12852 }
12853 if ( this.label || config.autosize ) {
12854 this.installParentChangeDetector();
12855 }
12856 };
12857
12858 /* Setup */
12859
12860 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
12861 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
12862 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
12863 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
12864 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
12865
12866 /* Static properties */
12867
12868 OO.ui.TextInputWidget.static.validationPatterns = {
12869 'non-empty': /.+/,
12870 integer: /^\d+$/
12871 };
12872
12873 /* Events */
12874
12875 /**
12876 * An `enter` event is emitted when the user presses 'enter' inside the text box.
12877 *
12878 * Not emitted if the input is multiline.
12879 *
12880 * @event enter
12881 */
12882
12883 /* Methods */
12884
12885 /**
12886 * Handle icon mouse down events.
12887 *
12888 * @private
12889 * @param {jQuery.Event} e Mouse down event
12890 * @fires icon
12891 */
12892 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
12893 if ( e.which === 1 ) {
12894 this.$input[ 0 ].focus();
12895 return false;
12896 }
12897 };
12898
12899 /**
12900 * Handle indicator mouse down events.
12901 *
12902 * @private
12903 * @param {jQuery.Event} e Mouse down event
12904 * @fires indicator
12905 */
12906 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
12907 if ( e.which === 1 ) {
12908 this.$input[ 0 ].focus();
12909 return false;
12910 }
12911 };
12912
12913 /**
12914 * Handle key press events.
12915 *
12916 * @private
12917 * @param {jQuery.Event} e Key press event
12918 * @fires enter If enter key is pressed and input is not multiline
12919 */
12920 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
12921 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
12922 this.emit( 'enter', e );
12923 }
12924 };
12925
12926 /**
12927 * Handle blur events.
12928 *
12929 * @private
12930 * @param {jQuery.Event} e Blur event
12931 */
12932 OO.ui.TextInputWidget.prototype.onBlur = function () {
12933 this.setValidityFlag();
12934 };
12935
12936 /**
12937 * Handle element attach events.
12938 *
12939 * @private
12940 * @param {jQuery.Event} e Element attach event
12941 */
12942 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
12943 // Any previously calculated size is now probably invalid if we reattached elsewhere
12944 this.valCache = null;
12945 this.adjustSize();
12946 this.positionLabel();
12947 };
12948
12949 /**
12950 * Handle change events.
12951 *
12952 * @param {string} value
12953 * @private
12954 */
12955 OO.ui.TextInputWidget.prototype.onChange = function () {
12956 this.setValidityFlag();
12957 this.adjustSize();
12958 };
12959
12960 /**
12961 * Check if the input is {@link #readOnly read-only}.
12962 *
12963 * @return {boolean}
12964 */
12965 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
12966 return this.readOnly;
12967 };
12968
12969 /**
12970 * Set the {@link #readOnly read-only} state of the input.
12971 *
12972 * @param {boolean} state Make input read-only
12973 * @chainable
12974 */
12975 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
12976 this.readOnly = !!state;
12977 this.$input.prop( 'readOnly', this.readOnly );
12978 return this;
12979 };
12980
12981 /**
12982 * Support function for making #onElementAttach work across browsers.
12983 *
12984 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
12985 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
12986 *
12987 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
12988 * first time that the element gets attached to the documented.
12989 */
12990 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
12991 var mutationObserver, onRemove, topmostNode, fakeParentNode,
12992 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
12993 widget = this;
12994
12995 if ( MutationObserver ) {
12996 // The new way. If only it wasn't so ugly.
12997
12998 if ( this.$element.closest( 'html' ).length ) {
12999 // Widget is attached already, do nothing. This breaks the functionality of this function when
13000 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
13001 // would require observation of the whole document, which would hurt performance of other,
13002 // more important code.
13003 return;
13004 }
13005
13006 // Find topmost node in the tree
13007 topmostNode = this.$element[0];
13008 while ( topmostNode.parentNode ) {
13009 topmostNode = topmostNode.parentNode;
13010 }
13011
13012 // We have no way to detect the $element being attached somewhere without observing the entire
13013 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
13014 // parent node of $element, and instead detect when $element is removed from it (and thus
13015 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
13016 // doesn't get attached, we end up back here and create the parent.
13017
13018 mutationObserver = new MutationObserver( function ( mutations ) {
13019 var i, j, removedNodes;
13020 for ( i = 0; i < mutations.length; i++ ) {
13021 removedNodes = mutations[ i ].removedNodes;
13022 for ( j = 0; j < removedNodes.length; j++ ) {
13023 if ( removedNodes[ j ] === topmostNode ) {
13024 setTimeout( onRemove, 0 );
13025 return;
13026 }
13027 }
13028 }
13029 } );
13030
13031 onRemove = function () {
13032 // If the node was attached somewhere else, report it
13033 if ( widget.$element.closest( 'html' ).length ) {
13034 widget.onElementAttach();
13035 }
13036 mutationObserver.disconnect();
13037 widget.installParentChangeDetector();
13038 };
13039
13040 // Create a fake parent and observe it
13041 fakeParentNode = $( '<div>' ).append( this.$element )[0];
13042 mutationObserver.observe( fakeParentNode, { childList: true } );
13043 } else {
13044 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
13045 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
13046 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
13047 }
13048 };
13049
13050 /**
13051 * Automatically adjust the size of the text input.
13052 *
13053 * This only affects #multiline inputs that are {@link #autosize autosized}.
13054 *
13055 * @chainable
13056 */
13057 OO.ui.TextInputWidget.prototype.adjustSize = function () {
13058 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
13059
13060 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
13061 this.$clone
13062 .val( this.$input.val() )
13063 .attr( 'rows', '' )
13064 // Set inline height property to 0 to measure scroll height
13065 .css( 'height', 0 );
13066
13067 this.$clone.removeClass( 'oo-ui-element-hidden' );
13068
13069 this.valCache = this.$input.val();
13070
13071 scrollHeight = this.$clone[ 0 ].scrollHeight;
13072
13073 // Remove inline height property to measure natural heights
13074 this.$clone.css( 'height', '' );
13075 innerHeight = this.$clone.innerHeight();
13076 outerHeight = this.$clone.outerHeight();
13077
13078 // Measure max rows height
13079 this.$clone
13080 .attr( 'rows', this.maxRows )
13081 .css( 'height', 'auto' )
13082 .val( '' );
13083 maxInnerHeight = this.$clone.innerHeight();
13084
13085 // Difference between reported innerHeight and scrollHeight with no scrollbars present
13086 // Equals 1 on Blink-based browsers and 0 everywhere else
13087 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
13088 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
13089
13090 this.$clone.addClass( 'oo-ui-element-hidden' );
13091
13092 // Only apply inline height when expansion beyond natural height is needed
13093 if ( idealHeight > innerHeight ) {
13094 // Use the difference between the inner and outer height as a buffer
13095 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
13096 } else {
13097 this.$input.css( 'height', '' );
13098 }
13099 }
13100 return this;
13101 };
13102
13103 /**
13104 * @inheritdoc
13105 * @private
13106 */
13107 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
13108 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
13109 };
13110
13111 /**
13112 * Check if the input supports multiple lines.
13113 *
13114 * @return {boolean}
13115 */
13116 OO.ui.TextInputWidget.prototype.isMultiline = function () {
13117 return !!this.multiline;
13118 };
13119
13120 /**
13121 * Check if the input automatically adjusts its size.
13122 *
13123 * @return {boolean}
13124 */
13125 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
13126 return !!this.autosize;
13127 };
13128
13129 /**
13130 * Select the entire text of the input.
13131 *
13132 * @chainable
13133 */
13134 OO.ui.TextInputWidget.prototype.select = function () {
13135 this.$input.select();
13136 return this;
13137 };
13138
13139 /**
13140 * Set the validation pattern.
13141 *
13142 * The validation pattern is either a regular expression, a function, or the symbolic name of a
13143 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
13144 * value must contain only numbers).
13145 *
13146 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
13147 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
13148 */
13149 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
13150 if ( validate instanceof RegExp || validate instanceof Function ) {
13151 this.validate = validate;
13152 } else {
13153 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
13154 }
13155 };
13156
13157 /**
13158 * Sets the 'invalid' flag appropriately.
13159 *
13160 * @param {boolean} [isValid] Optionally override validation result
13161 */
13162 OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) {
13163 var widget = this,
13164 setFlag = function ( valid ) {
13165 if ( !valid ) {
13166 widget.$input.attr( 'aria-invalid', 'true' );
13167 } else {
13168 widget.$input.removeAttr( 'aria-invalid' );
13169 }
13170 widget.setFlags( { invalid: !valid } );
13171 };
13172
13173 if ( isValid !== undefined ) {
13174 setFlag( isValid );
13175 } else {
13176 this.isValid().done( setFlag );
13177 }
13178 };
13179
13180 /**
13181 * Check if a value is valid.
13182 *
13183 * This method returns a promise that resolves with a boolean `true` if the current value is
13184 * considered valid according to the supplied {@link #validate validation pattern}.
13185 *
13186 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
13187 */
13188 OO.ui.TextInputWidget.prototype.isValid = function () {
13189 if ( this.validate instanceof Function ) {
13190 var result = this.validate( this.getValue() );
13191 if ( $.isFunction( result.promise ) ) {
13192 return result.promise();
13193 } else {
13194 return $.Deferred().resolve( !!result ).promise();
13195 }
13196 } else {
13197 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
13198 }
13199 };
13200
13201 /**
13202 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
13203 *
13204 * @param {string} labelPosition Label position, 'before' or 'after'
13205 * @chainable
13206 */
13207 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
13208 this.labelPosition = labelPosition;
13209 this.updatePosition();
13210 return this;
13211 };
13212
13213 /**
13214 * Deprecated alias of #setLabelPosition
13215 *
13216 * @deprecated Use setLabelPosition instead.
13217 */
13218 OO.ui.TextInputWidget.prototype.setPosition =
13219 OO.ui.TextInputWidget.prototype.setLabelPosition;
13220
13221 /**
13222 * Update the position of the inline label.
13223 *
13224 * This method is called by #setLabelPosition, and can also be called on its own if
13225 * something causes the label to be mispositioned.
13226 *
13227 *
13228 * @chainable
13229 */
13230 OO.ui.TextInputWidget.prototype.updatePosition = function () {
13231 var after = this.labelPosition === 'after';
13232
13233 this.$element
13234 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
13235 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
13236
13237 if ( this.label ) {
13238 this.positionLabel();
13239 }
13240
13241 return this;
13242 };
13243
13244 /**
13245 * Position the label by setting the correct padding on the input.
13246 *
13247 * @private
13248 * @chainable
13249 */
13250 OO.ui.TextInputWidget.prototype.positionLabel = function () {
13251 // Clear old values
13252 this.$input
13253 // Clear old values if present
13254 .css( {
13255 'padding-right': '',
13256 'padding-left': ''
13257 } );
13258
13259 if ( this.label ) {
13260 this.$element.append( this.$label );
13261 } else {
13262 this.$label.detach();
13263 return;
13264 }
13265
13266 var after = this.labelPosition === 'after',
13267 rtl = this.$element.css( 'direction' ) === 'rtl',
13268 property = after === rtl ? 'padding-left' : 'padding-right';
13269
13270 this.$input.css( property, this.$label.outerWidth( true ) );
13271
13272 return this;
13273 };
13274
13275 /**
13276 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
13277 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
13278 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
13279 *
13280 * - by typing a value in the text input field. If the value exactly matches the value of a menu
13281 * option, that option will appear to be selected.
13282 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
13283 * input field.
13284 *
13285 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13286 *
13287 * @example
13288 * // Example: A ComboBoxWidget.
13289 * var comboBox = new OO.ui.ComboBoxWidget( {
13290 * label: 'ComboBoxWidget',
13291 * input: { value: 'Option One' },
13292 * menu: {
13293 * items: [
13294 * new OO.ui.MenuOptionWidget( {
13295 * data: 'Option 1',
13296 * label: 'Option One'
13297 * } ),
13298 * new OO.ui.MenuOptionWidget( {
13299 * data: 'Option 2',
13300 * label: 'Option Two'
13301 * } ),
13302 * new OO.ui.MenuOptionWidget( {
13303 * data: 'Option 3',
13304 * label: 'Option Three'
13305 * } ),
13306 * new OO.ui.MenuOptionWidget( {
13307 * data: 'Option 4',
13308 * label: 'Option Four'
13309 * } ),
13310 * new OO.ui.MenuOptionWidget( {
13311 * data: 'Option 5',
13312 * label: 'Option Five'
13313 * } )
13314 * ]
13315 * }
13316 * } );
13317 * $( 'body' ).append( comboBox.$element );
13318 *
13319 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13320 *
13321 * @class
13322 * @extends OO.ui.Widget
13323 * @mixins OO.ui.TabIndexedElement
13324 *
13325 * @constructor
13326 * @param {Object} [config] Configuration options
13327 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13328 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
13329 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13330 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13331 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13332 */
13333 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
13334 // Configuration initialization
13335 config = config || {};
13336
13337 // Parent constructor
13338 OO.ui.ComboBoxWidget.super.call( this, config );
13339
13340 // Properties (must be set before TabIndexedElement constructor call)
13341 this.$indicator = this.$( '<span>' );
13342
13343 // Mixin constructors
13344 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
13345
13346 // Properties
13347 this.$overlay = config.$overlay || this.$element;
13348 this.input = new OO.ui.TextInputWidget( $.extend(
13349 {
13350 indicator: 'down',
13351 $indicator: this.$indicator,
13352 disabled: this.isDisabled()
13353 },
13354 config.input
13355 ) );
13356 this.input.$input.eq( 0 ).attr( {
13357 role: 'combobox',
13358 'aria-autocomplete': 'list'
13359 } );
13360 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
13361 {
13362 widget: this,
13363 input: this.input,
13364 disabled: this.isDisabled()
13365 },
13366 config.menu
13367 ) );
13368
13369 // Events
13370 this.$indicator.on( {
13371 click: this.onClick.bind( this ),
13372 keypress: this.onKeyPress.bind( this )
13373 } );
13374 this.input.connect( this, {
13375 change: 'onInputChange',
13376 enter: 'onInputEnter'
13377 } );
13378 this.menu.connect( this, {
13379 choose: 'onMenuChoose',
13380 add: 'onMenuItemsChange',
13381 remove: 'onMenuItemsChange'
13382 } );
13383
13384 // Initialization
13385 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
13386 this.$overlay.append( this.menu.$element );
13387 this.onMenuItemsChange();
13388 };
13389
13390 /* Setup */
13391
13392 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
13393 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
13394
13395 /* Methods */
13396
13397 /**
13398 * Get the combobox's menu.
13399 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
13400 */
13401 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
13402 return this.menu;
13403 };
13404
13405 /**
13406 * Handle input change events.
13407 *
13408 * @private
13409 * @param {string} value New value
13410 */
13411 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
13412 var match = this.menu.getItemFromData( value );
13413
13414 this.menu.selectItem( match );
13415 if ( this.menu.getHighlightedItem() ) {
13416 this.menu.highlightItem( match );
13417 }
13418
13419 if ( !this.isDisabled() ) {
13420 this.menu.toggle( true );
13421 }
13422 };
13423
13424 /**
13425 * Handle mouse click events.
13426 *
13427 *
13428 * @private
13429 * @param {jQuery.Event} e Mouse click event
13430 */
13431 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
13432 if ( !this.isDisabled() && e.which === 1 ) {
13433 this.menu.toggle();
13434 this.input.$input[ 0 ].focus();
13435 }
13436 return false;
13437 };
13438
13439 /**
13440 * Handle key press events.
13441 *
13442 *
13443 * @private
13444 * @param {jQuery.Event} e Key press event
13445 */
13446 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
13447 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
13448 this.menu.toggle();
13449 this.input.$input[ 0 ].focus();
13450 return false;
13451 }
13452 };
13453
13454 /**
13455 * Handle input enter events.
13456 *
13457 * @private
13458 */
13459 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
13460 if ( !this.isDisabled() ) {
13461 this.menu.toggle( false );
13462 }
13463 };
13464
13465 /**
13466 * Handle menu choose events.
13467 *
13468 * @private
13469 * @param {OO.ui.OptionWidget} item Chosen item
13470 */
13471 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
13472 this.input.setValue( item.getData() );
13473 };
13474
13475 /**
13476 * Handle menu item change events.
13477 *
13478 * @private
13479 */
13480 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
13481 var match = this.menu.getItemFromData( this.input.getValue() );
13482 this.menu.selectItem( match );
13483 if ( this.menu.getHighlightedItem() ) {
13484 this.menu.highlightItem( match );
13485 }
13486 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
13487 };
13488
13489 /**
13490 * @inheritdoc
13491 */
13492 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
13493 // Parent method
13494 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
13495
13496 if ( this.input ) {
13497 this.input.setDisabled( this.isDisabled() );
13498 }
13499 if ( this.menu ) {
13500 this.menu.setDisabled( this.isDisabled() );
13501 }
13502
13503 return this;
13504 };
13505
13506 /**
13507 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
13508 * be configured with a `label` option that is set to a string, a label node, or a function:
13509 *
13510 * - String: a plaintext string
13511 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
13512 * label that includes a link or special styling, such as a gray color or additional graphical elements.
13513 * - Function: a function that will produce a string in the future. Functions are used
13514 * in cases where the value of the label is not currently defined.
13515 *
13516 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
13517 * will come into focus when the label is clicked.
13518 *
13519 * @example
13520 * // Examples of LabelWidgets
13521 * var label1 = new OO.ui.LabelWidget( {
13522 * label: 'plaintext label'
13523 * } );
13524 * var label2 = new OO.ui.LabelWidget( {
13525 * label: $( '<a href="default.html">jQuery label</a>' )
13526 * } );
13527 * // Create a fieldset layout with fields for each example
13528 * var fieldset = new OO.ui.FieldsetLayout();
13529 * fieldset.addItems( [
13530 * new OO.ui.FieldLayout( label1 ),
13531 * new OO.ui.FieldLayout( label2 )
13532 * ] );
13533 * $( 'body' ).append( fieldset.$element );
13534 *
13535 *
13536 * @class
13537 * @extends OO.ui.Widget
13538 * @mixins OO.ui.LabelElement
13539 *
13540 * @constructor
13541 * @param {Object} [config] Configuration options
13542 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
13543 * Clicking the label will focus the specified input field.
13544 */
13545 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
13546 // Configuration initialization
13547 config = config || {};
13548
13549 // Parent constructor
13550 OO.ui.LabelWidget.super.call( this, config );
13551
13552 // Mixin constructors
13553 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
13554 OO.ui.TitledElement.call( this, config );
13555
13556 // Properties
13557 this.input = config.input;
13558
13559 // Events
13560 if ( this.input instanceof OO.ui.InputWidget ) {
13561 this.$element.on( 'click', this.onClick.bind( this ) );
13562 }
13563
13564 // Initialization
13565 this.$element.addClass( 'oo-ui-labelWidget' );
13566 };
13567
13568 /* Setup */
13569
13570 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
13571 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
13572 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
13573
13574 /* Static Properties */
13575
13576 OO.ui.LabelWidget.static.tagName = 'span';
13577
13578 /* Methods */
13579
13580 /**
13581 * Handles label mouse click events.
13582 *
13583 * @private
13584 * @param {jQuery.Event} e Mouse click event
13585 */
13586 OO.ui.LabelWidget.prototype.onClick = function () {
13587 this.input.simulateLabelClick();
13588 return false;
13589 };
13590
13591 /**
13592 * OptionWidgets are special elements that can be selected and configured with data. The
13593 * data is often unique for each option, but it does not have to be. OptionWidgets are used
13594 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
13595 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
13596 *
13597 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13598 *
13599 * @class
13600 * @extends OO.ui.Widget
13601 * @mixins OO.ui.LabelElement
13602 * @mixins OO.ui.FlaggedElement
13603 *
13604 * @constructor
13605 * @param {Object} [config] Configuration options
13606 */
13607 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
13608 // Configuration initialization
13609 config = config || {};
13610
13611 // Parent constructor
13612 OO.ui.OptionWidget.super.call( this, config );
13613
13614 // Mixin constructors
13615 OO.ui.ItemWidget.call( this );
13616 OO.ui.LabelElement.call( this, config );
13617 OO.ui.FlaggedElement.call( this, config );
13618
13619 // Properties
13620 this.selected = false;
13621 this.highlighted = false;
13622 this.pressed = false;
13623
13624 // Initialization
13625 this.$element
13626 .data( 'oo-ui-optionWidget', this )
13627 .attr( 'role', 'option' )
13628 .addClass( 'oo-ui-optionWidget' )
13629 .append( this.$label );
13630 };
13631
13632 /* Setup */
13633
13634 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
13635 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
13636 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
13637 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
13638
13639 /* Static Properties */
13640
13641 OO.ui.OptionWidget.static.selectable = true;
13642
13643 OO.ui.OptionWidget.static.highlightable = true;
13644
13645 OO.ui.OptionWidget.static.pressable = true;
13646
13647 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
13648
13649 /* Methods */
13650
13651 /**
13652 * Check if the option can be selected.
13653 *
13654 * @return {boolean} Item is selectable
13655 */
13656 OO.ui.OptionWidget.prototype.isSelectable = function () {
13657 return this.constructor.static.selectable && !this.isDisabled();
13658 };
13659
13660 /**
13661 * Check if the option can be highlighted. A highlight indicates that the option
13662 * may be selected when a user presses enter or clicks. Disabled items cannot
13663 * be highlighted.
13664 *
13665 * @return {boolean} Item is highlightable
13666 */
13667 OO.ui.OptionWidget.prototype.isHighlightable = function () {
13668 return this.constructor.static.highlightable && !this.isDisabled();
13669 };
13670
13671 /**
13672 * Check if the option can be pressed. The pressed state occurs when a user mouses
13673 * down on an item, but has not yet let go of the mouse.
13674 *
13675 * @return {boolean} Item is pressable
13676 */
13677 OO.ui.OptionWidget.prototype.isPressable = function () {
13678 return this.constructor.static.pressable && !this.isDisabled();
13679 };
13680
13681 /**
13682 * Check if the option is selected.
13683 *
13684 * @return {boolean} Item is selected
13685 */
13686 OO.ui.OptionWidget.prototype.isSelected = function () {
13687 return this.selected;
13688 };
13689
13690 /**
13691 * Check if the option is highlighted. A highlight indicates that the
13692 * item may be selected when a user presses enter or clicks.
13693 *
13694 * @return {boolean} Item is highlighted
13695 */
13696 OO.ui.OptionWidget.prototype.isHighlighted = function () {
13697 return this.highlighted;
13698 };
13699
13700 /**
13701 * Check if the option is pressed. The pressed state occurs when a user mouses
13702 * down on an item, but has not yet let go of the mouse. The item may appear
13703 * selected, but it will not be selected until the user releases the mouse.
13704 *
13705 * @return {boolean} Item is pressed
13706 */
13707 OO.ui.OptionWidget.prototype.isPressed = function () {
13708 return this.pressed;
13709 };
13710
13711 /**
13712 * Set the option’s selected state. In general, all modifications to the selection
13713 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
13714 * method instead of this method.
13715 *
13716 * @param {boolean} [state=false] Select option
13717 * @chainable
13718 */
13719 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
13720 if ( this.constructor.static.selectable ) {
13721 this.selected = !!state;
13722 this.$element
13723 .toggleClass( 'oo-ui-optionWidget-selected', state )
13724 .attr( 'aria-selected', state.toString() );
13725 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
13726 this.scrollElementIntoView();
13727 }
13728 this.updateThemeClasses();
13729 }
13730 return this;
13731 };
13732
13733 /**
13734 * Set the option’s highlighted state. In general, all programmatic
13735 * modifications to the highlight should be handled by the
13736 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
13737 * method instead of this method.
13738 *
13739 * @param {boolean} [state=false] Highlight option
13740 * @chainable
13741 */
13742 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
13743 if ( this.constructor.static.highlightable ) {
13744 this.highlighted = !!state;
13745 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
13746 this.updateThemeClasses();
13747 }
13748 return this;
13749 };
13750
13751 /**
13752 * Set the option’s pressed state. In general, all
13753 * programmatic modifications to the pressed state should be handled by the
13754 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
13755 * method instead of this method.
13756 *
13757 * @param {boolean} [state=false] Press option
13758 * @chainable
13759 */
13760 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
13761 if ( this.constructor.static.pressable ) {
13762 this.pressed = !!state;
13763 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
13764 this.updateThemeClasses();
13765 }
13766 return this;
13767 };
13768
13769 /**
13770 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
13771 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
13772 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
13773 * options. For more information about options and selects, please see the
13774 * [OOjs UI documentation on MediaWiki][1].
13775 *
13776 * @example
13777 * // Decorated options in a select widget
13778 * var select = new OO.ui.SelectWidget( {
13779 * items: [
13780 * new OO.ui.DecoratedOptionWidget( {
13781 * data: 'a',
13782 * label: 'Option with icon',
13783 * icon: 'help'
13784 * } ),
13785 * new OO.ui.DecoratedOptionWidget( {
13786 * data: 'b',
13787 * label: 'Option with indicator',
13788 * indicator: 'next'
13789 * } )
13790 * ]
13791 * } );
13792 * $( 'body' ).append( select.$element );
13793 *
13794 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13795 *
13796 * @class
13797 * @extends OO.ui.OptionWidget
13798 * @mixins OO.ui.IconElement
13799 * @mixins OO.ui.IndicatorElement
13800 *
13801 * @constructor
13802 * @param {Object} [config] Configuration options
13803 */
13804 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
13805 // Parent constructor
13806 OO.ui.DecoratedOptionWidget.super.call( this, config );
13807
13808 // Mixin constructors
13809 OO.ui.IconElement.call( this, config );
13810 OO.ui.IndicatorElement.call( this, config );
13811
13812 // Initialization
13813 this.$element
13814 .addClass( 'oo-ui-decoratedOptionWidget' )
13815 .prepend( this.$icon )
13816 .append( this.$indicator );
13817 };
13818
13819 /* Setup */
13820
13821 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
13822 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
13823 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
13824
13825 /**
13826 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
13827 * can be selected and configured with data. The class is
13828 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
13829 * [OOjs UI documentation on MediaWiki] [1] for more information.
13830 *
13831 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
13832 *
13833 * @class
13834 * @extends OO.ui.DecoratedOptionWidget
13835 * @mixins OO.ui.ButtonElement
13836 * @mixins OO.ui.TabIndexedElement
13837 *
13838 * @constructor
13839 * @param {Object} [config] Configuration options
13840 */
13841 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
13842 // Configuration initialization
13843 config = $.extend( { tabIndex: -1 }, config );
13844
13845 // Parent constructor
13846 OO.ui.ButtonOptionWidget.super.call( this, config );
13847
13848 // Mixin constructors
13849 OO.ui.ButtonElement.call( this, config );
13850 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13851
13852 // Initialization
13853 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
13854 this.$button.append( this.$element.contents() );
13855 this.$element.append( this.$button );
13856 };
13857
13858 /* Setup */
13859
13860 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
13861 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
13862 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
13863
13864 /* Static Properties */
13865
13866 // Allow button mouse down events to pass through so they can be handled by the parent select widget
13867 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
13868
13869 OO.ui.ButtonOptionWidget.static.highlightable = false;
13870
13871 /* Methods */
13872
13873 /**
13874 * @inheritdoc
13875 */
13876 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
13877 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
13878
13879 if ( this.constructor.static.selectable ) {
13880 this.setActive( state );
13881 }
13882
13883 return this;
13884 };
13885
13886 /**
13887 * RadioOptionWidget is an option widget that looks like a radio button.
13888 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
13889 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
13890 *
13891 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
13892 *
13893 * @class
13894 * @extends OO.ui.OptionWidget
13895 *
13896 * @constructor
13897 * @param {Object} [config] Configuration options
13898 */
13899 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
13900 // Configuration initialization
13901 config = config || {};
13902
13903 // Properties (must be done before parent constructor which calls #setDisabled)
13904 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
13905
13906 // Parent constructor
13907 OO.ui.RadioOptionWidget.super.call( this, config );
13908
13909 // Initialization
13910 this.$element
13911 .addClass( 'oo-ui-radioOptionWidget' )
13912 .prepend( this.radio.$element );
13913 };
13914
13915 /* Setup */
13916
13917 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
13918
13919 /* Static Properties */
13920
13921 OO.ui.RadioOptionWidget.static.highlightable = false;
13922
13923 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
13924
13925 OO.ui.RadioOptionWidget.static.pressable = false;
13926
13927 OO.ui.RadioOptionWidget.static.tagName = 'label';
13928
13929 /* Methods */
13930
13931 /**
13932 * @inheritdoc
13933 */
13934 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
13935 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
13936
13937 this.radio.setSelected( state );
13938
13939 return this;
13940 };
13941
13942 /**
13943 * @inheritdoc
13944 */
13945 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
13946 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
13947
13948 this.radio.setDisabled( this.isDisabled() );
13949
13950 return this;
13951 };
13952
13953 /**
13954 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
13955 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
13956 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13957 *
13958 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13959 *
13960 * @class
13961 * @extends OO.ui.DecoratedOptionWidget
13962 *
13963 * @constructor
13964 * @param {Object} [config] Configuration options
13965 */
13966 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
13967 // Configuration initialization
13968 config = $.extend( { icon: 'check' }, config );
13969
13970 // Parent constructor
13971 OO.ui.MenuOptionWidget.super.call( this, config );
13972
13973 // Initialization
13974 this.$element
13975 .attr( 'role', 'menuitem' )
13976 .addClass( 'oo-ui-menuOptionWidget' );
13977 };
13978
13979 /* Setup */
13980
13981 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
13982
13983 /* Static Properties */
13984
13985 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
13986
13987 /**
13988 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
13989 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
13990 *
13991 * @example
13992 * var myDropdown = new OO.ui.DropdownWidget( {
13993 * menu: {
13994 * items: [
13995 * new OO.ui.MenuSectionOptionWidget( {
13996 * label: 'Dogs'
13997 * } ),
13998 * new OO.ui.MenuOptionWidget( {
13999 * data: 'corgi',
14000 * label: 'Welsh Corgi'
14001 * } ),
14002 * new OO.ui.MenuOptionWidget( {
14003 * data: 'poodle',
14004 * label: 'Standard Poodle'
14005 * } ),
14006 * new OO.ui.MenuSectionOptionWidget( {
14007 * label: 'Cats'
14008 * } ),
14009 * new OO.ui.MenuOptionWidget( {
14010 * data: 'lion',
14011 * label: 'Lion'
14012 * } )
14013 * ]
14014 * }
14015 * } );
14016 * $( 'body' ).append( myDropdown.$element );
14017 *
14018 *
14019 * @class
14020 * @extends OO.ui.DecoratedOptionWidget
14021 *
14022 * @constructor
14023 * @param {Object} [config] Configuration options
14024 */
14025 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
14026 // Parent constructor
14027 OO.ui.MenuSectionOptionWidget.super.call( this, config );
14028
14029 // Initialization
14030 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
14031 };
14032
14033 /* Setup */
14034
14035 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
14036
14037 /* Static Properties */
14038
14039 OO.ui.MenuSectionOptionWidget.static.selectable = false;
14040
14041 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
14042
14043 /**
14044 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
14045 *
14046 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
14047 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
14048 * for an example.
14049 *
14050 * @class
14051 * @extends OO.ui.DecoratedOptionWidget
14052 *
14053 * @constructor
14054 * @param {Object} [config] Configuration options
14055 * @cfg {number} [level] Indentation level
14056 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
14057 */
14058 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
14059 // Configuration initialization
14060 config = config || {};
14061
14062 // Parent constructor
14063 OO.ui.OutlineOptionWidget.super.call( this, config );
14064
14065 // Properties
14066 this.level = 0;
14067 this.movable = !!config.movable;
14068 this.removable = !!config.removable;
14069
14070 // Initialization
14071 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
14072 this.setLevel( config.level );
14073 };
14074
14075 /* Setup */
14076
14077 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
14078
14079 /* Static Properties */
14080
14081 OO.ui.OutlineOptionWidget.static.highlightable = false;
14082
14083 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
14084
14085 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
14086
14087 OO.ui.OutlineOptionWidget.static.levels = 3;
14088
14089 /* Methods */
14090
14091 /**
14092 * Check if item is movable.
14093 *
14094 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14095 *
14096 * @return {boolean} Item is movable
14097 */
14098 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
14099 return this.movable;
14100 };
14101
14102 /**
14103 * Check if item is removable.
14104 *
14105 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14106 *
14107 * @return {boolean} Item is removable
14108 */
14109 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
14110 return this.removable;
14111 };
14112
14113 /**
14114 * Get indentation level.
14115 *
14116 * @return {number} Indentation level
14117 */
14118 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
14119 return this.level;
14120 };
14121
14122 /**
14123 * Set movability.
14124 *
14125 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14126 *
14127 * @param {boolean} movable Item is movable
14128 * @chainable
14129 */
14130 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
14131 this.movable = !!movable;
14132 this.updateThemeClasses();
14133 return this;
14134 };
14135
14136 /**
14137 * Set removability.
14138 *
14139 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
14140 *
14141 * @param {boolean} movable Item is removable
14142 * @chainable
14143 */
14144 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
14145 this.removable = !!removable;
14146 this.updateThemeClasses();
14147 return this;
14148 };
14149
14150 /**
14151 * Set indentation level.
14152 *
14153 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
14154 * @chainable
14155 */
14156 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
14157 var levels = this.constructor.static.levels,
14158 levelClass = this.constructor.static.levelClass,
14159 i = levels;
14160
14161 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
14162 while ( i-- ) {
14163 if ( this.level === i ) {
14164 this.$element.addClass( levelClass + i );
14165 } else {
14166 this.$element.removeClass( levelClass + i );
14167 }
14168 }
14169 this.updateThemeClasses();
14170
14171 return this;
14172 };
14173
14174 /**
14175 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
14176 *
14177 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
14178 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
14179 * for an example.
14180 *
14181 * @class
14182 * @extends OO.ui.OptionWidget
14183 *
14184 * @constructor
14185 * @param {Object} [config] Configuration options
14186 */
14187 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
14188 // Configuration initialization
14189 config = config || {};
14190
14191 // Parent constructor
14192 OO.ui.TabOptionWidget.super.call( this, config );
14193
14194 // Initialization
14195 this.$element.addClass( 'oo-ui-tabOptionWidget' );
14196 };
14197
14198 /* Setup */
14199
14200 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
14201
14202 /* Static Properties */
14203
14204 OO.ui.TabOptionWidget.static.highlightable = false;
14205
14206 /**
14207 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
14208 * By default, each popup has an anchor that points toward its origin.
14209 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
14210 *
14211 * @example
14212 * // A popup widget.
14213 * var popup = new OO.ui.PopupWidget( {
14214 * $content: $( '<p>Hi there!</p>' ),
14215 * padded: true,
14216 * width: 300
14217 * } );
14218 *
14219 * $( 'body' ).append( popup.$element );
14220 * // To display the popup, toggle the visibility to 'true'.
14221 * popup.toggle( true );
14222 *
14223 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
14224 *
14225 * @class
14226 * @extends OO.ui.Widget
14227 * @mixins OO.ui.LabelElement
14228 *
14229 * @constructor
14230 * @param {Object} [config] Configuration options
14231 * @cfg {number} [width=320] Width of popup in pixels
14232 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
14233 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
14234 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
14235 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
14236 * popup is leaning towards the right of the screen.
14237 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
14238 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
14239 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
14240 * sentence in the given language.
14241 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
14242 * See the [OOjs UI docs on MediaWiki][3] for an example.
14243 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
14244 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
14245 * @cfg {jQuery} [$content] Content to append to the popup's body
14246 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
14247 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
14248 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
14249 * for an example.
14250 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
14251 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
14252 * button.
14253 * @cfg {boolean} [padded] Add padding to the popup's body
14254 */
14255 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
14256 // Configuration initialization
14257 config = config || {};
14258
14259 // Parent constructor
14260 OO.ui.PopupWidget.super.call( this, config );
14261
14262 // Properties (must be set before ClippableElement constructor call)
14263 this.$body = $( '<div>' );
14264
14265 // Mixin constructors
14266 OO.ui.LabelElement.call( this, config );
14267 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
14268
14269 // Properties
14270 this.$popup = $( '<div>' );
14271 this.$head = $( '<div>' );
14272 this.$anchor = $( '<div>' );
14273 // If undefined, will be computed lazily in updateDimensions()
14274 this.$container = config.$container;
14275 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
14276 this.autoClose = !!config.autoClose;
14277 this.$autoCloseIgnore = config.$autoCloseIgnore;
14278 this.transitionTimeout = null;
14279 this.anchor = null;
14280 this.width = config.width !== undefined ? config.width : 320;
14281 this.height = config.height !== undefined ? config.height : null;
14282 this.setAlignment( config.align );
14283 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
14284 this.onMouseDownHandler = this.onMouseDown.bind( this );
14285 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
14286
14287 // Events
14288 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
14289
14290 // Initialization
14291 this.toggleAnchor( config.anchor === undefined || config.anchor );
14292 this.$body.addClass( 'oo-ui-popupWidget-body' );
14293 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
14294 this.$head
14295 .addClass( 'oo-ui-popupWidget-head' )
14296 .append( this.$label, this.closeButton.$element );
14297 if ( !config.head ) {
14298 this.$head.addClass( 'oo-ui-element-hidden' );
14299 }
14300 this.$popup
14301 .addClass( 'oo-ui-popupWidget-popup' )
14302 .append( this.$head, this.$body );
14303 this.$element
14304 .addClass( 'oo-ui-popupWidget' )
14305 .append( this.$popup, this.$anchor );
14306 // Move content, which was added to #$element by OO.ui.Widget, to the body
14307 if ( config.$content instanceof jQuery ) {
14308 this.$body.append( config.$content );
14309 }
14310 if ( config.padded ) {
14311 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
14312 }
14313
14314 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14315 // that reference properties not initialized at that time of parent class construction
14316 // TODO: Find a better way to handle post-constructor setup
14317 this.visible = false;
14318 this.$element.addClass( 'oo-ui-element-hidden' );
14319 };
14320
14321 /* Setup */
14322
14323 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
14324 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
14325 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
14326
14327 /* Methods */
14328
14329 /**
14330 * Handles mouse down events.
14331 *
14332 * @private
14333 * @param {MouseEvent} e Mouse down event
14334 */
14335 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
14336 if (
14337 this.isVisible() &&
14338 !$.contains( this.$element[ 0 ], e.target ) &&
14339 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
14340 ) {
14341 this.toggle( false );
14342 }
14343 };
14344
14345 /**
14346 * Bind mouse down listener.
14347 *
14348 * @private
14349 */
14350 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
14351 // Capture clicks outside popup
14352 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
14353 };
14354
14355 /**
14356 * Handles close button click events.
14357 *
14358 * @private
14359 */
14360 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
14361 if ( this.isVisible() ) {
14362 this.toggle( false );
14363 }
14364 };
14365
14366 /**
14367 * Unbind mouse down listener.
14368 *
14369 * @private
14370 */
14371 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
14372 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
14373 };
14374
14375 /**
14376 * Handles key down events.
14377 *
14378 * @private
14379 * @param {KeyboardEvent} e Key down event
14380 */
14381 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
14382 if (
14383 e.which === OO.ui.Keys.ESCAPE &&
14384 this.isVisible()
14385 ) {
14386 this.toggle( false );
14387 e.preventDefault();
14388 e.stopPropagation();
14389 }
14390 };
14391
14392 /**
14393 * Bind key down listener.
14394 *
14395 * @private
14396 */
14397 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
14398 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
14399 };
14400
14401 /**
14402 * Unbind key down listener.
14403 *
14404 * @private
14405 */
14406 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
14407 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
14408 };
14409
14410 /**
14411 * Show, hide, or toggle the visibility of the anchor.
14412 *
14413 * @param {boolean} [show] Show anchor, omit to toggle
14414 */
14415 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
14416 show = show === undefined ? !this.anchored : !!show;
14417
14418 if ( this.anchored !== show ) {
14419 if ( show ) {
14420 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
14421 } else {
14422 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
14423 }
14424 this.anchored = show;
14425 }
14426 };
14427
14428 /**
14429 * Check if the anchor is visible.
14430 *
14431 * @return {boolean} Anchor is visible
14432 */
14433 OO.ui.PopupWidget.prototype.hasAnchor = function () {
14434 return this.anchor;
14435 };
14436
14437 /**
14438 * @inheritdoc
14439 */
14440 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
14441 show = show === undefined ? !this.isVisible() : !!show;
14442
14443 var change = show !== this.isVisible();
14444
14445 // Parent method
14446 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
14447
14448 if ( change ) {
14449 if ( show ) {
14450 if ( this.autoClose ) {
14451 this.bindMouseDownListener();
14452 this.bindKeyDownListener();
14453 }
14454 this.updateDimensions();
14455 this.toggleClipping( true );
14456 } else {
14457 this.toggleClipping( false );
14458 if ( this.autoClose ) {
14459 this.unbindMouseDownListener();
14460 this.unbindKeyDownListener();
14461 }
14462 }
14463 }
14464
14465 return this;
14466 };
14467
14468 /**
14469 * Set the size of the popup.
14470 *
14471 * Changing the size may also change the popup's position depending on the alignment.
14472 *
14473 * @param {number} width Width in pixels
14474 * @param {number} height Height in pixels
14475 * @param {boolean} [transition=false] Use a smooth transition
14476 * @chainable
14477 */
14478 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
14479 this.width = width;
14480 this.height = height !== undefined ? height : null;
14481 if ( this.isVisible() ) {
14482 this.updateDimensions( transition );
14483 }
14484 };
14485
14486 /**
14487 * Update the size and position.
14488 *
14489 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
14490 * be called automatically.
14491 *
14492 * @param {boolean} [transition=false] Use a smooth transition
14493 * @chainable
14494 */
14495 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
14496 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
14497 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
14498 align = this.align,
14499 widget = this;
14500
14501 if ( !this.$container ) {
14502 // Lazy-initialize $container if not specified in constructor
14503 this.$container = $( this.getClosestScrollableElementContainer() );
14504 }
14505
14506 // Set height and width before measuring things, since it might cause our measurements
14507 // to change (e.g. due to scrollbars appearing or disappearing)
14508 this.$popup.css( {
14509 width: this.width,
14510 height: this.height !== null ? this.height : 'auto'
14511 } );
14512
14513 // If we are in RTL, we need to flip the alignment, unless it is center
14514 if ( align === 'forwards' || align === 'backwards' ) {
14515 if ( this.$container.css( 'direction' ) === 'rtl' ) {
14516 align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ];
14517 } else {
14518 align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ];
14519 }
14520
14521 }
14522
14523 // Compute initial popupOffset based on alignment
14524 popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ];
14525
14526 // Figure out if this will cause the popup to go beyond the edge of the container
14527 originOffset = this.$element.offset().left;
14528 containerLeft = this.$container.offset().left;
14529 containerWidth = this.$container.innerWidth();
14530 containerRight = containerLeft + containerWidth;
14531 popupLeft = popupOffset - this.containerPadding;
14532 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
14533 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
14534 overlapRight = containerRight - ( originOffset + popupRight );
14535
14536 // Adjust offset to make the popup not go beyond the edge, if needed
14537 if ( overlapRight < 0 ) {
14538 popupOffset += overlapRight;
14539 } else if ( overlapLeft < 0 ) {
14540 popupOffset -= overlapLeft;
14541 }
14542
14543 // Adjust offset to avoid anchor being rendered too close to the edge
14544 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
14545 // TODO: Find a measurement that works for CSS anchors and image anchors
14546 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
14547 if ( popupOffset + this.width < anchorWidth ) {
14548 popupOffset = anchorWidth - this.width;
14549 } else if ( -popupOffset < anchorWidth ) {
14550 popupOffset = -anchorWidth;
14551 }
14552
14553 // Prevent transition from being interrupted
14554 clearTimeout( this.transitionTimeout );
14555 if ( transition ) {
14556 // Enable transition
14557 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
14558 }
14559
14560 // Position body relative to anchor
14561 this.$popup.css( 'margin-left', popupOffset );
14562
14563 if ( transition ) {
14564 // Prevent transitioning after transition is complete
14565 this.transitionTimeout = setTimeout( function () {
14566 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
14567 }, 200 );
14568 } else {
14569 // Prevent transitioning immediately
14570 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
14571 }
14572
14573 // Reevaluate clipping state since we've relocated and resized the popup
14574 this.clip();
14575
14576 return this;
14577 };
14578
14579 /**
14580 * Set popup alignment
14581 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
14582 * `backwards` or `forwards`.
14583 */
14584 OO.ui.PopupWidget.prototype.setAlignment = function ( align ) {
14585 // Validate alignment and transform deprecated values
14586 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) {
14587 this.align = { left: 'force-right', right: 'force-left' }[ align ] || align;
14588 } else {
14589 this.align = 'center';
14590 }
14591 };
14592
14593 /**
14594 * Get popup alignment
14595 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
14596 * `backwards` or `forwards`.
14597 */
14598 OO.ui.PopupWidget.prototype.getAlignment = function () {
14599 return this.align;
14600 };
14601
14602 /**
14603 * Progress bars visually display the status of an operation, such as a download,
14604 * and can be either determinate or indeterminate:
14605 *
14606 * - **determinate** process bars show the percent of an operation that is complete.
14607 *
14608 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
14609 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
14610 * not use percentages.
14611 *
14612 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
14613 *
14614 * @example
14615 * // Examples of determinate and indeterminate progress bars.
14616 * var progressBar1 = new OO.ui.ProgressBarWidget( {
14617 * progress: 33
14618 * } );
14619 * var progressBar2 = new OO.ui.ProgressBarWidget();
14620 *
14621 * // Create a FieldsetLayout to layout progress bars
14622 * var fieldset = new OO.ui.FieldsetLayout;
14623 * fieldset.addItems( [
14624 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
14625 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
14626 * ] );
14627 * $( 'body' ).append( fieldset.$element );
14628 *
14629 * @class
14630 * @extends OO.ui.Widget
14631 *
14632 * @constructor
14633 * @param {Object} [config] Configuration options
14634 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
14635 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
14636 * By default, the progress bar is indeterminate.
14637 */
14638 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
14639 // Configuration initialization
14640 config = config || {};
14641
14642 // Parent constructor
14643 OO.ui.ProgressBarWidget.super.call( this, config );
14644
14645 // Properties
14646 this.$bar = $( '<div>' );
14647 this.progress = null;
14648
14649 // Initialization
14650 this.setProgress( config.progress !== undefined ? config.progress : false );
14651 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
14652 this.$element
14653 .attr( {
14654 role: 'progressbar',
14655 'aria-valuemin': 0,
14656 'aria-valuemax': 100
14657 } )
14658 .addClass( 'oo-ui-progressBarWidget' )
14659 .append( this.$bar );
14660 };
14661
14662 /* Setup */
14663
14664 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
14665
14666 /* Static Properties */
14667
14668 OO.ui.ProgressBarWidget.static.tagName = 'div';
14669
14670 /* Methods */
14671
14672 /**
14673 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
14674 *
14675 * @return {number|boolean} Progress percent
14676 */
14677 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
14678 return this.progress;
14679 };
14680
14681 /**
14682 * Set the percent of the process completed or `false` for an indeterminate process.
14683 *
14684 * @param {number|boolean} progress Progress percent or `false` for indeterminate
14685 */
14686 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
14687 this.progress = progress;
14688
14689 if ( progress !== false ) {
14690 this.$bar.css( 'width', this.progress + '%' );
14691 this.$element.attr( 'aria-valuenow', this.progress );
14692 } else {
14693 this.$bar.css( 'width', '' );
14694 this.$element.removeAttr( 'aria-valuenow' );
14695 }
14696 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
14697 };
14698
14699 /**
14700 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
14701 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
14702 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
14703 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
14704 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
14705 *
14706 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
14707 * the [OOjs UI demos][1] for an example.
14708 *
14709 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
14710 *
14711 * @class
14712 * @extends OO.ui.Widget
14713 *
14714 * @constructor
14715 * @param {Object} [config] Configuration options
14716 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
14717 * @cfg {string} [value] Initial query value
14718 */
14719 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
14720 // Configuration initialization
14721 config = config || {};
14722
14723 // Parent constructor
14724 OO.ui.SearchWidget.super.call( this, config );
14725
14726 // Properties
14727 this.query = new OO.ui.TextInputWidget( {
14728 icon: 'search',
14729 placeholder: config.placeholder,
14730 value: config.value
14731 } );
14732 this.results = new OO.ui.SelectWidget();
14733 this.$query = $( '<div>' );
14734 this.$results = $( '<div>' );
14735
14736 // Events
14737 this.query.connect( this, {
14738 change: 'onQueryChange',
14739 enter: 'onQueryEnter'
14740 } );
14741 this.results.connect( this, {
14742 highlight: 'onResultsHighlight',
14743 select: 'onResultsSelect'
14744 } );
14745 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
14746
14747 // Initialization
14748 this.$query
14749 .addClass( 'oo-ui-searchWidget-query' )
14750 .append( this.query.$element );
14751 this.$results
14752 .addClass( 'oo-ui-searchWidget-results' )
14753 .append( this.results.$element );
14754 this.$element
14755 .addClass( 'oo-ui-searchWidget' )
14756 .append( this.$results, this.$query );
14757 };
14758
14759 /* Setup */
14760
14761 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
14762
14763 /* Events */
14764
14765 /**
14766 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
14767 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
14768 * string is typed into the query field instead, the first menu item that matches the query
14769 * will be highlighted.
14770
14771 * @event highlight
14772 * @deprecated Connect straight to getResults() events instead
14773 * @param {Object|null} item Item data or null if no item is highlighted
14774 */
14775
14776 /**
14777 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
14778 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
14779 *
14780 * @event select
14781 * @deprecated Connect straight to getResults() events instead
14782 * @param {Object|null} item Item data or null if no item is selected
14783 */
14784
14785 /* Methods */
14786
14787 /**
14788 * Handle query key down events.
14789 *
14790 * @private
14791 * @param {jQuery.Event} e Key down event
14792 */
14793 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
14794 var highlightedItem, nextItem,
14795 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
14796
14797 if ( dir ) {
14798 highlightedItem = this.results.getHighlightedItem();
14799 if ( !highlightedItem ) {
14800 highlightedItem = this.results.getSelectedItem();
14801 }
14802 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
14803 this.results.highlightItem( nextItem );
14804 nextItem.scrollElementIntoView();
14805 }
14806 };
14807
14808 /**
14809 * Handle select widget select events.
14810 *
14811 * Clears existing results. Subclasses should repopulate items according to new query.
14812 *
14813 * @private
14814 * @param {string} value New value
14815 */
14816 OO.ui.SearchWidget.prototype.onQueryChange = function () {
14817 // Reset
14818 this.results.clearItems();
14819 };
14820
14821 /**
14822 * Handle select widget enter key events.
14823 *
14824 * Selects highlighted item.
14825 *
14826 * @private
14827 * @param {string} value New value
14828 */
14829 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
14830 // Reset
14831 this.results.selectItem( this.results.getHighlightedItem() );
14832 };
14833
14834 /**
14835 * Handle select widget highlight events.
14836 *
14837 * @private
14838 * @deprecated Connect straight to getResults() events instead
14839 * @param {OO.ui.OptionWidget} item Highlighted item
14840 * @fires highlight
14841 */
14842 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
14843 this.emit( 'highlight', item ? item.getData() : null );
14844 };
14845
14846 /**
14847 * Handle select widget select events.
14848 *
14849 * @private
14850 * @deprecated Connect straight to getResults() events instead
14851 * @param {OO.ui.OptionWidget} item Selected item
14852 * @fires select
14853 */
14854 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
14855 this.emit( 'select', item ? item.getData() : null );
14856 };
14857
14858 /**
14859 * Get the query input.
14860 *
14861 * @return {OO.ui.TextInputWidget} Query input
14862 */
14863 OO.ui.SearchWidget.prototype.getQuery = function () {
14864 return this.query;
14865 };
14866
14867 /**
14868 * Get the search results menu.
14869 *
14870 * @return {OO.ui.SelectWidget} Menu of search results
14871 */
14872 OO.ui.SearchWidget.prototype.getResults = function () {
14873 return this.results;
14874 };
14875
14876 /**
14877 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
14878 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
14879 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
14880 * menu selects}.
14881 *
14882 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
14883 * information, please see the [OOjs UI documentation on MediaWiki][1].
14884 *
14885 * @example
14886 * // Example of a select widget with three options
14887 * var select = new OO.ui.SelectWidget( {
14888 * items: [
14889 * new OO.ui.OptionWidget( {
14890 * data: 'a',
14891 * label: 'Option One',
14892 * } ),
14893 * new OO.ui.OptionWidget( {
14894 * data: 'b',
14895 * label: 'Option Two',
14896 * } ),
14897 * new OO.ui.OptionWidget( {
14898 * data: 'c',
14899 * label: 'Option Three',
14900 * } )
14901 * ]
14902 * } );
14903 * $( 'body' ).append( select.$element );
14904 *
14905 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14906 *
14907 * @abstract
14908 * @class
14909 * @extends OO.ui.Widget
14910 * @mixins OO.ui.GroupElement
14911 *
14912 * @constructor
14913 * @param {Object} [config] Configuration options
14914 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
14915 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
14916 * the [OOjs UI documentation on MediaWiki] [2] for examples.
14917 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14918 */
14919 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
14920 // Configuration initialization
14921 config = config || {};
14922
14923 // Parent constructor
14924 OO.ui.SelectWidget.super.call( this, config );
14925
14926 // Mixin constructors
14927 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
14928
14929 // Properties
14930 this.pressed = false;
14931 this.selecting = null;
14932 this.onMouseUpHandler = this.onMouseUp.bind( this );
14933 this.onMouseMoveHandler = this.onMouseMove.bind( this );
14934 this.onKeyDownHandler = this.onKeyDown.bind( this );
14935
14936 // Events
14937 this.$element.on( {
14938 mousedown: this.onMouseDown.bind( this ),
14939 mouseover: this.onMouseOver.bind( this ),
14940 mouseleave: this.onMouseLeave.bind( this )
14941 } );
14942
14943 // Initialization
14944 this.$element
14945 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
14946 .attr( 'role', 'listbox' );
14947 if ( Array.isArray( config.items ) ) {
14948 this.addItems( config.items );
14949 }
14950 };
14951
14952 /* Setup */
14953
14954 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
14955
14956 // Need to mixin base class as well
14957 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
14958 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
14959
14960 /* Events */
14961
14962 /**
14963 * @event highlight
14964 *
14965 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
14966 *
14967 * @param {OO.ui.OptionWidget|null} item Highlighted item
14968 */
14969
14970 /**
14971 * @event press
14972 *
14973 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
14974 * pressed state of an option.
14975 *
14976 * @param {OO.ui.OptionWidget|null} item Pressed item
14977 */
14978
14979 /**
14980 * @event select
14981 *
14982 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
14983 *
14984 * @param {OO.ui.OptionWidget|null} item Selected item
14985 */
14986
14987 /**
14988 * @event choose
14989 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
14990 * @param {OO.ui.OptionWidget} item Chosen item
14991 */
14992
14993 /**
14994 * @event add
14995 *
14996 * An `add` event is emitted when options are added to the select with the #addItems method.
14997 *
14998 * @param {OO.ui.OptionWidget[]} items Added items
14999 * @param {number} index Index of insertion point
15000 */
15001
15002 /**
15003 * @event remove
15004 *
15005 * A `remove` event is emitted when options are removed from the select with the #clearItems
15006 * or #removeItems methods.
15007 *
15008 * @param {OO.ui.OptionWidget[]} items Removed items
15009 */
15010
15011 /* Methods */
15012
15013 /**
15014 * Handle mouse down events.
15015 *
15016 * @private
15017 * @param {jQuery.Event} e Mouse down event
15018 */
15019 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
15020 var item;
15021
15022 if ( !this.isDisabled() && e.which === 1 ) {
15023 this.togglePressed( true );
15024 item = this.getTargetItem( e );
15025 if ( item && item.isSelectable() ) {
15026 this.pressItem( item );
15027 this.selecting = item;
15028 this.getElementDocument().addEventListener(
15029 'mouseup',
15030 this.onMouseUpHandler,
15031 true
15032 );
15033 this.getElementDocument().addEventListener(
15034 'mousemove',
15035 this.onMouseMoveHandler,
15036 true
15037 );
15038 }
15039 }
15040 return false;
15041 };
15042
15043 /**
15044 * Handle mouse up events.
15045 *
15046 * @private
15047 * @param {jQuery.Event} e Mouse up event
15048 */
15049 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
15050 var item;
15051
15052 this.togglePressed( false );
15053 if ( !this.selecting ) {
15054 item = this.getTargetItem( e );
15055 if ( item && item.isSelectable() ) {
15056 this.selecting = item;
15057 }
15058 }
15059 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
15060 this.pressItem( null );
15061 this.chooseItem( this.selecting );
15062 this.selecting = null;
15063 }
15064
15065 this.getElementDocument().removeEventListener(
15066 'mouseup',
15067 this.onMouseUpHandler,
15068 true
15069 );
15070 this.getElementDocument().removeEventListener(
15071 'mousemove',
15072 this.onMouseMoveHandler,
15073 true
15074 );
15075
15076 return false;
15077 };
15078
15079 /**
15080 * Handle mouse move events.
15081 *
15082 * @private
15083 * @param {jQuery.Event} e Mouse move event
15084 */
15085 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
15086 var item;
15087
15088 if ( !this.isDisabled() && this.pressed ) {
15089 item = this.getTargetItem( e );
15090 if ( item && item !== this.selecting && item.isSelectable() ) {
15091 this.pressItem( item );
15092 this.selecting = item;
15093 }
15094 }
15095 return false;
15096 };
15097
15098 /**
15099 * Handle mouse over events.
15100 *
15101 * @private
15102 * @param {jQuery.Event} e Mouse over event
15103 */
15104 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
15105 var item;
15106
15107 if ( !this.isDisabled() ) {
15108 item = this.getTargetItem( e );
15109 this.highlightItem( item && item.isHighlightable() ? item : null );
15110 }
15111 return false;
15112 };
15113
15114 /**
15115 * Handle mouse leave events.
15116 *
15117 * @private
15118 * @param {jQuery.Event} e Mouse over event
15119 */
15120 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
15121 if ( !this.isDisabled() ) {
15122 this.highlightItem( null );
15123 }
15124 return false;
15125 };
15126
15127 /**
15128 * Handle key down events.
15129 *
15130 * @protected
15131 * @param {jQuery.Event} e Key down event
15132 */
15133 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
15134 var nextItem,
15135 handled = false,
15136 currentItem = this.getHighlightedItem() || this.getSelectedItem();
15137
15138 if ( !this.isDisabled() && this.isVisible() ) {
15139 switch ( e.keyCode ) {
15140 case OO.ui.Keys.ENTER:
15141 if ( currentItem && currentItem.constructor.static.highlightable ) {
15142 // Was only highlighted, now let's select it. No-op if already selected.
15143 this.chooseItem( currentItem );
15144 handled = true;
15145 }
15146 break;
15147 case OO.ui.Keys.UP:
15148 case OO.ui.Keys.LEFT:
15149 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
15150 handled = true;
15151 break;
15152 case OO.ui.Keys.DOWN:
15153 case OO.ui.Keys.RIGHT:
15154 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
15155 handled = true;
15156 break;
15157 case OO.ui.Keys.ESCAPE:
15158 case OO.ui.Keys.TAB:
15159 if ( currentItem && currentItem.constructor.static.highlightable ) {
15160 currentItem.setHighlighted( false );
15161 }
15162 this.unbindKeyDownListener();
15163 // Don't prevent tabbing away / defocusing
15164 handled = false;
15165 break;
15166 }
15167
15168 if ( nextItem ) {
15169 if ( nextItem.constructor.static.highlightable ) {
15170 this.highlightItem( nextItem );
15171 } else {
15172 this.chooseItem( nextItem );
15173 }
15174 nextItem.scrollElementIntoView();
15175 }
15176
15177 if ( handled ) {
15178 // Can't just return false, because e is not always a jQuery event
15179 e.preventDefault();
15180 e.stopPropagation();
15181 }
15182 }
15183 };
15184
15185 /**
15186 * Bind key down listener.
15187 *
15188 * @protected
15189 */
15190 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
15191 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
15192 };
15193
15194 /**
15195 * Unbind key down listener.
15196 *
15197 * @protected
15198 */
15199 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
15200 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
15201 };
15202
15203 /**
15204 * Get the closest item to a jQuery.Event.
15205 *
15206 * @private
15207 * @param {jQuery.Event} e
15208 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
15209 */
15210 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
15211 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
15212 };
15213
15214 /**
15215 * Get selected item.
15216 *
15217 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
15218 */
15219 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
15220 var i, len;
15221
15222 for ( i = 0, len = this.items.length; i < len; i++ ) {
15223 if ( this.items[ i ].isSelected() ) {
15224 return this.items[ i ];
15225 }
15226 }
15227 return null;
15228 };
15229
15230 /**
15231 * Get highlighted item.
15232 *
15233 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
15234 */
15235 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
15236 var i, len;
15237
15238 for ( i = 0, len = this.items.length; i < len; i++ ) {
15239 if ( this.items[ i ].isHighlighted() ) {
15240 return this.items[ i ];
15241 }
15242 }
15243 return null;
15244 };
15245
15246 /**
15247 * Toggle pressed state.
15248 *
15249 * Press is a state that occurs when a user mouses down on an item, but
15250 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
15251 * until the user releases the mouse.
15252 *
15253 * @param {boolean} pressed An option is being pressed
15254 */
15255 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
15256 if ( pressed === undefined ) {
15257 pressed = !this.pressed;
15258 }
15259 if ( pressed !== this.pressed ) {
15260 this.$element
15261 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
15262 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
15263 this.pressed = pressed;
15264 }
15265 };
15266
15267 /**
15268 * Highlight an option. If the `item` param is omitted, no options will be highlighted
15269 * and any existing highlight will be removed. The highlight is mutually exclusive.
15270 *
15271 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
15272 * @fires highlight
15273 * @chainable
15274 */
15275 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
15276 var i, len, highlighted,
15277 changed = false;
15278
15279 for ( i = 0, len = this.items.length; i < len; i++ ) {
15280 highlighted = this.items[ i ] === item;
15281 if ( this.items[ i ].isHighlighted() !== highlighted ) {
15282 this.items[ i ].setHighlighted( highlighted );
15283 changed = true;
15284 }
15285 }
15286 if ( changed ) {
15287 this.emit( 'highlight', item );
15288 }
15289
15290 return this;
15291 };
15292
15293 /**
15294 * Programmatically select an option by its data. If the `data` parameter is omitted,
15295 * or if the item does not exist, all options will be deselected.
15296 *
15297 * @param {Object|string} [data] Value of the item to select, omit to deselect all
15298 * @fires select
15299 * @chainable
15300 */
15301 OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) {
15302 var itemFromData = this.getItemFromData( data );
15303 if ( data === undefined || !itemFromData ) {
15304 return this.selectItem();
15305 }
15306 return this.selectItem( itemFromData );
15307 };
15308
15309 /**
15310 * Programmatically select an option by its reference. If the `item` parameter is omitted,
15311 * all options will be deselected.
15312 *
15313 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
15314 * @fires select
15315 * @chainable
15316 */
15317 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
15318 var i, len, selected,
15319 changed = false;
15320
15321 for ( i = 0, len = this.items.length; i < len; i++ ) {
15322 selected = this.items[ i ] === item;
15323 if ( this.items[ i ].isSelected() !== selected ) {
15324 this.items[ i ].setSelected( selected );
15325 changed = true;
15326 }
15327 }
15328 if ( changed ) {
15329 this.emit( 'select', item );
15330 }
15331
15332 return this;
15333 };
15334
15335 /**
15336 * Press an item.
15337 *
15338 * Press is a state that occurs when a user mouses down on an item, but has not
15339 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
15340 * releases the mouse.
15341 *
15342 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
15343 * @fires press
15344 * @chainable
15345 */
15346 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
15347 var i, len, pressed,
15348 changed = false;
15349
15350 for ( i = 0, len = this.items.length; i < len; i++ ) {
15351 pressed = this.items[ i ] === item;
15352 if ( this.items[ i ].isPressed() !== pressed ) {
15353 this.items[ i ].setPressed( pressed );
15354 changed = true;
15355 }
15356 }
15357 if ( changed ) {
15358 this.emit( 'press', item );
15359 }
15360
15361 return this;
15362 };
15363
15364 /**
15365 * Choose an item.
15366 *
15367 * Note that ‘choose’ should never be modified programmatically. A user can choose
15368 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
15369 * use the #selectItem method.
15370 *
15371 * This method is identical to #selectItem, but may vary in subclasses that take additional action
15372 * when users choose an item with the keyboard or mouse.
15373 *
15374 * @param {OO.ui.OptionWidget} item Item to choose
15375 * @fires choose
15376 * @chainable
15377 */
15378 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
15379 this.selectItem( item );
15380 this.emit( 'choose', item );
15381
15382 return this;
15383 };
15384
15385 /**
15386 * Get an option by its position relative to the specified item (or to the start of the option array,
15387 * if item is `null`). The direction in which to search through the option array is specified with a
15388 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
15389 * `null` if there are no options in the array.
15390 *
15391 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
15392 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
15393 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
15394 */
15395 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
15396 var currentIndex, nextIndex, i,
15397 increase = direction > 0 ? 1 : -1,
15398 len = this.items.length;
15399
15400 if ( item instanceof OO.ui.OptionWidget ) {
15401 currentIndex = $.inArray( item, this.items );
15402 nextIndex = ( currentIndex + increase + len ) % len;
15403 } else {
15404 // If no item is selected and moving forward, start at the beginning.
15405 // If moving backward, start at the end.
15406 nextIndex = direction > 0 ? 0 : len - 1;
15407 }
15408
15409 for ( i = 0; i < len; i++ ) {
15410 item = this.items[ nextIndex ];
15411 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
15412 return item;
15413 }
15414 nextIndex = ( nextIndex + increase + len ) % len;
15415 }
15416 return null;
15417 };
15418
15419 /**
15420 * Get the next selectable item or `null` if there are no selectable items.
15421 * Disabled options and menu-section markers and breaks are not selectable.
15422 *
15423 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
15424 */
15425 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
15426 var i, len, item;
15427
15428 for ( i = 0, len = this.items.length; i < len; i++ ) {
15429 item = this.items[ i ];
15430 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
15431 return item;
15432 }
15433 }
15434
15435 return null;
15436 };
15437
15438 /**
15439 * Add an array of options to the select. Optionally, an index number can be used to
15440 * specify an insertion point.
15441 *
15442 * @param {OO.ui.OptionWidget[]} items Items to add
15443 * @param {number} [index] Index to insert items after
15444 * @fires add
15445 * @chainable
15446 */
15447 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
15448 // Mixin method
15449 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
15450
15451 // Always provide an index, even if it was omitted
15452 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
15453
15454 return this;
15455 };
15456
15457 /**
15458 * Remove the specified array of options from the select. Options will be detached
15459 * from the DOM, not removed, so they can be reused later. To remove all options from
15460 * the select, you may wish to use the #clearItems method instead.
15461 *
15462 * @param {OO.ui.OptionWidget[]} items Items to remove
15463 * @fires remove
15464 * @chainable
15465 */
15466 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
15467 var i, len, item;
15468
15469 // Deselect items being removed
15470 for ( i = 0, len = items.length; i < len; i++ ) {
15471 item = items[ i ];
15472 if ( item.isSelected() ) {
15473 this.selectItem( null );
15474 }
15475 }
15476
15477 // Mixin method
15478 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
15479
15480 this.emit( 'remove', items );
15481
15482 return this;
15483 };
15484
15485 /**
15486 * Clear all options from the select. Options will be detached from the DOM, not removed,
15487 * so that they can be reused later. To remove a subset of options from the select, use
15488 * the #removeItems method.
15489 *
15490 * @fires remove
15491 * @chainable
15492 */
15493 OO.ui.SelectWidget.prototype.clearItems = function () {
15494 var items = this.items.slice();
15495
15496 // Mixin method
15497 OO.ui.GroupWidget.prototype.clearItems.call( this );
15498
15499 // Clear selection
15500 this.selectItem( null );
15501
15502 this.emit( 'remove', items );
15503
15504 return this;
15505 };
15506
15507 /**
15508 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
15509 * button options and is used together with
15510 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
15511 * highlighting, choosing, and selecting mutually exclusive options. Please see
15512 * the [OOjs UI documentation on MediaWiki] [1] for more information.
15513 *
15514 * @example
15515 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
15516 * var option1 = new OO.ui.ButtonOptionWidget( {
15517 * data: 1,
15518 * label: 'Option 1',
15519 * title: 'Button option 1'
15520 * } );
15521 *
15522 * var option2 = new OO.ui.ButtonOptionWidget( {
15523 * data: 2,
15524 * label: 'Option 2',
15525 * title: 'Button option 2'
15526 * } );
15527 *
15528 * var option3 = new OO.ui.ButtonOptionWidget( {
15529 * data: 3,
15530 * label: 'Option 3',
15531 * title: 'Button option 3'
15532 * } );
15533 *
15534 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
15535 * items: [ option1, option2, option3 ]
15536 * } );
15537 * $( 'body' ).append( buttonSelect.$element );
15538 *
15539 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15540 *
15541 * @class
15542 * @extends OO.ui.SelectWidget
15543 * @mixins OO.ui.TabIndexedElement
15544 *
15545 * @constructor
15546 * @param {Object} [config] Configuration options
15547 */
15548 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
15549 // Parent constructor
15550 OO.ui.ButtonSelectWidget.super.call( this, config );
15551
15552 // Mixin constructors
15553 OO.ui.TabIndexedElement.call( this, config );
15554
15555 // Events
15556 this.$element.on( {
15557 focus: this.bindKeyDownListener.bind( this ),
15558 blur: this.unbindKeyDownListener.bind( this )
15559 } );
15560
15561 // Initialization
15562 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
15563 };
15564
15565 /* Setup */
15566
15567 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
15568 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
15569
15570 /**
15571 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
15572 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
15573 * an interface for adding, removing and selecting options.
15574 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
15575 *
15576 * @example
15577 * // A RadioSelectWidget with RadioOptions.
15578 * var option1 = new OO.ui.RadioOptionWidget( {
15579 * data: 'a',
15580 * label: 'Selected radio option'
15581 * } );
15582 *
15583 * var option2 = new OO.ui.RadioOptionWidget( {
15584 * data: 'b',
15585 * label: 'Unselected radio option'
15586 * } );
15587 *
15588 * var radioSelect=new OO.ui.RadioSelectWidget( {
15589 * items: [ option1, option2 ]
15590 * } );
15591 *
15592 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
15593 * radioSelect.selectItem( option1 );
15594 *
15595 * $( 'body' ).append( radioSelect.$element );
15596 *
15597 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15598
15599 *
15600 * @class
15601 * @extends OO.ui.SelectWidget
15602 * @mixins OO.ui.TabIndexedElement
15603 *
15604 * @constructor
15605 * @param {Object} [config] Configuration options
15606 */
15607 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
15608 // Parent constructor
15609 OO.ui.RadioSelectWidget.super.call( this, config );
15610
15611 // Mixin constructors
15612 OO.ui.TabIndexedElement.call( this, config );
15613
15614 // Events
15615 this.$element.on( {
15616 focus: this.bindKeyDownListener.bind( this ),
15617 blur: this.unbindKeyDownListener.bind( this )
15618 } );
15619
15620 // Initialization
15621 this.$element.addClass( 'oo-ui-radioSelectWidget' );
15622 };
15623
15624 /* Setup */
15625
15626 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
15627 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
15628
15629 /**
15630 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
15631 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
15632 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
15633 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
15634 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
15635 * and customized to be opened, closed, and displayed as needed.
15636 *
15637 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
15638 * mouse outside the menu.
15639 *
15640 * Menus also have support for keyboard interaction:
15641 *
15642 * - Enter/Return key: choose and select a menu option
15643 * - Up-arrow key: highlight the previous menu option
15644 * - Down-arrow key: highlight the next menu option
15645 * - Esc key: hide the menu
15646 *
15647 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
15648 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
15649 *
15650 * @class
15651 * @extends OO.ui.SelectWidget
15652 * @mixins OO.ui.ClippableElement
15653 *
15654 * @constructor
15655 * @param {Object} [config] Configuration options
15656 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
15657 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
15658 * and {@link OO.ui.LookupElement LookupElement}
15659 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
15660 * anywhere on the page outside of this widget, the menu is hidden.
15661 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
15662 */
15663 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
15664 // Configuration initialization
15665 config = config || {};
15666
15667 // Parent constructor
15668 OO.ui.MenuSelectWidget.super.call( this, config );
15669
15670 // Mixin constructors
15671 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
15672
15673 // Properties
15674 this.newItems = null;
15675 this.autoHide = config.autoHide === undefined || !!config.autoHide;
15676 this.$input = config.input ? config.input.$input : null;
15677 this.$widget = config.widget ? config.widget.$element : null;
15678 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
15679
15680 // Initialization
15681 this.$element
15682 .addClass( 'oo-ui-menuSelectWidget' )
15683 .attr( 'role', 'menu' );
15684
15685 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
15686 // that reference properties not initialized at that time of parent class construction
15687 // TODO: Find a better way to handle post-constructor setup
15688 this.visible = false;
15689 this.$element.addClass( 'oo-ui-element-hidden' );
15690 };
15691
15692 /* Setup */
15693
15694 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
15695 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
15696
15697 /* Methods */
15698
15699 /**
15700 * Handles document mouse down events.
15701 *
15702 * @protected
15703 * @param {jQuery.Event} e Key down event
15704 */
15705 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
15706 if (
15707 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
15708 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
15709 ) {
15710 this.toggle( false );
15711 }
15712 };
15713
15714 /**
15715 * @inheritdoc
15716 */
15717 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
15718 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
15719
15720 if ( !this.isDisabled() && this.isVisible() ) {
15721 switch ( e.keyCode ) {
15722 case OO.ui.Keys.LEFT:
15723 case OO.ui.Keys.RIGHT:
15724 // Do nothing if a text field is associated, arrow keys will be handled natively
15725 if ( !this.$input ) {
15726 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
15727 }
15728 break;
15729 case OO.ui.Keys.ESCAPE:
15730 case OO.ui.Keys.TAB:
15731 if ( currentItem ) {
15732 currentItem.setHighlighted( false );
15733 }
15734 this.toggle( false );
15735 // Don't prevent tabbing away, prevent defocusing
15736 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
15737 e.preventDefault();
15738 e.stopPropagation();
15739 }
15740 break;
15741 default:
15742 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
15743 return;
15744 }
15745 }
15746 };
15747
15748 /**
15749 * @inheritdoc
15750 */
15751 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
15752 if ( this.$input ) {
15753 this.$input.on( 'keydown', this.onKeyDownHandler );
15754 } else {
15755 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
15756 }
15757 };
15758
15759 /**
15760 * @inheritdoc
15761 */
15762 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
15763 if ( this.$input ) {
15764 this.$input.off( 'keydown', this.onKeyDownHandler );
15765 } else {
15766 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
15767 }
15768 };
15769
15770 /**
15771 * Choose an item.
15772 *
15773 * When a user chooses an item, the menu is closed.
15774 *
15775 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
15776 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
15777 * @param {OO.ui.OptionWidget} item Item to choose
15778 * @chainable
15779 */
15780 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
15781 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
15782 this.toggle( false );
15783 return this;
15784 };
15785
15786 /**
15787 * @inheritdoc
15788 */
15789 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
15790 var i, len, item;
15791
15792 // Parent method
15793 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
15794
15795 // Auto-initialize
15796 if ( !this.newItems ) {
15797 this.newItems = [];
15798 }
15799
15800 for ( i = 0, len = items.length; i < len; i++ ) {
15801 item = items[ i ];
15802 if ( this.isVisible() ) {
15803 // Defer fitting label until item has been attached
15804 item.fitLabel();
15805 } else {
15806 this.newItems.push( item );
15807 }
15808 }
15809
15810 // Reevaluate clipping
15811 this.clip();
15812
15813 return this;
15814 };
15815
15816 /**
15817 * @inheritdoc
15818 */
15819 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
15820 // Parent method
15821 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
15822
15823 // Reevaluate clipping
15824 this.clip();
15825
15826 return this;
15827 };
15828
15829 /**
15830 * @inheritdoc
15831 */
15832 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
15833 // Parent method
15834 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
15835
15836 // Reevaluate clipping
15837 this.clip();
15838
15839 return this;
15840 };
15841
15842 /**
15843 * @inheritdoc
15844 */
15845 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
15846 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
15847
15848 var i, len,
15849 change = visible !== this.isVisible();
15850
15851 // Parent method
15852 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
15853
15854 if ( change ) {
15855 if ( visible ) {
15856 this.bindKeyDownListener();
15857
15858 if ( this.newItems && this.newItems.length ) {
15859 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
15860 this.newItems[ i ].fitLabel();
15861 }
15862 this.newItems = null;
15863 }
15864 this.toggleClipping( true );
15865
15866 // Auto-hide
15867 if ( this.autoHide ) {
15868 this.getElementDocument().addEventListener(
15869 'mousedown', this.onDocumentMouseDownHandler, true
15870 );
15871 }
15872 } else {
15873 this.unbindKeyDownListener();
15874 this.getElementDocument().removeEventListener(
15875 'mousedown', this.onDocumentMouseDownHandler, true
15876 );
15877 this.toggleClipping( false );
15878 }
15879 }
15880
15881 return this;
15882 };
15883
15884 /**
15885 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
15886 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
15887 * calculated and maintained when the menu is toggled or the window is resized.
15888 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
15889 *
15890 * @class
15891 * @extends OO.ui.MenuSelectWidget
15892 *
15893 * @constructor
15894 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
15895 * @param {Object} [config] Configuration options
15896 * @cfg {jQuery} [$container=input.$element] Element to render menu under
15897 */
15898 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
15899 // Allow passing positional parameters inside the config object
15900 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
15901 config = inputWidget;
15902 inputWidget = config.inputWidget;
15903 }
15904
15905 // Configuration initialization
15906 config = config || {};
15907
15908 // Parent constructor
15909 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
15910
15911 // Properties
15912 this.inputWidget = inputWidget;
15913 this.$container = config.$container || this.inputWidget.$element;
15914 this.onWindowResizeHandler = this.onWindowResize.bind( this );
15915
15916 // Initialization
15917 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
15918 };
15919
15920 /* Setup */
15921
15922 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
15923
15924 /* Methods */
15925
15926 /**
15927 * Handle window resize event.
15928 *
15929 * @private
15930 * @param {jQuery.Event} e Window resize event
15931 */
15932 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
15933 this.position();
15934 };
15935
15936 /**
15937 * @inheritdoc
15938 */
15939 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
15940 visible = visible === undefined ? !this.isVisible() : !!visible;
15941
15942 var change = visible !== this.isVisible();
15943
15944 if ( change && visible ) {
15945 // Make sure the width is set before the parent method runs.
15946 // After this we have to call this.position(); again to actually
15947 // position ourselves correctly.
15948 this.position();
15949 }
15950
15951 // Parent method
15952 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
15953
15954 if ( change ) {
15955 if ( this.isVisible() ) {
15956 this.position();
15957 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
15958 } else {
15959 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
15960 }
15961 }
15962
15963 return this;
15964 };
15965
15966 /**
15967 * Position the menu.
15968 *
15969 * @private
15970 * @chainable
15971 */
15972 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
15973 var $container = this.$container,
15974 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
15975
15976 // Position under input
15977 pos.top += $container.height();
15978 this.$element.css( pos );
15979
15980 // Set width
15981 this.setIdealSize( $container.width() );
15982 // We updated the position, so re-evaluate the clipping state
15983 this.clip();
15984
15985 return this;
15986 };
15987
15988 /**
15989 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
15990 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
15991 *
15992 * ####Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.####
15993 *
15994 * @class
15995 * @extends OO.ui.SelectWidget
15996 * @mixins OO.ui.TabIndexedElement
15997 *
15998 * @constructor
15999 * @param {Object} [config] Configuration options
16000 */
16001 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
16002 // Parent constructor
16003 OO.ui.OutlineSelectWidget.super.call( this, config );
16004
16005 // Mixin constructors
16006 OO.ui.TabIndexedElement.call( this, config );
16007
16008 // Events
16009 this.$element.on( {
16010 focus: this.bindKeyDownListener.bind( this ),
16011 blur: this.unbindKeyDownListener.bind( this )
16012 } );
16013
16014 // Initialization
16015 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
16016 };
16017
16018 /* Setup */
16019
16020 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
16021 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
16022
16023 /**
16024 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
16025 *
16026 * ####Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.####
16027 *
16028 * @class
16029 * @extends OO.ui.SelectWidget
16030 * @mixins OO.ui.TabIndexedElement
16031 *
16032 * @constructor
16033 * @param {Object} [config] Configuration options
16034 */
16035 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
16036 // Parent constructor
16037 OO.ui.TabSelectWidget.super.call( this, config );
16038
16039 // Mixin constructors
16040 OO.ui.TabIndexedElement.call( this, config );
16041
16042 // Events
16043 this.$element.on( {
16044 focus: this.bindKeyDownListener.bind( this ),
16045 blur: this.unbindKeyDownListener.bind( this )
16046 } );
16047
16048 // Initialization
16049 this.$element.addClass( 'oo-ui-tabSelectWidget' );
16050 };
16051
16052 /* Setup */
16053
16054 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
16055 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.TabIndexedElement );
16056
16057 /**
16058 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
16059 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
16060 * visually by a slider in the leftmost position.
16061 *
16062 * @example
16063 * // Toggle switches in the 'off' and 'on' position.
16064 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
16065 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
16066 * value: true
16067 * } );
16068 *
16069 * // Create a FieldsetLayout to layout and label switches
16070 * var fieldset = new OO.ui.FieldsetLayout( {
16071 * label: 'Toggle switches'
16072 * } );
16073 * fieldset.addItems( [
16074 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
16075 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
16076 * ] );
16077 * $( 'body' ).append( fieldset.$element );
16078 *
16079 * @class
16080 * @extends OO.ui.ToggleWidget
16081 * @mixins OO.ui.TabIndexedElement
16082 *
16083 * @constructor
16084 * @param {Object} [config] Configuration options
16085 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
16086 * By default, the toggle switch is in the 'off' position.
16087 */
16088 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
16089 // Parent constructor
16090 OO.ui.ToggleSwitchWidget.super.call( this, config );
16091
16092 // Mixin constructors
16093 OO.ui.TabIndexedElement.call( this, config );
16094
16095 // Properties
16096 this.dragging = false;
16097 this.dragStart = null;
16098 this.sliding = false;
16099 this.$glow = $( '<span>' );
16100 this.$grip = $( '<span>' );
16101
16102 // Events
16103 this.$element.on( {
16104 click: this.onClick.bind( this ),
16105 keypress: this.onKeyPress.bind( this )
16106 } );
16107
16108 // Initialization
16109 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
16110 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
16111 this.$element
16112 .addClass( 'oo-ui-toggleSwitchWidget' )
16113 .attr( 'role', 'checkbox' )
16114 .append( this.$glow, this.$grip );
16115 };
16116
16117 /* Setup */
16118
16119 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
16120 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
16121
16122 /* Methods */
16123
16124 /**
16125 * Handle mouse click events.
16126 *
16127 * @private
16128 * @param {jQuery.Event} e Mouse click event
16129 */
16130 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
16131 if ( !this.isDisabled() && e.which === 1 ) {
16132 this.setValue( !this.value );
16133 }
16134 return false;
16135 };
16136
16137 /**
16138 * Handle key press events.
16139 *
16140 * @private
16141 * @param {jQuery.Event} e Key press event
16142 */
16143 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
16144 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
16145 this.setValue( !this.value );
16146 return false;
16147 }
16148 };
16149
16150 }( OO ) );