Make AuthManager::getAuthenticationProvider() public
[mediawiki.git] / resources / lib / oojs-ui / oojs-ui-windows.js
blob17bab019c511fb8a8fd464e4960057df09faac27
1 /*!
2 * OOjs UI v0.17.4
3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-05-31T21:50:52Z
11 ( function ( OO ) {
13 'use strict';
15 /**
16 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
17 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
18 * of the actions.
20 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
21 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
22 * and examples.
24 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
26 * @class
27 * @extends OO.ui.ButtonWidget
28 * @mixins OO.ui.mixin.PendingElement
30 * @constructor
31 * @param {Object} [config] Configuration options
32 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
33 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
34 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
35 * for more information about setting modes.
36 * @cfg {boolean} [framed=false] Render the action button with a frame
38 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
39 // Configuration initialization
40 config = $.extend( { framed: false }, config );
42 // Parent constructor
43 OO.ui.ActionWidget.parent.call( this, config );
45 // Mixin constructors
46 OO.ui.mixin.PendingElement.call( this, config );
48 // Properties
49 this.action = config.action || '';
50 this.modes = config.modes || [];
51 this.width = 0;
52 this.height = 0;
54 // Initialization
55 this.$element.addClass( 'oo-ui-actionWidget' );
58 /* Setup */
60 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
61 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
63 /* Events */
65 /**
66 * A resize event is emitted when the size of the widget changes.
68 * @event resize
71 /* Methods */
73 /**
74 * Check if the action is configured to be available in the specified `mode`.
76 * @param {string} mode Name of mode
77 * @return {boolean} The action is configured with the mode
79 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
80 return this.modes.indexOf( mode ) !== -1;
83 /**
84 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
86 * @return {string}
88 OO.ui.ActionWidget.prototype.getAction = function () {
89 return this.action;
92 /**
93 * Get the symbolic name of the mode or modes for which the action is configured to be available.
95 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
96 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
97 * are hidden.
99 * @return {string[]}
101 OO.ui.ActionWidget.prototype.getModes = function () {
102 return this.modes.slice();
106 * Emit a resize event if the size has changed.
108 * @private
109 * @chainable
111 OO.ui.ActionWidget.prototype.propagateResize = function () {
112 var width, height;
114 if ( this.isElementAttached() ) {
115 width = this.$element.width();
116 height = this.$element.height();
118 if ( width !== this.width || height !== this.height ) {
119 this.width = width;
120 this.height = height;
121 this.emit( 'resize' );
125 return this;
129 * @inheritdoc
131 OO.ui.ActionWidget.prototype.setIcon = function () {
132 // Mixin method
133 OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments );
134 this.propagateResize();
136 return this;
140 * @inheritdoc
142 OO.ui.ActionWidget.prototype.setLabel = function () {
143 // Mixin method
144 OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments );
145 this.propagateResize();
147 return this;
151 * @inheritdoc
153 OO.ui.ActionWidget.prototype.setFlags = function () {
154 // Mixin method
155 OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments );
156 this.propagateResize();
158 return this;
162 * @inheritdoc
164 OO.ui.ActionWidget.prototype.clearFlags = function () {
165 // Mixin method
166 OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments );
167 this.propagateResize();
169 return this;
173 * Toggle the visibility of the action button.
175 * @param {boolean} [show] Show button, omit to toggle visibility
176 * @chainable
178 OO.ui.ActionWidget.prototype.toggle = function () {
179 // Parent method
180 OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments );
181 this.propagateResize();
183 return this;
187 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
188 * Actions can be made available for specific contexts (modes) and circumstances
189 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
191 * ActionSets contain two types of actions:
193 * - 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.
194 * - Other: Other actions include all non-special visible actions.
196 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
198 * @example
199 * // Example: An action set used in a process dialog
200 * function MyProcessDialog( config ) {
201 * MyProcessDialog.parent.call( this, config );
203 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
204 * MyProcessDialog.static.title = 'An action set in a process dialog';
205 * // An action set that uses modes ('edit' and 'help' mode, in this example).
206 * MyProcessDialog.static.actions = [
207 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
208 * { action: 'help', modes: 'edit', label: 'Help' },
209 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
210 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
211 * ];
213 * MyProcessDialog.prototype.initialize = function () {
214 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
215 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
216 * 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>' );
217 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
218 * 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>' );
219 * this.stackLayout = new OO.ui.StackLayout( {
220 * items: [ this.panel1, this.panel2 ]
221 * } );
222 * this.$body.append( this.stackLayout.$element );
223 * };
224 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
225 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
226 * .next( function () {
227 * this.actions.setMode( 'edit' );
228 * }, this );
229 * };
230 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
231 * if ( action === 'help' ) {
232 * this.actions.setMode( 'help' );
233 * this.stackLayout.setItem( this.panel2 );
234 * } else if ( action === 'back' ) {
235 * this.actions.setMode( 'edit' );
236 * this.stackLayout.setItem( this.panel1 );
237 * } else if ( action === 'continue' ) {
238 * var dialog = this;
239 * return new OO.ui.Process( function () {
240 * dialog.close();
241 * } );
243 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
244 * };
245 * MyProcessDialog.prototype.getBodyHeight = function () {
246 * return this.panel1.$element.outerHeight( true );
247 * };
248 * var windowManager = new OO.ui.WindowManager();
249 * $( 'body' ).append( windowManager.$element );
250 * var dialog = new MyProcessDialog( {
251 * size: 'medium'
252 * } );
253 * windowManager.addWindows( [ dialog ] );
254 * windowManager.openWindow( dialog );
256 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
258 * @abstract
259 * @class
260 * @mixins OO.EventEmitter
262 * @constructor
263 * @param {Object} [config] Configuration options
265 OO.ui.ActionSet = function OoUiActionSet( config ) {
266 // Configuration initialization
267 config = config || {};
269 // Mixin constructors
270 OO.EventEmitter.call( this );
272 // Properties
273 this.list = [];
274 this.categories = {
275 actions: 'getAction',
276 flags: 'getFlags',
277 modes: 'getModes'
279 this.categorized = {};
280 this.special = {};
281 this.others = [];
282 this.organized = false;
283 this.changing = false;
284 this.changed = false;
287 /* Setup */
289 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
291 /* Static Properties */
294 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
295 * header of a {@link OO.ui.ProcessDialog process dialog}.
296 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
298 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
300 * @abstract
301 * @static
302 * @inheritable
303 * @property {string}
305 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
307 /* Events */
310 * @event click
312 * A 'click' event is emitted when an action is clicked.
314 * @param {OO.ui.ActionWidget} action Action that was clicked
318 * @event resize
320 * A 'resize' event is emitted when an action widget is resized.
322 * @param {OO.ui.ActionWidget} action Action that was resized
326 * @event add
328 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
330 * @param {OO.ui.ActionWidget[]} added Actions added
334 * @event remove
336 * A 'remove' event is emitted when actions are {@link #method-remove removed}
337 * or {@link #clear cleared}.
339 * @param {OO.ui.ActionWidget[]} added Actions removed
343 * @event change
345 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
346 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
350 /* Methods */
353 * Handle action change events.
355 * @private
356 * @fires change
358 OO.ui.ActionSet.prototype.onActionChange = function () {
359 this.organized = false;
360 if ( this.changing ) {
361 this.changed = true;
362 } else {
363 this.emit( 'change' );
368 * Check if an action is one of the special actions.
370 * @param {OO.ui.ActionWidget} action Action to check
371 * @return {boolean} Action is special
373 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
374 var flag;
376 for ( flag in this.special ) {
377 if ( action === this.special[ flag ] ) {
378 return true;
382 return false;
386 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
387 * or ‘disabled’.
389 * @param {Object} [filters] Filters to use, omit to get all actions
390 * @param {string|string[]} [filters.actions] Actions that action widgets must have
391 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
392 * @param {string|string[]} [filters.modes] Modes that action widgets must have
393 * @param {boolean} [filters.visible] Action widgets must be visible
394 * @param {boolean} [filters.disabled] Action widgets must be disabled
395 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
397 OO.ui.ActionSet.prototype.get = function ( filters ) {
398 var i, len, list, category, actions, index, match, matches;
400 if ( filters ) {
401 this.organize();
403 // Collect category candidates
404 matches = [];
405 for ( category in this.categorized ) {
406 list = filters[ category ];
407 if ( list ) {
408 if ( !Array.isArray( list ) ) {
409 list = [ list ];
411 for ( i = 0, len = list.length; i < len; i++ ) {
412 actions = this.categorized[ category ][ list[ i ] ];
413 if ( Array.isArray( actions ) ) {
414 matches.push.apply( matches, actions );
419 // Remove by boolean filters
420 for ( i = 0, len = matches.length; i < len; i++ ) {
421 match = matches[ i ];
422 if (
423 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
424 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
426 matches.splice( i, 1 );
427 len--;
428 i--;
431 // Remove duplicates
432 for ( i = 0, len = matches.length; i < len; i++ ) {
433 match = matches[ i ];
434 index = matches.lastIndexOf( match );
435 while ( index !== i ) {
436 matches.splice( index, 1 );
437 len--;
438 index = matches.lastIndexOf( match );
441 return matches;
443 return this.list.slice();
447 * Get 'special' actions.
449 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
450 * Special flags can be configured in subclasses by changing the static #specialFlags property.
452 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
454 OO.ui.ActionSet.prototype.getSpecial = function () {
455 this.organize();
456 return $.extend( {}, this.special );
460 * Get 'other' actions.
462 * Other actions include all non-special visible action widgets.
464 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
466 OO.ui.ActionSet.prototype.getOthers = function () {
467 this.organize();
468 return this.others.slice();
472 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
473 * to be available in the specified mode will be made visible. All other actions will be hidden.
475 * @param {string} mode The mode. Only actions configured to be available in the specified
476 * mode will be made visible.
477 * @chainable
478 * @fires toggle
479 * @fires change
481 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
482 var i, len, action;
484 this.changing = true;
485 for ( i = 0, len = this.list.length; i < len; i++ ) {
486 action = this.list[ i ];
487 action.toggle( action.hasMode( mode ) );
490 this.organized = false;
491 this.changing = false;
492 this.emit( 'change' );
494 return this;
498 * Set the abilities of the specified actions.
500 * Action widgets that are configured with the specified actions will be enabled
501 * or disabled based on the boolean values specified in the `actions`
502 * parameter.
504 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
505 * values that indicate whether or not the action should be enabled.
506 * @chainable
508 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
509 var i, len, action, item;
511 for ( i = 0, len = this.list.length; i < len; i++ ) {
512 item = this.list[ i ];
513 action = item.getAction();
514 if ( actions[ action ] !== undefined ) {
515 item.setDisabled( !actions[ action ] );
519 return this;
523 * Executes a function once per action.
525 * When making changes to multiple actions, use this method instead of iterating over the actions
526 * manually to defer emitting a #change event until after all actions have been changed.
528 * @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
529 * @param {Function} callback Callback to run for each action; callback is invoked with three
530 * arguments: the action, the action's index, the list of actions being iterated over
531 * @chainable
533 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
534 this.changed = false;
535 this.changing = true;
536 this.get( filter ).forEach( callback );
537 this.changing = false;
538 if ( this.changed ) {
539 this.emit( 'change' );
542 return this;
546 * Add action widgets to the action set.
548 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
549 * @chainable
550 * @fires add
551 * @fires change
553 OO.ui.ActionSet.prototype.add = function ( actions ) {
554 var i, len, action;
556 this.changing = true;
557 for ( i = 0, len = actions.length; i < len; i++ ) {
558 action = actions[ i ];
559 action.connect( this, {
560 click: [ 'emit', 'click', action ],
561 resize: [ 'emit', 'resize', action ],
562 toggle: [ 'onActionChange' ]
563 } );
564 this.list.push( action );
566 this.organized = false;
567 this.emit( 'add', actions );
568 this.changing = false;
569 this.emit( 'change' );
571 return this;
575 * Remove action widgets from the set.
577 * To remove all actions, you may wish to use the #clear method instead.
579 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
580 * @chainable
581 * @fires remove
582 * @fires change
584 OO.ui.ActionSet.prototype.remove = function ( actions ) {
585 var i, len, index, action;
587 this.changing = true;
588 for ( i = 0, len = actions.length; i < len; i++ ) {
589 action = actions[ i ];
590 index = this.list.indexOf( action );
591 if ( index !== -1 ) {
592 action.disconnect( this );
593 this.list.splice( index, 1 );
596 this.organized = false;
597 this.emit( 'remove', actions );
598 this.changing = false;
599 this.emit( 'change' );
601 return this;
605 * Remove all action widets from the set.
607 * To remove only specified actions, use the {@link #method-remove remove} method instead.
609 * @chainable
610 * @fires remove
611 * @fires change
613 OO.ui.ActionSet.prototype.clear = function () {
614 var i, len, action,
615 removed = this.list.slice();
617 this.changing = true;
618 for ( i = 0, len = this.list.length; i < len; i++ ) {
619 action = this.list[ i ];
620 action.disconnect( this );
623 this.list = [];
625 this.organized = false;
626 this.emit( 'remove', removed );
627 this.changing = false;
628 this.emit( 'change' );
630 return this;
634 * Organize actions.
636 * This is called whenever organized information is requested. It will only reorganize the actions
637 * if something has changed since the last time it ran.
639 * @private
640 * @chainable
642 OO.ui.ActionSet.prototype.organize = function () {
643 var i, iLen, j, jLen, flag, action, category, list, item, special,
644 specialFlags = this.constructor.static.specialFlags;
646 if ( !this.organized ) {
647 this.categorized = {};
648 this.special = {};
649 this.others = [];
650 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
651 action = this.list[ i ];
652 if ( action.isVisible() ) {
653 // Populate categories
654 for ( category in this.categories ) {
655 if ( !this.categorized[ category ] ) {
656 this.categorized[ category ] = {};
658 list = action[ this.categories[ category ] ]();
659 if ( !Array.isArray( list ) ) {
660 list = [ list ];
662 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
663 item = list[ j ];
664 if ( !this.categorized[ category ][ item ] ) {
665 this.categorized[ category ][ item ] = [];
667 this.categorized[ category ][ item ].push( action );
670 // Populate special/others
671 special = false;
672 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
673 flag = specialFlags[ j ];
674 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
675 this.special[ flag ] = action;
676 special = true;
677 break;
680 if ( !special ) {
681 this.others.push( action );
685 this.organized = true;
688 return this;
692 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
693 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
694 * appearance and functionality of the error interface.
696 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
697 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
698 * that initiated the failed process will be disabled.
700 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
701 * process again.
703 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
705 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
707 * @class
709 * @constructor
710 * @param {string|jQuery} message Description of error
711 * @param {Object} [config] Configuration options
712 * @cfg {boolean} [recoverable=true] Error is recoverable.
713 * By default, errors are recoverable, and users can try the process again.
714 * @cfg {boolean} [warning=false] Error is a warning.
715 * If the error is a warning, the error interface will include a
716 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
717 * is not triggered a second time if the user chooses to continue.
719 OO.ui.Error = function OoUiError( message, config ) {
720 // Allow passing positional parameters inside the config object
721 if ( OO.isPlainObject( message ) && config === undefined ) {
722 config = message;
723 message = config.message;
726 // Configuration initialization
727 config = config || {};
729 // Properties
730 this.message = message instanceof jQuery ? message : String( message );
731 this.recoverable = config.recoverable === undefined || !!config.recoverable;
732 this.warning = !!config.warning;
735 /* Setup */
737 OO.initClass( OO.ui.Error );
739 /* Methods */
742 * Check if the error is recoverable.
744 * If the error is recoverable, users are able to try the process again.
746 * @return {boolean} Error is recoverable
748 OO.ui.Error.prototype.isRecoverable = function () {
749 return this.recoverable;
753 * Check if the error is a warning.
755 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
757 * @return {boolean} Error is warning
759 OO.ui.Error.prototype.isWarning = function () {
760 return this.warning;
764 * Get error message as DOM nodes.
766 * @return {jQuery} Error message in DOM nodes
768 OO.ui.Error.prototype.getMessage = function () {
769 return this.message instanceof jQuery ?
770 this.message.clone() :
771 $( '<div>' ).text( this.message ).contents();
775 * Get the error message text.
777 * @return {string} Error message
779 OO.ui.Error.prototype.getMessageText = function () {
780 return this.message instanceof jQuery ? this.message.text() : this.message;
784 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
785 * or a function:
787 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
788 * - **promise**: the process will continue to the next step when the promise is successfully resolved
789 * or stop if the promise is rejected.
790 * - **function**: the process will execute the function. The process will stop if the function returns
791 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
792 * will wait for that number of milliseconds before proceeding.
794 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
795 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
796 * its remaining steps will not be performed.
798 * @class
800 * @constructor
801 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
802 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
803 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
804 * a number or promise.
805 * @return {Object} Step object, with `callback` and `context` properties
807 OO.ui.Process = function ( step, context ) {
808 // Properties
809 this.steps = [];
811 // Initialization
812 if ( step !== undefined ) {
813 this.next( step, context );
817 /* Setup */
819 OO.initClass( OO.ui.Process );
821 /* Methods */
824 * Start the process.
826 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
827 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
828 * and any remaining steps are not performed.
830 OO.ui.Process.prototype.execute = function () {
831 var i, len, promise;
834 * Continue execution.
836 * @ignore
837 * @param {Array} step A function and the context it should be called in
838 * @return {Function} Function that continues the process
840 function proceed( step ) {
841 return function () {
842 // Execute step in the correct context
843 var deferred,
844 result = step.callback.call( step.context );
846 if ( result === false ) {
847 // Use rejected promise for boolean false results
848 return $.Deferred().reject( [] ).promise();
850 if ( typeof result === 'number' ) {
851 if ( result < 0 ) {
852 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
854 // Use a delayed promise for numbers, expecting them to be in milliseconds
855 deferred = $.Deferred();
856 setTimeout( deferred.resolve, result );
857 return deferred.promise();
859 if ( result instanceof OO.ui.Error ) {
860 // Use rejected promise for error
861 return $.Deferred().reject( [ result ] ).promise();
863 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
864 // Use rejected promise for list of errors
865 return $.Deferred().reject( result ).promise();
867 // Duck-type the object to see if it can produce a promise
868 if ( result && $.isFunction( result.promise ) ) {
869 // Use a promise generated from the result
870 return result.promise();
872 // Use resolved promise for other results
873 return $.Deferred().resolve().promise();
877 if ( this.steps.length ) {
878 // Generate a chain reaction of promises
879 promise = proceed( this.steps[ 0 ] )();
880 for ( i = 1, len = this.steps.length; i < len; i++ ) {
881 promise = promise.then( proceed( this.steps[ i ] ) );
883 } else {
884 promise = $.Deferred().resolve().promise();
887 return promise;
891 * Create a process step.
893 * @private
894 * @param {number|jQuery.Promise|Function} step
896 * - Number of milliseconds to wait before proceeding
897 * - Promise that must be resolved before proceeding
898 * - Function to execute
899 * - If the function returns a boolean false the process will stop
900 * - If the function returns a promise, the process will continue to the next
901 * step when the promise is resolved or stop if the promise is rejected
902 * - If the function returns a number, the process will wait for that number of
903 * milliseconds before proceeding
904 * @param {Object} [context=null] Execution context of the function. The context is
905 * ignored if the step is a number or promise.
906 * @return {Object} Step object, with `callback` and `context` properties
908 OO.ui.Process.prototype.createStep = function ( step, context ) {
909 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
910 return {
911 callback: function () {
912 return step;
914 context: null
917 if ( $.isFunction( step ) ) {
918 return {
919 callback: step,
920 context: context
923 throw new Error( 'Cannot create process step: number, promise or function expected' );
927 * Add step to the beginning of the process.
929 * @inheritdoc #createStep
930 * @return {OO.ui.Process} this
931 * @chainable
933 OO.ui.Process.prototype.first = function ( step, context ) {
934 this.steps.unshift( this.createStep( step, context ) );
935 return this;
939 * Add step to the end of the process.
941 * @inheritdoc #createStep
942 * @return {OO.ui.Process} this
943 * @chainable
945 OO.ui.Process.prototype.next = function ( step, context ) {
946 this.steps.push( this.createStep( step, context ) );
947 return this;
951 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
952 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
953 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
954 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
955 * pertinent data and reused.
957 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
958 * `opened`, and `closing`, which represent the primary stages of the cycle:
960 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
961 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
963 * - an `opening` event is emitted with an `opening` promise
964 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
965 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
966 * window and its result executed
967 * - a `setup` progress notification is emitted from the `opening` promise
968 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
969 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
970 * window and its result executed
971 * - a `ready` progress notification is emitted from the `opening` promise
972 * - the `opening` promise is resolved with an `opened` promise
974 * **Opened**: the window is now open.
976 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
977 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
978 * to close the window.
980 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
981 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
982 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
983 * window and its result executed
984 * - a `hold` progress notification is emitted from the `closing` promise
985 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
986 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
987 * window and its result executed
988 * - a `teardown` progress notification is emitted from the `closing` promise
989 * - the `closing` promise is resolved. The window is now closed
991 * See the [OOjs UI documentation on MediaWiki][1] for more information.
993 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
995 * @class
996 * @extends OO.ui.Element
997 * @mixins OO.EventEmitter
999 * @constructor
1000 * @param {Object} [config] Configuration options
1001 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
1002 * Note that window classes that are instantiated with a factory must have
1003 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
1004 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
1006 OO.ui.WindowManager = function OoUiWindowManager( config ) {
1007 // Configuration initialization
1008 config = config || {};
1010 // Parent constructor
1011 OO.ui.WindowManager.parent.call( this, config );
1013 // Mixin constructors
1014 OO.EventEmitter.call( this );
1016 // Properties
1017 this.factory = config.factory;
1018 this.modal = config.modal === undefined || !!config.modal;
1019 this.windows = {};
1020 this.opening = null;
1021 this.opened = null;
1022 this.closing = null;
1023 this.preparingToOpen = null;
1024 this.preparingToClose = null;
1025 this.currentWindow = null;
1026 this.globalEvents = false;
1027 this.$ariaHidden = null;
1028 this.onWindowResizeTimeout = null;
1029 this.onWindowResizeHandler = this.onWindowResize.bind( this );
1030 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
1032 // Initialization
1033 this.$element
1034 .addClass( 'oo-ui-windowManager' )
1035 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
1038 /* Setup */
1040 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
1041 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
1043 /* Events */
1046 * An 'opening' event is emitted when the window begins to be opened.
1048 * @event opening
1049 * @param {OO.ui.Window} win Window that's being opened
1050 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
1051 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
1052 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
1053 * @param {Object} data Window opening data
1057 * A 'closing' event is emitted when the window begins to be closed.
1059 * @event closing
1060 * @param {OO.ui.Window} win Window that's being closed
1061 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
1062 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
1063 * processes are complete. When the `closing` promise is resolved, the first argument of its value
1064 * is the closing data.
1065 * @param {Object} data Window closing data
1069 * A 'resize' event is emitted when a window is resized.
1071 * @event resize
1072 * @param {OO.ui.Window} win Window that was resized
1075 /* Static Properties */
1078 * Map of the symbolic name of each window size and its CSS properties.
1080 * @static
1081 * @inheritable
1082 * @property {Object}
1084 OO.ui.WindowManager.static.sizes = {
1085 small: {
1086 width: 300
1088 medium: {
1089 width: 500
1091 large: {
1092 width: 700
1094 larger: {
1095 width: 900
1097 full: {
1098 // These can be non-numeric because they are never used in calculations
1099 width: '100%',
1100 height: '100%'
1105 * Symbolic name of the default window size.
1107 * The default size is used if the window's requested size is not recognized.
1109 * @static
1110 * @inheritable
1111 * @property {string}
1113 OO.ui.WindowManager.static.defaultSize = 'medium';
1115 /* Methods */
1118 * Handle window resize events.
1120 * @private
1121 * @param {jQuery.Event} e Window resize event
1123 OO.ui.WindowManager.prototype.onWindowResize = function () {
1124 clearTimeout( this.onWindowResizeTimeout );
1125 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
1129 * Handle window resize events.
1131 * @private
1132 * @param {jQuery.Event} e Window resize event
1134 OO.ui.WindowManager.prototype.afterWindowResize = function () {
1135 if ( this.currentWindow ) {
1136 this.updateWindowSize( this.currentWindow );
1141 * Check if window is opening.
1143 * @return {boolean} Window is opening
1145 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
1146 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
1150 * Check if window is closing.
1152 * @return {boolean} Window is closing
1154 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
1155 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
1159 * Check if window is opened.
1161 * @return {boolean} Window is opened
1163 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
1164 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
1168 * Check if a window is being managed.
1170 * @param {OO.ui.Window} win Window to check
1171 * @return {boolean} Window is being managed
1173 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
1174 var name;
1176 for ( name in this.windows ) {
1177 if ( this.windows[ name ] === win ) {
1178 return true;
1182 return false;
1186 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
1188 * @param {OO.ui.Window} win Window being opened
1189 * @param {Object} [data] Window opening data
1190 * @return {number} Milliseconds to wait
1192 OO.ui.WindowManager.prototype.getSetupDelay = function () {
1193 return 0;
1197 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
1199 * @param {OO.ui.Window} win Window being opened
1200 * @param {Object} [data] Window opening data
1201 * @return {number} Milliseconds to wait
1203 OO.ui.WindowManager.prototype.getReadyDelay = function () {
1204 return 0;
1208 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
1210 * @param {OO.ui.Window} win Window being closed
1211 * @param {Object} [data] Window closing data
1212 * @return {number} Milliseconds to wait
1214 OO.ui.WindowManager.prototype.getHoldDelay = function () {
1215 return 0;
1219 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
1220 * executing the ‘teardown’ process.
1222 * @param {OO.ui.Window} win Window being closed
1223 * @param {Object} [data] Window closing data
1224 * @return {number} Milliseconds to wait
1226 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
1227 return this.modal ? 250 : 0;
1231 * Get a window by its symbolic name.
1233 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
1234 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
1235 * for more information about using factories.
1236 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
1238 * @param {string} name Symbolic name of the window
1239 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
1240 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
1241 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
1243 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
1244 var deferred = $.Deferred(),
1245 win = this.windows[ name ];
1247 if ( !( win instanceof OO.ui.Window ) ) {
1248 if ( this.factory ) {
1249 if ( !this.factory.lookup( name ) ) {
1250 deferred.reject( new OO.ui.Error(
1251 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
1252 ) );
1253 } else {
1254 win = this.factory.create( name );
1255 this.addWindows( [ win ] );
1256 deferred.resolve( win );
1258 } else {
1259 deferred.reject( new OO.ui.Error(
1260 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
1261 ) );
1263 } else {
1264 deferred.resolve( win );
1267 return deferred.promise();
1271 * Get current window.
1273 * @return {OO.ui.Window|null} Currently opening/opened/closing window
1275 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
1276 return this.currentWindow;
1280 * Open a window.
1282 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
1283 * @param {Object} [data] Window opening data
1284 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
1285 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
1286 * @fires opening
1288 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
1289 var manager = this,
1290 opening = $.Deferred();
1292 // Argument handling
1293 if ( typeof win === 'string' ) {
1294 return this.getWindow( win ).then( function ( win ) {
1295 return manager.openWindow( win, data );
1296 } );
1299 // Error handling
1300 if ( !this.hasWindow( win ) ) {
1301 opening.reject( new OO.ui.Error(
1302 'Cannot open window: window is not attached to manager'
1303 ) );
1304 } else if ( this.preparingToOpen || this.opening || this.opened ) {
1305 opening.reject( new OO.ui.Error(
1306 'Cannot open window: another window is opening or open'
1307 ) );
1310 // Window opening
1311 if ( opening.state() !== 'rejected' ) {
1312 // If a window is currently closing, wait for it to complete
1313 this.preparingToOpen = $.when( this.closing );
1314 // Ensure handlers get called after preparingToOpen is set
1315 this.preparingToOpen.done( function () {
1316 if ( manager.modal ) {
1317 manager.toggleGlobalEvents( true );
1318 manager.toggleAriaIsolation( true );
1320 manager.currentWindow = win;
1321 manager.opening = opening;
1322 manager.preparingToOpen = null;
1323 manager.emit( 'opening', win, opening, data );
1324 setTimeout( function () {
1325 win.setup( data ).then( function () {
1326 manager.updateWindowSize( win );
1327 manager.opening.notify( { state: 'setup' } );
1328 setTimeout( function () {
1329 win.ready( data ).then( function () {
1330 manager.opening.notify( { state: 'ready' } );
1331 manager.opening = null;
1332 manager.opened = $.Deferred();
1333 opening.resolve( manager.opened.promise(), data );
1334 }, function () {
1335 manager.opening = null;
1336 manager.opened = $.Deferred();
1337 opening.reject();
1338 manager.closeWindow( win );
1339 } );
1340 }, manager.getReadyDelay() );
1341 }, function () {
1342 manager.opening = null;
1343 manager.opened = $.Deferred();
1344 opening.reject();
1345 manager.closeWindow( win );
1346 } );
1347 }, manager.getSetupDelay() );
1348 } );
1351 return opening.promise();
1355 * Close a window.
1357 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
1358 * @param {Object} [data] Window closing data
1359 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
1360 * See {@link #event-closing 'closing' event} for more information about closing promises.
1361 * @throws {Error} An error is thrown if the window is not managed by the window manager.
1362 * @fires closing
1364 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
1365 var manager = this,
1366 closing = $.Deferred(),
1367 opened;
1369 // Argument handling
1370 if ( typeof win === 'string' ) {
1371 win = this.windows[ win ];
1372 } else if ( !this.hasWindow( win ) ) {
1373 win = null;
1376 // Error handling
1377 if ( !win ) {
1378 closing.reject( new OO.ui.Error(
1379 'Cannot close window: window is not attached to manager'
1380 ) );
1381 } else if ( win !== this.currentWindow ) {
1382 closing.reject( new OO.ui.Error(
1383 'Cannot close window: window already closed with different data'
1384 ) );
1385 } else if ( this.preparingToClose || this.closing ) {
1386 closing.reject( new OO.ui.Error(
1387 'Cannot close window: window already closing with different data'
1388 ) );
1391 // Window closing
1392 if ( closing.state() !== 'rejected' ) {
1393 // If the window is currently opening, close it when it's done
1394 this.preparingToClose = $.when( this.opening );
1395 // Ensure handlers get called after preparingToClose is set
1396 this.preparingToClose.always( function () {
1397 manager.closing = closing;
1398 manager.preparingToClose = null;
1399 manager.emit( 'closing', win, closing, data );
1400 opened = manager.opened;
1401 manager.opened = null;
1402 opened.resolve( closing.promise(), data );
1403 setTimeout( function () {
1404 win.hold( data ).then( function () {
1405 closing.notify( { state: 'hold' } );
1406 setTimeout( function () {
1407 win.teardown( data ).then( function () {
1408 closing.notify( { state: 'teardown' } );
1409 if ( manager.modal ) {
1410 manager.toggleGlobalEvents( false );
1411 manager.toggleAriaIsolation( false );
1413 manager.closing = null;
1414 manager.currentWindow = null;
1415 closing.resolve( data );
1416 } );
1417 }, manager.getTeardownDelay() );
1418 } );
1419 }, manager.getHoldDelay() );
1420 } );
1423 return closing.promise();
1427 * Add windows to the window manager.
1429 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
1430 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
1431 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
1433 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
1434 * by reference, symbolic name, or explicitly defined symbolic names.
1435 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
1436 * explicit nor a statically configured symbolic name.
1438 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
1439 var i, len, win, name, list;
1441 if ( Array.isArray( windows ) ) {
1442 // Convert to map of windows by looking up symbolic names from static configuration
1443 list = {};
1444 for ( i = 0, len = windows.length; i < len; i++ ) {
1445 name = windows[ i ].constructor.static.name;
1446 if ( typeof name !== 'string' ) {
1447 throw new Error( 'Cannot add window' );
1449 list[ name ] = windows[ i ];
1451 } else if ( OO.isPlainObject( windows ) ) {
1452 list = windows;
1455 // Add windows
1456 for ( name in list ) {
1457 win = list[ name ];
1458 this.windows[ name ] = win.toggle( false );
1459 this.$element.append( win.$element );
1460 win.setManager( this );
1465 * Remove the specified windows from the windows manager.
1467 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
1468 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
1469 * longer listens to events, use the #destroy method.
1471 * @param {string[]} names Symbolic names of windows to remove
1472 * @return {jQuery.Promise} Promise resolved when window is closed and removed
1473 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
1475 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
1476 var i, len, win, name, cleanupWindow,
1477 manager = this,
1478 promises = [],
1479 cleanup = function ( name, win ) {
1480 delete manager.windows[ name ];
1481 win.$element.detach();
1484 for ( i = 0, len = names.length; i < len; i++ ) {
1485 name = names[ i ];
1486 win = this.windows[ name ];
1487 if ( !win ) {
1488 throw new Error( 'Cannot remove window' );
1490 cleanupWindow = cleanup.bind( null, name, win );
1491 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
1494 return $.when.apply( $, promises );
1498 * Remove all windows from the window manager.
1500 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
1501 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
1502 * To remove just a subset of windows, use the #removeWindows method.
1504 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
1506 OO.ui.WindowManager.prototype.clearWindows = function () {
1507 return this.removeWindows( Object.keys( this.windows ) );
1511 * Set dialog size. In general, this method should not be called directly.
1513 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
1515 * @chainable
1517 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
1518 var isFullscreen;
1520 // Bypass for non-current, and thus invisible, windows
1521 if ( win !== this.currentWindow ) {
1522 return;
1525 isFullscreen = win.getSize() === 'full';
1527 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
1528 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
1529 win.setDimensions( win.getSizeProperties() );
1531 this.emit( 'resize', win );
1533 return this;
1537 * Bind or unbind global events for scrolling.
1539 * @private
1540 * @param {boolean} [on] Bind global events
1541 * @chainable
1543 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
1544 var scrollWidth, bodyMargin,
1545 $body = $( this.getElementDocument().body ),
1546 // We could have multiple window managers open so only modify
1547 // the body css at the bottom of the stack
1548 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
1550 on = on === undefined ? !!this.globalEvents : !!on;
1552 if ( on ) {
1553 if ( !this.globalEvents ) {
1554 $( this.getElementWindow() ).on( {
1555 // Start listening for top-level window dimension changes
1556 'orientationchange resize': this.onWindowResizeHandler
1557 } );
1558 if ( stackDepth === 0 ) {
1559 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
1560 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
1561 $body.css( {
1562 overflow: 'hidden',
1563 'margin-right': bodyMargin + scrollWidth
1564 } );
1566 stackDepth++;
1567 this.globalEvents = true;
1569 } else if ( this.globalEvents ) {
1570 $( this.getElementWindow() ).off( {
1571 // Stop listening for top-level window dimension changes
1572 'orientationchange resize': this.onWindowResizeHandler
1573 } );
1574 stackDepth--;
1575 if ( stackDepth === 0 ) {
1576 $body.css( {
1577 overflow: '',
1578 'margin-right': ''
1579 } );
1581 this.globalEvents = false;
1583 $body.data( 'windowManagerGlobalEvents', stackDepth );
1585 return this;
1589 * Toggle screen reader visibility of content other than the window manager.
1591 * @private
1592 * @param {boolean} [isolate] Make only the window manager visible to screen readers
1593 * @chainable
1595 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
1596 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
1598 if ( isolate ) {
1599 if ( !this.$ariaHidden ) {
1600 // Hide everything other than the window manager from screen readers
1601 this.$ariaHidden = $( 'body' )
1602 .children()
1603 .not( this.$element.parentsUntil( 'body' ).last() )
1604 .attr( 'aria-hidden', '' );
1606 } else if ( this.$ariaHidden ) {
1607 // Restore screen reader visibility
1608 this.$ariaHidden.removeAttr( 'aria-hidden' );
1609 this.$ariaHidden = null;
1612 return this;
1616 * Destroy the window manager.
1618 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
1619 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
1620 * instead.
1622 OO.ui.WindowManager.prototype.destroy = function () {
1623 this.toggleGlobalEvents( false );
1624 this.toggleAriaIsolation( false );
1625 this.clearWindows();
1626 this.$element.remove();
1630 * A window is a container for elements that are in a child frame. They are used with
1631 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1632 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1633 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1634 * the window manager will choose a sensible fallback.
1636 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1637 * different processes are executed:
1639 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1640 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1641 * the window.
1643 * - {@link #getSetupProcess} method is called and its result executed
1644 * - {@link #getReadyProcess} method is called and its result executed
1646 * **opened**: The window is now open
1648 * **closing**: The closing stage begins when the window manager's
1649 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1650 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1652 * - {@link #getHoldProcess} method is called and its result executed
1653 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1655 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1656 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1657 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1658 * processing can complete. Always assume window processes are executed asynchronously.
1660 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1662 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1664 * @abstract
1665 * @class
1666 * @extends OO.ui.Element
1667 * @mixins OO.EventEmitter
1669 * @constructor
1670 * @param {Object} [config] Configuration options
1671 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1672 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1674 OO.ui.Window = function OoUiWindow( config ) {
1675 // Configuration initialization
1676 config = config || {};
1678 // Parent constructor
1679 OO.ui.Window.parent.call( this, config );
1681 // Mixin constructors
1682 OO.EventEmitter.call( this );
1684 // Properties
1685 this.manager = null;
1686 this.size = config.size || this.constructor.static.size;
1687 this.$frame = $( '<div>' );
1688 this.$overlay = $( '<div>' );
1689 this.$content = $( '<div>' );
1691 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
1692 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
1693 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
1695 // Initialization
1696 this.$overlay.addClass( 'oo-ui-window-overlay' );
1697 this.$content
1698 .addClass( 'oo-ui-window-content' )
1699 .attr( 'tabindex', 0 );
1700 this.$frame
1701 .addClass( 'oo-ui-window-frame' )
1702 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
1704 this.$element
1705 .addClass( 'oo-ui-window' )
1706 .append( this.$frame, this.$overlay );
1708 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1709 // that reference properties not initialized at that time of parent class construction
1710 // TODO: Find a better way to handle post-constructor setup
1711 this.visible = false;
1712 this.$element.addClass( 'oo-ui-element-hidden' );
1715 /* Setup */
1717 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1718 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1720 /* Static Properties */
1723 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1725 * The static size is used if no #size is configured during construction.
1727 * @static
1728 * @inheritable
1729 * @property {string}
1731 OO.ui.Window.static.size = 'medium';
1733 /* Methods */
1736 * Handle mouse down events.
1738 * @private
1739 * @param {jQuery.Event} e Mouse down event
1741 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1742 // Prevent clicking on the click-block from stealing focus
1743 if ( e.target === this.$element[ 0 ] ) {
1744 return false;
1749 * Check if the window has been initialized.
1751 * Initialization occurs when a window is added to a manager.
1753 * @return {boolean} Window has been initialized
1755 OO.ui.Window.prototype.isInitialized = function () {
1756 return !!this.manager;
1760 * Check if the window is visible.
1762 * @return {boolean} Window is visible
1764 OO.ui.Window.prototype.isVisible = function () {
1765 return this.visible;
1769 * Check if the window is opening.
1771 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1772 * method.
1774 * @return {boolean} Window is opening
1776 OO.ui.Window.prototype.isOpening = function () {
1777 return this.manager.isOpening( this );
1781 * Check if the window is closing.
1783 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1785 * @return {boolean} Window is closing
1787 OO.ui.Window.prototype.isClosing = function () {
1788 return this.manager.isClosing( this );
1792 * Check if the window is opened.
1794 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1796 * @return {boolean} Window is opened
1798 OO.ui.Window.prototype.isOpened = function () {
1799 return this.manager.isOpened( this );
1803 * Get the window manager.
1805 * All windows must be attached to a window manager, which is used to open
1806 * and close the window and control its presentation.
1808 * @return {OO.ui.WindowManager} Manager of window
1810 OO.ui.Window.prototype.getManager = function () {
1811 return this.manager;
1815 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1817 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1819 OO.ui.Window.prototype.getSize = function () {
1820 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
1821 sizes = this.manager.constructor.static.sizes,
1822 size = this.size;
1824 if ( !sizes[ size ] ) {
1825 size = this.manager.constructor.static.defaultSize;
1827 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
1828 size = 'full';
1831 return size;
1835 * Get the size properties associated with the current window size
1837 * @return {Object} Size properties
1839 OO.ui.Window.prototype.getSizeProperties = function () {
1840 return this.manager.constructor.static.sizes[ this.getSize() ];
1844 * Disable transitions on window's frame for the duration of the callback function, then enable them
1845 * back.
1847 * @private
1848 * @param {Function} callback Function to call while transitions are disabled
1850 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1851 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1852 // Disable transitions first, otherwise we'll get values from when the window was animating.
1853 var oldTransition,
1854 styleObj = this.$frame[ 0 ].style;
1855 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1856 styleObj.MozTransition || styleObj.WebkitTransition;
1857 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1858 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1859 callback();
1860 // Force reflow to make sure the style changes done inside callback really are not transitioned
1861 this.$frame.height();
1862 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1863 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1867 * Get the height of the full window contents (i.e., the window head, body and foot together).
1869 * What consistitutes the head, body, and foot varies depending on the window type.
1870 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1871 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1872 * and special actions in the head, and dialog content in the body.
1874 * To get just the height of the dialog body, use the #getBodyHeight method.
1876 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1878 OO.ui.Window.prototype.getContentHeight = function () {
1879 var bodyHeight,
1880 win = this,
1881 bodyStyleObj = this.$body[ 0 ].style,
1882 frameStyleObj = this.$frame[ 0 ].style;
1884 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1885 // Disable transitions first, otherwise we'll get values from when the window was animating.
1886 this.withoutSizeTransitions( function () {
1887 var oldHeight = frameStyleObj.height,
1888 oldPosition = bodyStyleObj.position;
1889 frameStyleObj.height = '1px';
1890 // Force body to resize to new width
1891 bodyStyleObj.position = 'relative';
1892 bodyHeight = win.getBodyHeight();
1893 frameStyleObj.height = oldHeight;
1894 bodyStyleObj.position = oldPosition;
1895 } );
1897 return (
1898 // Add buffer for border
1899 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1900 // Use combined heights of children
1901 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1906 * Get the height of the window body.
1908 * To get the height of the full window contents (the window body, head, and foot together),
1909 * use #getContentHeight.
1911 * When this function is called, the window will temporarily have been resized
1912 * to height=1px, so .scrollHeight measurements can be taken accurately.
1914 * @return {number} Height of the window body in pixels
1916 OO.ui.Window.prototype.getBodyHeight = function () {
1917 return this.$body[ 0 ].scrollHeight;
1921 * Get the directionality of the frame (right-to-left or left-to-right).
1923 * @return {string} Directionality: `'ltr'` or `'rtl'`
1925 OO.ui.Window.prototype.getDir = function () {
1926 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
1930 * Get the 'setup' process.
1932 * The setup process is used to set up a window for use in a particular context,
1933 * based on the `data` argument. This method is called during the opening phase of the window’s
1934 * lifecycle.
1936 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1937 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1938 * of OO.ui.Process.
1940 * To add window content that persists between openings, you may wish to use the #initialize method
1941 * instead.
1943 * @param {Object} [data] Window opening data
1944 * @return {OO.ui.Process} Setup process
1946 OO.ui.Window.prototype.getSetupProcess = function () {
1947 return new OO.ui.Process();
1951 * Get the ‘ready’ process.
1953 * The ready process is used to ready a window for use in a particular
1954 * context, based on the `data` argument. This method is called during the opening phase of
1955 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
1957 * Override this method to add additional steps to the ‘ready’ process the parent method
1958 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
1959 * methods of OO.ui.Process.
1961 * @param {Object} [data] Window opening data
1962 * @return {OO.ui.Process} Ready process
1964 OO.ui.Window.prototype.getReadyProcess = function () {
1965 return new OO.ui.Process();
1969 * Get the 'hold' process.
1971 * The hold proccess is used to keep a window from being used in a particular context,
1972 * based on the `data` argument. This method is called during the closing phase of the window’s
1973 * lifecycle.
1975 * Override this method to add additional steps to the 'hold' process the parent method provides
1976 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1977 * of OO.ui.Process.
1979 * @param {Object} [data] Window closing data
1980 * @return {OO.ui.Process} Hold process
1982 OO.ui.Window.prototype.getHoldProcess = function () {
1983 return new OO.ui.Process();
1987 * Get the ‘teardown’ process.
1989 * The teardown process is used to teardown a window after use. During teardown,
1990 * user interactions within the window are conveyed and the window is closed, based on the `data`
1991 * argument. This method is called during the closing phase of the window’s lifecycle.
1993 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
1994 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1995 * of OO.ui.Process.
1997 * @param {Object} [data] Window closing data
1998 * @return {OO.ui.Process} Teardown process
2000 OO.ui.Window.prototype.getTeardownProcess = function () {
2001 return new OO.ui.Process();
2005 * Set the window manager.
2007 * This will cause the window to initialize. Calling it more than once will cause an error.
2009 * @param {OO.ui.WindowManager} manager Manager for this window
2010 * @throws {Error} An error is thrown if the method is called more than once
2011 * @chainable
2013 OO.ui.Window.prototype.setManager = function ( manager ) {
2014 if ( this.manager ) {
2015 throw new Error( 'Cannot set window manager, window already has a manager' );
2018 this.manager = manager;
2019 this.initialize();
2021 return this;
2025 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2027 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2028 * `full`
2029 * @chainable
2031 OO.ui.Window.prototype.setSize = function ( size ) {
2032 this.size = size;
2033 this.updateSize();
2034 return this;
2038 * Update the window size.
2040 * @throws {Error} An error is thrown if the window is not attached to a window manager
2041 * @chainable
2043 OO.ui.Window.prototype.updateSize = function () {
2044 if ( !this.manager ) {
2045 throw new Error( 'Cannot update window size, must be attached to a manager' );
2048 this.manager.updateWindowSize( this );
2050 return this;
2054 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2055 * when the window is opening. In general, setDimensions should not be called directly.
2057 * To set the size of the window, use the #setSize method.
2059 * @param {Object} dim CSS dimension properties
2060 * @param {string|number} [dim.width] Width
2061 * @param {string|number} [dim.minWidth] Minimum width
2062 * @param {string|number} [dim.maxWidth] Maximum width
2063 * @param {string|number} [dim.height] Height, omit to set based on height of contents
2064 * @param {string|number} [dim.minHeight] Minimum height
2065 * @param {string|number} [dim.maxHeight] Maximum height
2066 * @chainable
2068 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2069 var height,
2070 win = this,
2071 styleObj = this.$frame[ 0 ].style;
2073 // Calculate the height we need to set using the correct width
2074 if ( dim.height === undefined ) {
2075 this.withoutSizeTransitions( function () {
2076 var oldWidth = styleObj.width;
2077 win.$frame.css( 'width', dim.width || '' );
2078 height = win.getContentHeight();
2079 styleObj.width = oldWidth;
2080 } );
2081 } else {
2082 height = dim.height;
2085 this.$frame.css( {
2086 width: dim.width || '',
2087 minWidth: dim.minWidth || '',
2088 maxWidth: dim.maxWidth || '',
2089 height: height || '',
2090 minHeight: dim.minHeight || '',
2091 maxHeight: dim.maxHeight || ''
2092 } );
2094 return this;
2098 * Initialize window contents.
2100 * Before the window is opened for the first time, #initialize is called so that content that
2101 * persists between openings can be added to the window.
2103 * To set up a window with new content each time the window opens, use #getSetupProcess.
2105 * @throws {Error} An error is thrown if the window is not attached to a window manager
2106 * @chainable
2108 OO.ui.Window.prototype.initialize = function () {
2109 if ( !this.manager ) {
2110 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2113 // Properties
2114 this.$head = $( '<div>' );
2115 this.$body = $( '<div>' );
2116 this.$foot = $( '<div>' );
2117 this.$document = $( this.getElementDocument() );
2119 // Events
2120 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2122 // Initialization
2123 this.$head.addClass( 'oo-ui-window-head' );
2124 this.$body.addClass( 'oo-ui-window-body' );
2125 this.$foot.addClass( 'oo-ui-window-foot' );
2126 this.$content.append( this.$head, this.$body, this.$foot );
2128 return this;
2132 * Called when someone tries to focus the hidden element at the end of the dialog.
2133 * Sends focus back to the start of the dialog.
2135 * @param {jQuery.Event} event Focus event
2137 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2138 if ( this.$focusTrapBefore.is( event.target ) ) {
2139 OO.ui.findFocusable( this.$content, true ).focus();
2140 } else {
2141 // this.$content is the part of the focus cycle, and is the first focusable element
2142 this.$content.focus();
2147 * Open the window.
2149 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2150 * method, which returns a promise resolved when the window is done opening.
2152 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2154 * @param {Object} [data] Window opening data
2155 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2156 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2157 * value is a new promise, which is resolved when the window begins closing.
2158 * @throws {Error} An error is thrown if the window is not attached to a window manager
2160 OO.ui.Window.prototype.open = function ( data ) {
2161 if ( !this.manager ) {
2162 throw new Error( 'Cannot open window, must be attached to a manager' );
2165 return this.manager.openWindow( this, data );
2169 * Close the window.
2171 * This method is a wrapper around a call to the window
2172 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2173 * which returns a closing promise resolved when the window is done closing.
2175 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2176 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2177 * the window closes.
2179 * @param {Object} [data] Window closing data
2180 * @return {jQuery.Promise} Promise resolved when window is closed
2181 * @throws {Error} An error is thrown if the window is not attached to a window manager
2183 OO.ui.Window.prototype.close = function ( data ) {
2184 if ( !this.manager ) {
2185 throw new Error( 'Cannot close window, must be attached to a manager' );
2188 return this.manager.closeWindow( this, data );
2192 * Setup window.
2194 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2195 * by other systems.
2197 * @param {Object} [data] Window opening data
2198 * @return {jQuery.Promise} Promise resolved when window is setup
2200 OO.ui.Window.prototype.setup = function ( data ) {
2201 var win = this;
2203 this.toggle( true );
2205 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2206 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2208 return this.getSetupProcess( data ).execute().then( function () {
2209 // Force redraw by asking the browser to measure the elements' widths
2210 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2211 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2212 } );
2216 * Ready window.
2218 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2219 * by other systems.
2221 * @param {Object} [data] Window opening data
2222 * @return {jQuery.Promise} Promise resolved when window is ready
2224 OO.ui.Window.prototype.ready = function ( data ) {
2225 var win = this;
2227 this.$content.focus();
2228 return this.getReadyProcess( data ).execute().then( function () {
2229 // Force redraw by asking the browser to measure the elements' widths
2230 win.$element.addClass( 'oo-ui-window-ready' ).width();
2231 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2232 } );
2236 * Hold window.
2238 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2239 * by other systems.
2241 * @param {Object} [data] Window closing data
2242 * @return {jQuery.Promise} Promise resolved when window is held
2244 OO.ui.Window.prototype.hold = function ( data ) {
2245 var win = this;
2247 return this.getHoldProcess( data ).execute().then( function () {
2248 // Get the focused element within the window's content
2249 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2251 // Blur the focused element
2252 if ( $focus.length ) {
2253 $focus[ 0 ].blur();
2256 // Force redraw by asking the browser to measure the elements' widths
2257 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2258 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2259 } );
2263 * Teardown window.
2265 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2266 * by other systems.
2268 * @param {Object} [data] Window closing data
2269 * @return {jQuery.Promise} Promise resolved when window is torn down
2271 OO.ui.Window.prototype.teardown = function ( data ) {
2272 var win = this;
2274 return this.getTeardownProcess( data ).execute().then( function () {
2275 // Force redraw by asking the browser to measure the elements' widths
2276 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2277 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2278 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2279 win.toggle( false );
2280 } );
2284 * The Dialog class serves as the base class for the other types of dialogs.
2285 * Unless extended to include controls, the rendered dialog box is a simple window
2286 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2287 * which opens, closes, and controls the presentation of the window. See the
2288 * [OOjs UI documentation on MediaWiki] [1] for more information.
2290 * @example
2291 * // A simple dialog window.
2292 * function MyDialog( config ) {
2293 * MyDialog.parent.call( this, config );
2295 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2296 * MyDialog.prototype.initialize = function () {
2297 * MyDialog.parent.prototype.initialize.call( this );
2298 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2299 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2300 * this.$body.append( this.content.$element );
2301 * };
2302 * MyDialog.prototype.getBodyHeight = function () {
2303 * return this.content.$element.outerHeight( true );
2304 * };
2305 * var myDialog = new MyDialog( {
2306 * size: 'medium'
2307 * } );
2308 * // Create and append a window manager, which opens and closes the window.
2309 * var windowManager = new OO.ui.WindowManager();
2310 * $( 'body' ).append( windowManager.$element );
2311 * windowManager.addWindows( [ myDialog ] );
2312 * // Open the window!
2313 * windowManager.openWindow( myDialog );
2315 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2317 * @abstract
2318 * @class
2319 * @extends OO.ui.Window
2320 * @mixins OO.ui.mixin.PendingElement
2322 * @constructor
2323 * @param {Object} [config] Configuration options
2325 OO.ui.Dialog = function OoUiDialog( config ) {
2326 // Parent constructor
2327 OO.ui.Dialog.parent.call( this, config );
2329 // Mixin constructors
2330 OO.ui.mixin.PendingElement.call( this );
2332 // Properties
2333 this.actions = new OO.ui.ActionSet();
2334 this.attachedActions = [];
2335 this.currentAction = null;
2336 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2338 // Events
2339 this.actions.connect( this, {
2340 click: 'onActionClick',
2341 resize: 'onActionResize',
2342 change: 'onActionsChange'
2343 } );
2345 // Initialization
2346 this.$element
2347 .addClass( 'oo-ui-dialog' )
2348 .attr( 'role', 'dialog' );
2351 /* Setup */
2353 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2354 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2356 /* Static Properties */
2359 * Symbolic name of dialog.
2361 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2362 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2364 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2366 * @abstract
2367 * @static
2368 * @inheritable
2369 * @property {string}
2371 OO.ui.Dialog.static.name = '';
2374 * The dialog title.
2376 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2377 * that will produce a Label node or string. The title can also be specified with data passed to the
2378 * constructor (see #getSetupProcess). In this case, the static value will be overridden.
2380 * @abstract
2381 * @static
2382 * @inheritable
2383 * @property {jQuery|string|Function}
2385 OO.ui.Dialog.static.title = '';
2388 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2390 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2391 * value will be overridden.
2393 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2395 * @static
2396 * @inheritable
2397 * @property {Object[]}
2399 OO.ui.Dialog.static.actions = [];
2402 * Close the dialog when the 'Esc' key is pressed.
2404 * @static
2405 * @abstract
2406 * @inheritable
2407 * @property {boolean}
2409 OO.ui.Dialog.static.escapable = true;
2411 /* Methods */
2414 * Handle frame document key down events.
2416 * @private
2417 * @param {jQuery.Event} e Key down event
2419 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2420 var actions;
2421 if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
2422 this.executeAction( '' );
2423 e.preventDefault();
2424 e.stopPropagation();
2425 } else if ( e.which === OO.ui.Keys.ENTER && e.ctrlKey ) {
2426 actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
2427 if ( actions.length > 0 ) {
2428 this.executeAction( actions[ 0 ].getAction() );
2429 e.preventDefault();
2430 e.stopPropagation();
2436 * Handle action resized events.
2438 * @private
2439 * @param {OO.ui.ActionWidget} action Action that was resized
2441 OO.ui.Dialog.prototype.onActionResize = function () {
2442 // Override in subclass
2446 * Handle action click events.
2448 * @private
2449 * @param {OO.ui.ActionWidget} action Action that was clicked
2451 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2452 if ( !this.isPending() ) {
2453 this.executeAction( action.getAction() );
2458 * Handle actions change event.
2460 * @private
2462 OO.ui.Dialog.prototype.onActionsChange = function () {
2463 this.detachActions();
2464 if ( !this.isClosing() ) {
2465 this.attachActions();
2470 * Get the set of actions used by the dialog.
2472 * @return {OO.ui.ActionSet}
2474 OO.ui.Dialog.prototype.getActions = function () {
2475 return this.actions;
2479 * Get a process for taking action.
2481 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2482 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2483 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2485 * @param {string} [action] Symbolic name of action
2486 * @return {OO.ui.Process} Action process
2488 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2489 return new OO.ui.Process()
2490 .next( function () {
2491 if ( !action ) {
2492 // An empty action always closes the dialog without data, which should always be
2493 // safe and make no changes
2494 this.close();
2496 }, this );
2500 * @inheritdoc
2502 * @param {Object} [data] Dialog opening data
2503 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2504 * the {@link #static-title static title}
2505 * @param {Object[]} [data.actions] List of configuration options for each
2506 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2508 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2509 data = data || {};
2511 // Parent method
2512 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2513 .next( function () {
2514 var config = this.constructor.static,
2515 actions = data.actions !== undefined ? data.actions : config.actions;
2517 this.title.setLabel(
2518 data.title !== undefined ? data.title : this.constructor.static.title
2520 this.actions.add( this.getActionWidgets( actions ) );
2522 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2523 }, this );
2527 * @inheritdoc
2529 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2530 // Parent method
2531 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2532 .first( function () {
2533 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2535 this.actions.clear();
2536 this.currentAction = null;
2537 }, this );
2541 * @inheritdoc
2543 OO.ui.Dialog.prototype.initialize = function () {
2544 var titleId;
2546 // Parent method
2547 OO.ui.Dialog.parent.prototype.initialize.call( this );
2549 titleId = OO.ui.generateElementId();
2551 // Properties
2552 this.title = new OO.ui.LabelWidget( {
2553 id: titleId
2554 } );
2556 // Initialization
2557 this.$content.addClass( 'oo-ui-dialog-content' );
2558 this.$element.attr( 'aria-labelledby', titleId );
2559 this.setPendingElement( this.$head );
2563 * Get action widgets from a list of configs
2565 * @param {Object[]} actions Action widget configs
2566 * @return {OO.ui.ActionWidget[]} Action widgets
2568 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2569 var i, len, widgets = [];
2570 for ( i = 0, len = actions.length; i < len; i++ ) {
2571 widgets.push(
2572 new OO.ui.ActionWidget( actions[ i ] )
2575 return widgets;
2579 * Attach action actions.
2581 * @protected
2583 OO.ui.Dialog.prototype.attachActions = function () {
2584 // Remember the list of potentially attached actions
2585 this.attachedActions = this.actions.get();
2589 * Detach action actions.
2591 * @protected
2592 * @chainable
2594 OO.ui.Dialog.prototype.detachActions = function () {
2595 var i, len;
2597 // Detach all actions that may have been previously attached
2598 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2599 this.attachedActions[ i ].$element.detach();
2601 this.attachedActions = [];
2605 * Execute an action.
2607 * @param {string} action Symbolic name of action to execute
2608 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2610 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2611 this.pushPending();
2612 this.currentAction = action;
2613 return this.getActionProcess( action ).execute()
2614 .always( this.popPending.bind( this ) );
2618 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
2619 * consists of a header that contains the dialog title, a body with the message, and a footer that
2620 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
2621 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
2623 * There are two basic types of message dialogs, confirmation and alert:
2625 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
2626 * more details about the consequences.
2627 * - **alert**: the dialog title describes which event occurred and the message provides more information
2628 * about why the event occurred.
2630 * The MessageDialog class specifies two actions: ‘accept’, the primary
2631 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
2632 * passing along the selected action.
2634 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
2636 * @example
2637 * // Example: Creating and opening a message dialog window.
2638 * var messageDialog = new OO.ui.MessageDialog();
2640 * // Create and append a window manager.
2641 * var windowManager = new OO.ui.WindowManager();
2642 * $( 'body' ).append( windowManager.$element );
2643 * windowManager.addWindows( [ messageDialog ] );
2644 * // Open the window.
2645 * windowManager.openWindow( messageDialog, {
2646 * title: 'Basic message dialog',
2647 * message: 'This is the message'
2648 * } );
2650 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
2652 * @class
2653 * @extends OO.ui.Dialog
2655 * @constructor
2656 * @param {Object} [config] Configuration options
2658 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
2659 // Parent constructor
2660 OO.ui.MessageDialog.parent.call( this, config );
2662 // Properties
2663 this.verticalActionLayout = null;
2665 // Initialization
2666 this.$element.addClass( 'oo-ui-messageDialog' );
2669 /* Setup */
2671 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
2673 /* Static Properties */
2675 OO.ui.MessageDialog.static.name = 'message';
2677 OO.ui.MessageDialog.static.size = 'small';
2679 OO.ui.MessageDialog.static.verbose = false;
2682 * Dialog title.
2684 * The title of a confirmation dialog describes what a progressive action will do. The
2685 * title of an alert dialog describes which event occurred.
2687 * @static
2688 * @inheritable
2689 * @property {jQuery|string|Function|null}
2691 OO.ui.MessageDialog.static.title = null;
2694 * The message displayed in the dialog body.
2696 * A confirmation message describes the consequences of a progressive action. An alert
2697 * message describes why an event occurred.
2699 * @static
2700 * @inheritable
2701 * @property {jQuery|string|Function|null}
2703 OO.ui.MessageDialog.static.message = null;
2705 // Note that OO.ui.alert() and OO.ui.confirm() rely on these.
2706 OO.ui.MessageDialog.static.actions = [
2707 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
2708 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
2711 /* Methods */
2714 * @inheritdoc
2716 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
2717 OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
2719 // Events
2720 this.manager.connect( this, {
2721 resize: 'onResize'
2722 } );
2724 return this;
2728 * @inheritdoc
2730 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
2731 this.fitActions();
2732 return OO.ui.MessageDialog.parent.prototype.onActionResize.call( this, action );
2736 * Handle window resized events.
2738 * @private
2740 OO.ui.MessageDialog.prototype.onResize = function () {
2741 var dialog = this;
2742 dialog.fitActions();
2743 // Wait for CSS transition to finish and do it again :(
2744 setTimeout( function () {
2745 dialog.fitActions();
2746 }, 300 );
2750 * Toggle action layout between vertical and horizontal.
2752 * @private
2753 * @param {boolean} [value] Layout actions vertically, omit to toggle
2754 * @chainable
2756 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
2757 value = value === undefined ? !this.verticalActionLayout : !!value;
2759 if ( value !== this.verticalActionLayout ) {
2760 this.verticalActionLayout = value;
2761 this.$actions
2762 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
2763 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
2766 return this;
2770 * @inheritdoc
2772 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
2773 if ( action ) {
2774 return new OO.ui.Process( function () {
2775 this.close( { action: action } );
2776 }, this );
2778 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
2782 * @inheritdoc
2784 * @param {Object} [data] Dialog opening data
2785 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
2786 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
2787 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
2788 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
2789 * action item
2791 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
2792 data = data || {};
2794 // Parent method
2795 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
2796 .next( function () {
2797 this.title.setLabel(
2798 data.title !== undefined ? data.title : this.constructor.static.title
2800 this.message.setLabel(
2801 data.message !== undefined ? data.message : this.constructor.static.message
2803 this.message.$element.toggleClass(
2804 'oo-ui-messageDialog-message-verbose',
2805 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
2807 }, this );
2811 * @inheritdoc
2813 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
2814 data = data || {};
2816 // Parent method
2817 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
2818 .next( function () {
2819 // Focus the primary action button
2820 var actions = this.actions.get();
2821 actions = actions.filter( function ( action ) {
2822 return action.getFlags().indexOf( 'primary' ) > -1;
2823 } );
2824 if ( actions.length > 0 ) {
2825 actions[ 0 ].$button.focus();
2827 }, this );
2831 * @inheritdoc
2833 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
2834 var bodyHeight, oldOverflow,
2835 $scrollable = this.container.$element;
2837 oldOverflow = $scrollable[ 0 ].style.overflow;
2838 $scrollable[ 0 ].style.overflow = 'hidden';
2840 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
2842 bodyHeight = this.text.$element.outerHeight( true );
2843 $scrollable[ 0 ].style.overflow = oldOverflow;
2845 return bodyHeight;
2849 * @inheritdoc
2851 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
2852 var $scrollable = this.container.$element;
2853 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
2855 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
2856 // Need to do it after transition completes (250ms), add 50ms just in case.
2857 setTimeout( function () {
2858 var oldOverflow = $scrollable[ 0 ].style.overflow;
2859 $scrollable[ 0 ].style.overflow = 'hidden';
2861 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
2863 $scrollable[ 0 ].style.overflow = oldOverflow;
2864 }, 300 );
2866 return this;
2870 * @inheritdoc
2872 OO.ui.MessageDialog.prototype.initialize = function () {
2873 // Parent method
2874 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
2876 // Properties
2877 this.$actions = $( '<div>' );
2878 this.container = new OO.ui.PanelLayout( {
2879 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
2880 } );
2881 this.text = new OO.ui.PanelLayout( {
2882 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
2883 } );
2884 this.message = new OO.ui.LabelWidget( {
2885 classes: [ 'oo-ui-messageDialog-message' ]
2886 } );
2888 // Initialization
2889 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
2890 this.$content.addClass( 'oo-ui-messageDialog-content' );
2891 this.container.$element.append( this.text.$element );
2892 this.text.$element.append( this.title.$element, this.message.$element );
2893 this.$body.append( this.container.$element );
2894 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
2895 this.$foot.append( this.$actions );
2899 * @inheritdoc
2901 OO.ui.MessageDialog.prototype.attachActions = function () {
2902 var i, len, other, special, others;
2904 // Parent method
2905 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
2907 special = this.actions.getSpecial();
2908 others = this.actions.getOthers();
2910 if ( special.safe ) {
2911 this.$actions.append( special.safe.$element );
2912 special.safe.toggleFramed( false );
2914 if ( others.length ) {
2915 for ( i = 0, len = others.length; i < len; i++ ) {
2916 other = others[ i ];
2917 this.$actions.append( other.$element );
2918 other.toggleFramed( false );
2921 if ( special.primary ) {
2922 this.$actions.append( special.primary.$element );
2923 special.primary.toggleFramed( false );
2926 if ( !this.isOpening() ) {
2927 // If the dialog is currently opening, this will be called automatically soon.
2928 // This also calls #fitActions.
2929 this.updateSize();
2934 * Fit action actions into columns or rows.
2936 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
2938 * @private
2940 OO.ui.MessageDialog.prototype.fitActions = function () {
2941 var i, len, action,
2942 previous = this.verticalActionLayout,
2943 actions = this.actions.get();
2945 // Detect clipping
2946 this.toggleVerticalActionLayout( false );
2947 for ( i = 0, len = actions.length; i < len; i++ ) {
2948 action = actions[ i ];
2949 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
2950 this.toggleVerticalActionLayout( true );
2951 break;
2955 // Move the body out of the way of the foot
2956 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
2958 if ( this.verticalActionLayout !== previous ) {
2959 // We changed the layout, window height might need to be updated.
2960 this.updateSize();
2965 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
2966 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
2967 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
2968 * relevant. The ProcessDialog class is always extended and customized with the actions and content
2969 * required for each process.
2971 * The process dialog box consists of a header that visually represents the ‘working’ state of long
2972 * processes with an animation. The header contains the dialog title as well as
2973 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
2974 * a ‘primary’ action on the right (e.g., ‘Done’).
2976 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
2977 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
2979 * @example
2980 * // Example: Creating and opening a process dialog window.
2981 * function MyProcessDialog( config ) {
2982 * MyProcessDialog.parent.call( this, config );
2984 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
2986 * MyProcessDialog.static.title = 'Process dialog';
2987 * MyProcessDialog.static.actions = [
2988 * { action: 'save', label: 'Done', flags: 'primary' },
2989 * { label: 'Cancel', flags: 'safe' }
2990 * ];
2992 * MyProcessDialog.prototype.initialize = function () {
2993 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
2994 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2995 * 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>' );
2996 * this.$body.append( this.content.$element );
2997 * };
2998 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
2999 * var dialog = this;
3000 * if ( action ) {
3001 * return new OO.ui.Process( function () {
3002 * dialog.close( { action: action } );
3003 * } );
3005 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
3006 * };
3008 * var windowManager = new OO.ui.WindowManager();
3009 * $( 'body' ).append( windowManager.$element );
3011 * var dialog = new MyProcessDialog();
3012 * windowManager.addWindows( [ dialog ] );
3013 * windowManager.openWindow( dialog );
3015 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
3017 * @abstract
3018 * @class
3019 * @extends OO.ui.Dialog
3021 * @constructor
3022 * @param {Object} [config] Configuration options
3024 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
3025 // Parent constructor
3026 OO.ui.ProcessDialog.parent.call( this, config );
3028 // Properties
3029 this.fitOnOpen = false;
3031 // Initialization
3032 this.$element.addClass( 'oo-ui-processDialog' );
3035 /* Setup */
3037 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
3039 /* Methods */
3042 * Handle dismiss button click events.
3044 * Hides errors.
3046 * @private
3048 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
3049 this.hideErrors();
3053 * Handle retry button click events.
3055 * Hides errors and then tries again.
3057 * @private
3059 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
3060 this.hideErrors();
3061 this.executeAction( this.currentAction );
3065 * @inheritdoc
3067 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
3068 if ( this.actions.isSpecial( action ) ) {
3069 this.fitLabel();
3071 return OO.ui.ProcessDialog.parent.prototype.onActionResize.call( this, action );
3075 * @inheritdoc
3077 OO.ui.ProcessDialog.prototype.initialize = function () {
3078 // Parent method
3079 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
3081 // Properties
3082 this.$navigation = $( '<div>' );
3083 this.$location = $( '<div>' );
3084 this.$safeActions = $( '<div>' );
3085 this.$primaryActions = $( '<div>' );
3086 this.$otherActions = $( '<div>' );
3087 this.dismissButton = new OO.ui.ButtonWidget( {
3088 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
3089 } );
3090 this.retryButton = new OO.ui.ButtonWidget();
3091 this.$errors = $( '<div>' );
3092 this.$errorsTitle = $( '<div>' );
3094 // Events
3095 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
3096 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
3098 // Initialization
3099 this.title.$element.addClass( 'oo-ui-processDialog-title' );
3100 this.$location
3101 .append( this.title.$element )
3102 .addClass( 'oo-ui-processDialog-location' );
3103 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
3104 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
3105 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
3106 this.$errorsTitle
3107 .addClass( 'oo-ui-processDialog-errors-title' )
3108 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
3109 this.$errors
3110 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
3111 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
3112 this.$content
3113 .addClass( 'oo-ui-processDialog-content' )
3114 .append( this.$errors );
3115 this.$navigation
3116 .addClass( 'oo-ui-processDialog-navigation' )
3117 .append( this.$safeActions, this.$location, this.$primaryActions );
3118 this.$head.append( this.$navigation );
3119 this.$foot.append( this.$otherActions );
3123 * @inheritdoc
3125 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
3126 var i, len, widgets = [];
3127 for ( i = 0, len = actions.length; i < len; i++ ) {
3128 widgets.push(
3129 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
3132 return widgets;
3136 * @inheritdoc
3138 OO.ui.ProcessDialog.prototype.attachActions = function () {
3139 var i, len, other, special, others;
3141 // Parent method
3142 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
3144 special = this.actions.getSpecial();
3145 others = this.actions.getOthers();
3146 if ( special.primary ) {
3147 this.$primaryActions.append( special.primary.$element );
3149 for ( i = 0, len = others.length; i < len; i++ ) {
3150 other = others[ i ];
3151 this.$otherActions.append( other.$element );
3153 if ( special.safe ) {
3154 this.$safeActions.append( special.safe.$element );
3157 this.fitLabel();
3158 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
3162 * @inheritdoc
3164 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
3165 var process = this;
3166 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
3167 .fail( function ( errors ) {
3168 process.showErrors( errors || [] );
3169 } );
3173 * @inheritdoc
3175 OO.ui.ProcessDialog.prototype.setDimensions = function () {
3176 // Parent method
3177 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
3179 this.fitLabel();
3183 * Fit label between actions.
3185 * @private
3186 * @chainable
3188 OO.ui.ProcessDialog.prototype.fitLabel = function () {
3189 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
3190 size = this.getSizeProperties();
3192 if ( typeof size.width !== 'number' ) {
3193 if ( this.isOpened() ) {
3194 navigationWidth = this.$head.width() - 20;
3195 } else if ( this.isOpening() ) {
3196 if ( !this.fitOnOpen ) {
3197 // Size is relative and the dialog isn't open yet, so wait.
3198 this.manager.opening.done( this.fitLabel.bind( this ) );
3199 this.fitOnOpen = true;
3201 return;
3202 } else {
3203 return;
3205 } else {
3206 navigationWidth = size.width - 20;
3209 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
3210 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
3211 biggerWidth = Math.max( safeWidth, primaryWidth );
3213 labelWidth = this.title.$element.width();
3215 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
3216 // We have enough space to center the label
3217 leftWidth = rightWidth = biggerWidth;
3218 } else {
3219 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
3220 if ( this.getDir() === 'ltr' ) {
3221 leftWidth = safeWidth;
3222 rightWidth = primaryWidth;
3223 } else {
3224 leftWidth = primaryWidth;
3225 rightWidth = safeWidth;
3229 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
3231 return this;
3235 * Handle errors that occurred during accept or reject processes.
3237 * @private
3238 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
3240 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
3241 var i, len, $item, actions,
3242 items = [],
3243 abilities = {},
3244 recoverable = true,
3245 warning = false;
3247 if ( errors instanceof OO.ui.Error ) {
3248 errors = [ errors ];
3251 for ( i = 0, len = errors.length; i < len; i++ ) {
3252 if ( !errors[ i ].isRecoverable() ) {
3253 recoverable = false;
3255 if ( errors[ i ].isWarning() ) {
3256 warning = true;
3258 $item = $( '<div>' )
3259 .addClass( 'oo-ui-processDialog-error' )
3260 .append( errors[ i ].getMessage() );
3261 items.push( $item[ 0 ] );
3263 this.$errorItems = $( items );
3264 if ( recoverable ) {
3265 abilities[ this.currentAction ] = true;
3266 // Copy the flags from the first matching action
3267 actions = this.actions.get( { actions: this.currentAction } );
3268 if ( actions.length ) {
3269 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
3271 } else {
3272 abilities[ this.currentAction ] = false;
3273 this.actions.setAbilities( abilities );
3275 if ( warning ) {
3276 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
3277 } else {
3278 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
3280 this.retryButton.toggle( recoverable );
3281 this.$errorsTitle.after( this.$errorItems );
3282 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
3286 * Hide errors.
3288 * @private
3290 OO.ui.ProcessDialog.prototype.hideErrors = function () {
3291 this.$errors.addClass( 'oo-ui-element-hidden' );
3292 if ( this.$errorItems ) {
3293 this.$errorItems.remove();
3294 this.$errorItems = null;
3299 * @inheritdoc
3301 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
3302 // Parent method
3303 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
3304 .first( function () {
3305 // Make sure to hide errors
3306 this.hideErrors();
3307 this.fitOnOpen = false;
3308 }, this );
3312 * @class OO.ui
3316 * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
3317 * OO.ui.confirm.
3319 * @private
3320 * @return {OO.ui.WindowManager}
3322 OO.ui.getWindowManager = function () {
3323 if ( !OO.ui.windowManager ) {
3324 OO.ui.windowManager = new OO.ui.WindowManager();
3325 $( 'body' ).append( OO.ui.windowManager.$element );
3326 OO.ui.windowManager.addWindows( {
3327 messageDialog: new OO.ui.MessageDialog()
3328 } );
3330 return OO.ui.windowManager;
3334 * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
3335 * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
3336 * has only one action button, labelled "OK", clicking it will simply close the dialog.
3338 * A window manager is created automatically when this function is called for the first time.
3340 * @example
3341 * OO.ui.alert( 'Something happened!' ).done( function () {
3342 * console.log( 'User closed the dialog.' );
3343 * } );
3345 * @param {jQuery|string} text Message text to display
3346 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
3347 * @return {jQuery.Promise} Promise resolved when the user closes the dialog
3349 OO.ui.alert = function ( text, options ) {
3350 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
3351 message: text,
3352 verbose: true,
3353 actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
3354 }, options ) ).then( function ( opened ) {
3355 return opened.then( function ( closing ) {
3356 return closing.then( function () {
3357 return $.Deferred().resolve();
3358 } );
3359 } );
3360 } );
3364 * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
3365 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
3366 * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
3367 * (labelled "Cancel").
3369 * A window manager is created automatically when this function is called for the first time.
3371 * @example
3372 * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
3373 * if ( confirmed ) {
3374 * console.log( 'User clicked "OK"!' );
3375 * } else {
3376 * console.log( 'User clicked "Cancel" or closed the dialog.' );
3378 * } );
3380 * @param {jQuery|string} text Message text to display
3381 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
3382 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
3383 * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
3384 * `false`.
3386 OO.ui.confirm = function ( text, options ) {
3387 return OO.ui.getWindowManager().openWindow( 'messageDialog', $.extend( {
3388 message: text,
3389 verbose: true
3390 }, options ) ).then( function ( opened ) {
3391 return opened.then( function ( closing ) {
3392 return closing.then( function ( data ) {
3393 return $.Deferred().resolve( !!( data && data.action === 'accept' ) );
3394 } );
3395 } );
3396 } );
3399 }( OO ) );