Update OOUI to v0.30.3
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-windows.js
1 /*!
2 * OOUI v0.30.3
3 * https://www.mediawiki.org/wiki/OOUI
4 *
5 * Copyright 2011–2019 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2019-02-21T10:57:07Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
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.
19 *
20 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
21 * Please see the [OOUI documentation on MediaWiki] [1] for more information
22 * and examples.
23 *
24 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
25 *
26 * @class
27 * @extends OO.ui.ButtonWidget
28 * @mixins OO.ui.mixin.PendingElement
29 *
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
37 */
38 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
39 // Configuration initialization
40 config = $.extend( { framed: false }, config );
41
42 // Parent constructor
43 OO.ui.ActionWidget.parent.call( this, config );
44
45 // Mixin constructors
46 OO.ui.mixin.PendingElement.call( this, config );
47
48 // Properties
49 this.action = config.action || '';
50 this.modes = config.modes || [];
51 this.width = 0;
52 this.height = 0;
53
54 // Initialization
55 this.$element.addClass( 'oo-ui-actionWidget' );
56 };
57
58 /* Setup */
59
60 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
61 OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
62
63 /* Methods */
64
65 /**
66 * Check if the action is configured to be available in the specified `mode`.
67 *
68 * @param {string} mode Name of mode
69 * @return {boolean} The action is configured with the mode
70 */
71 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
72 return this.modes.indexOf( mode ) !== -1;
73 };
74
75 /**
76 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
77 *
78 * @return {string}
79 */
80 OO.ui.ActionWidget.prototype.getAction = function () {
81 return this.action;
82 };
83
84 /**
85 * Get the symbolic name of the mode or modes for which the action is configured to be available.
86 *
87 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
88 * Only actions that are configured to be available in the current mode will be visible. All other actions
89 * are hidden.
90 *
91 * @return {string[]}
92 */
93 OO.ui.ActionWidget.prototype.getModes = function () {
94 return this.modes.slice();
95 };
96
97 /* eslint-disable no-unused-vars */
98 /**
99 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
100 * Actions can be made available for specific contexts (modes) and circumstances
101 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
102 *
103 * ActionSets contain two types of actions:
104 *
105 * - 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.
106 * - Other: Other actions include all non-special visible actions.
107 *
108 * See the [OOUI documentation on MediaWiki][1] for more information.
109 *
110 * @example
111 * // Example: An action set used in a process dialog
112 * function MyProcessDialog( config ) {
113 * MyProcessDialog.parent.call( this, config );
114 * }
115 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
116 * MyProcessDialog.static.title = 'An action set in a process dialog';
117 * MyProcessDialog.static.name = 'myProcessDialog';
118 * // An action set that uses modes ('edit' and 'help' mode, in this example).
119 * MyProcessDialog.static.actions = [
120 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'progressive' ] },
121 * { action: 'help', modes: 'edit', label: 'Help' },
122 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
123 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
124 * ];
125 *
126 * MyProcessDialog.prototype.initialize = function () {
127 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
128 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
129 * 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>' );
130 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
131 * 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>' );
132 * this.stackLayout = new OO.ui.StackLayout( {
133 * items: [ this.panel1, this.panel2 ]
134 * } );
135 * this.$body.append( this.stackLayout.$element );
136 * };
137 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
138 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
139 * .next( function () {
140 * this.actions.setMode( 'edit' );
141 * }, this );
142 * };
143 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
144 * if ( action === 'help' ) {
145 * this.actions.setMode( 'help' );
146 * this.stackLayout.setItem( this.panel2 );
147 * } else if ( action === 'back' ) {
148 * this.actions.setMode( 'edit' );
149 * this.stackLayout.setItem( this.panel1 );
150 * } else if ( action === 'continue' ) {
151 * var dialog = this;
152 * return new OO.ui.Process( function () {
153 * dialog.close();
154 * } );
155 * }
156 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
157 * };
158 * MyProcessDialog.prototype.getBodyHeight = function () {
159 * return this.panel1.$element.outerHeight( true );
160 * };
161 * var windowManager = new OO.ui.WindowManager();
162 * $( document.body ).append( windowManager.$element );
163 * var dialog = new MyProcessDialog( {
164 * size: 'medium'
165 * } );
166 * windowManager.addWindows( [ dialog ] );
167 * windowManager.openWindow( dialog );
168 *
169 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
170 *
171 * @abstract
172 * @class
173 * @mixins OO.EventEmitter
174 *
175 * @constructor
176 * @param {Object} [config] Configuration options
177 */
178 OO.ui.ActionSet = function OoUiActionSet( config ) {
179 // Configuration initialization
180 config = config || {};
181
182 // Mixin constructors
183 OO.EventEmitter.call( this );
184
185 // Properties
186 this.list = [];
187 this.categories = {
188 actions: 'getAction',
189 flags: 'getFlags',
190 modes: 'getModes'
191 };
192 this.categorized = {};
193 this.special = {};
194 this.others = [];
195 this.organized = false;
196 this.changing = false;
197 this.changed = false;
198 };
199 /* eslint-enable no-unused-vars */
200
201 /* Setup */
202
203 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
204
205 /* Static Properties */
206
207 /**
208 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
209 * header of a {@link OO.ui.ProcessDialog process dialog}.
210 * See the [OOUI documentation on MediaWiki][2] for more information and examples.
211 *
212 * [2]:https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs
213 *
214 * @abstract
215 * @static
216 * @inheritable
217 * @property {string}
218 */
219 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
220
221 /* Events */
222
223 /**
224 * @event click
225 *
226 * A 'click' event is emitted when an action is clicked.
227 *
228 * @param {OO.ui.ActionWidget} action Action that was clicked
229 */
230
231 /**
232 * @event add
233 *
234 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
235 *
236 * @param {OO.ui.ActionWidget[]} added Actions added
237 */
238
239 /**
240 * @event remove
241 *
242 * A 'remove' event is emitted when actions are {@link #method-remove removed}
243 * or {@link #clear cleared}.
244 *
245 * @param {OO.ui.ActionWidget[]} added Actions removed
246 */
247
248 /**
249 * @event change
250 *
251 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
252 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
253 *
254 */
255
256 /* Methods */
257
258 /**
259 * Handle action change events.
260 *
261 * @private
262 * @fires change
263 */
264 OO.ui.ActionSet.prototype.onActionChange = function () {
265 this.organized = false;
266 if ( this.changing ) {
267 this.changed = true;
268 } else {
269 this.emit( 'change' );
270 }
271 };
272
273 /**
274 * Check if an action is one of the special actions.
275 *
276 * @param {OO.ui.ActionWidget} action Action to check
277 * @return {boolean} Action is special
278 */
279 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
280 var flag;
281
282 for ( flag in this.special ) {
283 if ( action === this.special[ flag ] ) {
284 return true;
285 }
286 }
287
288 return false;
289 };
290
291 /**
292 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
293 * or ‘disabled’.
294 *
295 * @param {Object} [filters] Filters to use, omit to get all actions
296 * @param {string|string[]} [filters.actions] Actions that action widgets must have
297 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
298 * @param {string|string[]} [filters.modes] Modes that action widgets must have
299 * @param {boolean} [filters.visible] Action widgets must be visible
300 * @param {boolean} [filters.disabled] Action widgets must be disabled
301 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
302 */
303 OO.ui.ActionSet.prototype.get = function ( filters ) {
304 var i, len, list, category, actions, index, match, matches;
305
306 if ( filters ) {
307 this.organize();
308
309 // Collect category candidates
310 matches = [];
311 for ( category in this.categorized ) {
312 list = filters[ category ];
313 if ( list ) {
314 if ( !Array.isArray( list ) ) {
315 list = [ list ];
316 }
317 for ( i = 0, len = list.length; i < len; i++ ) {
318 actions = this.categorized[ category ][ list[ i ] ];
319 if ( Array.isArray( actions ) ) {
320 matches.push.apply( matches, actions );
321 }
322 }
323 }
324 }
325 // Remove by boolean filters
326 for ( i = 0, len = matches.length; i < len; i++ ) {
327 match = matches[ i ];
328 if (
329 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
330 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
331 ) {
332 matches.splice( i, 1 );
333 len--;
334 i--;
335 }
336 }
337 // Remove duplicates
338 for ( i = 0, len = matches.length; i < len; i++ ) {
339 match = matches[ i ];
340 index = matches.lastIndexOf( match );
341 while ( index !== i ) {
342 matches.splice( index, 1 );
343 len--;
344 index = matches.lastIndexOf( match );
345 }
346 }
347 return matches;
348 }
349 return this.list.slice();
350 };
351
352 /**
353 * Get 'special' actions.
354 *
355 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
356 * Special flags can be configured in subclasses by changing the static #specialFlags property.
357 *
358 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
359 */
360 OO.ui.ActionSet.prototype.getSpecial = function () {
361 this.organize();
362 return $.extend( {}, this.special );
363 };
364
365 /**
366 * Get 'other' actions.
367 *
368 * Other actions include all non-special visible action widgets.
369 *
370 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
371 */
372 OO.ui.ActionSet.prototype.getOthers = function () {
373 this.organize();
374 return this.others.slice();
375 };
376
377 /**
378 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
379 * to be available in the specified mode will be made visible. All other actions will be hidden.
380 *
381 * @param {string} mode The mode. Only actions configured to be available in the specified
382 * mode will be made visible.
383 * @chainable
384 * @return {OO.ui.ActionSet} The widget, for chaining
385 * @fires toggle
386 * @fires change
387 */
388 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
389 var i, len, action;
390
391 this.changing = true;
392 for ( i = 0, len = this.list.length; i < len; i++ ) {
393 action = this.list[ i ];
394 action.toggle( action.hasMode( mode ) );
395 }
396
397 this.organized = false;
398 this.changing = false;
399 this.emit( 'change' );
400
401 return this;
402 };
403
404 /**
405 * Set the abilities of the specified actions.
406 *
407 * Action widgets that are configured with the specified actions will be enabled
408 * or disabled based on the boolean values specified in the `actions`
409 * parameter.
410 *
411 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
412 * values that indicate whether or not the action should be enabled.
413 * @chainable
414 * @return {OO.ui.ActionSet} The widget, for chaining
415 */
416 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
417 var i, len, action, item;
418
419 for ( i = 0, len = this.list.length; i < len; i++ ) {
420 item = this.list[ i ];
421 action = item.getAction();
422 if ( actions[ action ] !== undefined ) {
423 item.setDisabled( !actions[ action ] );
424 }
425 }
426
427 return this;
428 };
429
430 /**
431 * Executes a function once per action.
432 *
433 * When making changes to multiple actions, use this method instead of iterating over the actions
434 * manually to defer emitting a #change event until after all actions have been changed.
435 *
436 * @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
437 * @param {Function} callback Callback to run for each action; callback is invoked with three
438 * arguments: the action, the action's index, the list of actions being iterated over
439 * @chainable
440 * @return {OO.ui.ActionSet} The widget, for chaining
441 */
442 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
443 this.changed = false;
444 this.changing = true;
445 this.get( filter ).forEach( callback );
446 this.changing = false;
447 if ( this.changed ) {
448 this.emit( 'change' );
449 }
450
451 return this;
452 };
453
454 /**
455 * Add action widgets to the action set.
456 *
457 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
458 * @chainable
459 * @return {OO.ui.ActionSet} The widget, for chaining
460 * @fires add
461 * @fires change
462 */
463 OO.ui.ActionSet.prototype.add = function ( actions ) {
464 var i, len, action;
465
466 this.changing = true;
467 for ( i = 0, len = actions.length; i < len; i++ ) {
468 action = actions[ i ];
469 action.connect( this, {
470 click: [ 'emit', 'click', action ],
471 toggle: [ 'onActionChange' ]
472 } );
473 this.list.push( action );
474 }
475 this.organized = false;
476 this.emit( 'add', actions );
477 this.changing = false;
478 this.emit( 'change' );
479
480 return this;
481 };
482
483 /**
484 * Remove action widgets from the set.
485 *
486 * To remove all actions, you may wish to use the #clear method instead.
487 *
488 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
489 * @chainable
490 * @return {OO.ui.ActionSet} The widget, for chaining
491 * @fires remove
492 * @fires change
493 */
494 OO.ui.ActionSet.prototype.remove = function ( actions ) {
495 var i, len, index, action;
496
497 this.changing = true;
498 for ( i = 0, len = actions.length; i < len; i++ ) {
499 action = actions[ i ];
500 index = this.list.indexOf( action );
501 if ( index !== -1 ) {
502 action.disconnect( this );
503 this.list.splice( index, 1 );
504 }
505 }
506 this.organized = false;
507 this.emit( 'remove', actions );
508 this.changing = false;
509 this.emit( 'change' );
510
511 return this;
512 };
513
514 /**
515 * Remove all action widgets from the set.
516 *
517 * To remove only specified actions, use the {@link #method-remove remove} method instead.
518 *
519 * @chainable
520 * @return {OO.ui.ActionSet} The widget, for chaining
521 * @fires remove
522 * @fires change
523 */
524 OO.ui.ActionSet.prototype.clear = function () {
525 var i, len, action,
526 removed = this.list.slice();
527
528 this.changing = true;
529 for ( i = 0, len = this.list.length; i < len; i++ ) {
530 action = this.list[ i ];
531 action.disconnect( this );
532 }
533
534 this.list = [];
535
536 this.organized = false;
537 this.emit( 'remove', removed );
538 this.changing = false;
539 this.emit( 'change' );
540
541 return this;
542 };
543
544 /**
545 * Organize actions.
546 *
547 * This is called whenever organized information is requested. It will only reorganize the actions
548 * if something has changed since the last time it ran.
549 *
550 * @private
551 * @chainable
552 * @return {OO.ui.ActionSet} The widget, for chaining
553 */
554 OO.ui.ActionSet.prototype.organize = function () {
555 var i, iLen, j, jLen, flag, action, category, list, item, special,
556 specialFlags = this.constructor.static.specialFlags;
557
558 if ( !this.organized ) {
559 this.categorized = {};
560 this.special = {};
561 this.others = [];
562 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
563 action = this.list[ i ];
564 if ( action.isVisible() ) {
565 // Populate categories
566 for ( category in this.categories ) {
567 if ( !this.categorized[ category ] ) {
568 this.categorized[ category ] = {};
569 }
570 list = action[ this.categories[ category ] ]();
571 if ( !Array.isArray( list ) ) {
572 list = [ list ];
573 }
574 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
575 item = list[ j ];
576 if ( !this.categorized[ category ][ item ] ) {
577 this.categorized[ category ][ item ] = [];
578 }
579 this.categorized[ category ][ item ].push( action );
580 }
581 }
582 // Populate special/others
583 special = false;
584 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
585 flag = specialFlags[ j ];
586 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
587 this.special[ flag ] = action;
588 special = true;
589 break;
590 }
591 }
592 if ( !special ) {
593 this.others.push( action );
594 }
595 }
596 }
597 this.organized = true;
598 }
599
600 return this;
601 };
602
603 /**
604 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
605 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
606 * appearance and functionality of the error interface.
607 *
608 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
609 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
610 * that initiated the failed process will be disabled.
611 *
612 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
613 * process again.
614 *
615 * For an example of error interfaces, please see the [OOUI documentation on MediaWiki][1].
616 *
617 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Processes_and_errors
618 *
619 * @class
620 *
621 * @constructor
622 * @param {string|jQuery} message Description of error
623 * @param {Object} [config] Configuration options
624 * @cfg {boolean} [recoverable=true] Error is recoverable.
625 * By default, errors are recoverable, and users can try the process again.
626 * @cfg {boolean} [warning=false] Error is a warning.
627 * If the error is a warning, the error interface will include a
628 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
629 * is not triggered a second time if the user chooses to continue.
630 */
631 OO.ui.Error = function OoUiError( message, config ) {
632 // Allow passing positional parameters inside the config object
633 if ( OO.isPlainObject( message ) && config === undefined ) {
634 config = message;
635 message = config.message;
636 }
637
638 // Configuration initialization
639 config = config || {};
640
641 // Properties
642 this.message = message instanceof $ ? message : String( message );
643 this.recoverable = config.recoverable === undefined || !!config.recoverable;
644 this.warning = !!config.warning;
645 };
646
647 /* Setup */
648
649 OO.initClass( OO.ui.Error );
650
651 /* Methods */
652
653 /**
654 * Check if the error is recoverable.
655 *
656 * If the error is recoverable, users are able to try the process again.
657 *
658 * @return {boolean} Error is recoverable
659 */
660 OO.ui.Error.prototype.isRecoverable = function () {
661 return this.recoverable;
662 };
663
664 /**
665 * Check if the error is a warning.
666 *
667 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
668 *
669 * @return {boolean} Error is warning
670 */
671 OO.ui.Error.prototype.isWarning = function () {
672 return this.warning;
673 };
674
675 /**
676 * Get error message as DOM nodes.
677 *
678 * @return {jQuery} Error message in DOM nodes
679 */
680 OO.ui.Error.prototype.getMessage = function () {
681 return this.message instanceof $ ?
682 this.message.clone() :
683 $( '<div>' ).text( this.message ).contents();
684 };
685
686 /**
687 * Get the error message text.
688 *
689 * @return {string} Error message
690 */
691 OO.ui.Error.prototype.getMessageText = function () {
692 return this.message instanceof $ ? this.message.text() : this.message;
693 };
694
695 /**
696 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
697 * or a function:
698 *
699 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
700 * - **promise**: the process will continue to the next step when the promise is successfully resolved
701 * or stop if the promise is rejected.
702 * - **function**: the process will execute the function. The process will stop if the function returns
703 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
704 * will wait for that number of milliseconds before proceeding.
705 *
706 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
707 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
708 * its remaining steps will not be performed.
709 *
710 * @class
711 *
712 * @constructor
713 * @param {number|jQuery.Promise|Function} step Number of milliseconds to wait before proceeding, promise
714 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
715 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
716 * a number or promise.
717 */
718 OO.ui.Process = function ( step, context ) {
719 // Properties
720 this.steps = [];
721
722 // Initialization
723 if ( step !== undefined ) {
724 this.next( step, context );
725 }
726 };
727
728 /* Setup */
729
730 OO.initClass( OO.ui.Process );
731
732 /* Methods */
733
734 /**
735 * Start the process.
736 *
737 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
738 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
739 * and any remaining steps are not performed.
740 */
741 OO.ui.Process.prototype.execute = function () {
742 var i, len, promise;
743
744 /**
745 * Continue execution.
746 *
747 * @ignore
748 * @param {Array} step A function and the context it should be called in
749 * @return {Function} Function that continues the process
750 */
751 function proceed( step ) {
752 return function () {
753 // Execute step in the correct context
754 var deferred,
755 result = step.callback.call( step.context );
756
757 if ( result === false ) {
758 // Use rejected promise for boolean false results
759 return $.Deferred().reject( [] ).promise();
760 }
761 if ( typeof result === 'number' ) {
762 if ( result < 0 ) {
763 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
764 }
765 // Use a delayed promise for numbers, expecting them to be in milliseconds
766 deferred = $.Deferred();
767 setTimeout( deferred.resolve, result );
768 return deferred.promise();
769 }
770 if ( result instanceof OO.ui.Error ) {
771 // Use rejected promise for error
772 return $.Deferred().reject( [ result ] ).promise();
773 }
774 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
775 // Use rejected promise for list of errors
776 return $.Deferred().reject( result ).promise();
777 }
778 // Duck-type the object to see if it can produce a promise
779 if ( result && typeof result.promise === 'function' ) {
780 // Use a promise generated from the result
781 return result.promise();
782 }
783 // Use resolved promise for other results
784 return $.Deferred().resolve().promise();
785 };
786 }
787
788 if ( this.steps.length ) {
789 // Generate a chain reaction of promises
790 promise = proceed( this.steps[ 0 ] )();
791 for ( i = 1, len = this.steps.length; i < len; i++ ) {
792 promise = promise.then( proceed( this.steps[ i ] ) );
793 }
794 } else {
795 promise = $.Deferred().resolve().promise();
796 }
797
798 return promise;
799 };
800
801 /**
802 * Create a process step.
803 *
804 * @private
805 * @param {number|jQuery.Promise|Function} step
806 *
807 * - Number of milliseconds to wait before proceeding
808 * - Promise that must be resolved before proceeding
809 * - Function to execute
810 * - If the function returns a boolean false the process will stop
811 * - If the function returns a promise, the process will continue to the next
812 * step when the promise is resolved or stop if the promise is rejected
813 * - If the function returns a number, the process will wait for that number of
814 * milliseconds before proceeding
815 * @param {Object} [context=null] Execution context of the function. The context is
816 * ignored if the step is a number or promise.
817 * @return {Object} Step object, with `callback` and `context` properties
818 */
819 OO.ui.Process.prototype.createStep = function ( step, context ) {
820 if ( typeof step === 'number' || typeof step.promise === 'function' ) {
821 return {
822 callback: function () {
823 return step;
824 },
825 context: null
826 };
827 }
828 if ( typeof step === 'function' ) {
829 return {
830 callback: step,
831 context: context
832 };
833 }
834 throw new Error( 'Cannot create process step: number, promise or function expected' );
835 };
836
837 /**
838 * Add step to the beginning of the process.
839 *
840 * @inheritdoc #createStep
841 * @return {OO.ui.Process} this
842 * @chainable
843 */
844 OO.ui.Process.prototype.first = function ( step, context ) {
845 this.steps.unshift( this.createStep( step, context ) );
846 return this;
847 };
848
849 /**
850 * Add step to the end of the process.
851 *
852 * @inheritdoc #createStep
853 * @return {OO.ui.Process} this
854 * @chainable
855 */
856 OO.ui.Process.prototype.next = function ( step, context ) {
857 this.steps.push( this.createStep( step, context ) );
858 return this;
859 };
860
861 /**
862 * A window instance represents the life cycle for one single opening of a window
863 * until its closing.
864 *
865 * While OO.ui.WindowManager will reuse OO.ui.Window objects, each time a window is
866 * opened, a new lifecycle starts.
867 *
868 * For more information, please see the [OOUI documentation on MediaWiki] [1].
869 *
870 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows
871 *
872 * @class
873 *
874 * @constructor
875 */
876 OO.ui.WindowInstance = function OoUiWindowInstance() {
877 var deferreds = {
878 opening: $.Deferred(),
879 opened: $.Deferred(),
880 closing: $.Deferred(),
881 closed: $.Deferred()
882 };
883
884 /**
885 * @private
886 * @property {Object}
887 */
888 this.deferreds = deferreds;
889
890 // Set these up as chained promises so that rejecting of
891 // an earlier stage automatically rejects the subsequent
892 // would-be stages as well.
893
894 /**
895 * @property {jQuery.Promise}
896 */
897 this.opening = deferreds.opening.promise();
898 /**
899 * @property {jQuery.Promise}
900 */
901 this.opened = this.opening.then( function () {
902 return deferreds.opened;
903 } );
904 /**
905 * @property {jQuery.Promise}
906 */
907 this.closing = this.opened.then( function () {
908 return deferreds.closing;
909 } );
910 /**
911 * @property {jQuery.Promise}
912 */
913 this.closed = this.closing.then( function () {
914 return deferreds.closed;
915 } );
916 };
917
918 /* Setup */
919
920 OO.initClass( OO.ui.WindowInstance );
921
922 /**
923 * Check if window is opening.
924 *
925 * @return {boolean} Window is opening
926 */
927 OO.ui.WindowInstance.prototype.isOpening = function () {
928 return this.deferreds.opened.state() === 'pending';
929 };
930
931 /**
932 * Check if window is opened.
933 *
934 * @return {boolean} Window is opened
935 */
936 OO.ui.WindowInstance.prototype.isOpened = function () {
937 return this.deferreds.opened.state() === 'resolved' &&
938 this.deferreds.closing.state() === 'pending';
939 };
940
941 /**
942 * Check if window is closing.
943 *
944 * @return {boolean} Window is closing
945 */
946 OO.ui.WindowInstance.prototype.isClosing = function () {
947 return this.deferreds.closing.state() === 'resolved' &&
948 this.deferreds.closed.state() === 'pending';
949 };
950
951 /**
952 * Check if window is closed.
953 *
954 * @return {boolean} Window is closed
955 */
956 OO.ui.WindowInstance.prototype.isClosed = function () {
957 return this.deferreds.closed.state() === 'resolved';
958 };
959
960 /**
961 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
962 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
963 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
964 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
965 * pertinent data and reused.
966 *
967 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
968 * `opened`, and `closing`, which represent the primary stages of the cycle:
969 *
970 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
971 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
972 *
973 * - an `opening` event is emitted with an `opening` promise
974 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before the
975 * window’s {@link OO.ui.Window#method-setup setup} method is called which executes OO.ui.Window#getSetupProcess.
976 * - a `setup` progress notification is emitted from the `opening` promise
977 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before the
978 * window’s {@link OO.ui.Window#method-ready ready} method is called which executes OO.ui.Window#getReadyProcess.
979 * - a `ready` progress notification is emitted from the `opening` promise
980 * - the `opening` promise is resolved with an `opened` promise
981 *
982 * **Opened**: the window is now open.
983 *
984 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
985 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
986 * to close the window.
987 *
988 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
989 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
990 * the window's {@link OO.ui.Window#getHoldProcess getHoldProcess} method is called on the
991 * window and its result executed
992 * - a `hold` progress notification is emitted from the `closing` promise
993 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
994 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
995 * window and its result executed
996 * - a `teardown` progress notification is emitted from the `closing` promise
997 * - the `closing` promise is resolved. The window is now closed
998 *
999 * See the [OOUI documentation on MediaWiki][1] for more information.
1000 *
1001 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
1002 *
1003 * @class
1004 * @extends OO.ui.Element
1005 * @mixins OO.EventEmitter
1006 *
1007 * @constructor
1008 * @param {Object} [config] Configuration options
1009 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
1010 * Note that window classes that are instantiated with a factory must have
1011 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
1012 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
1013 */
1014 OO.ui.WindowManager = function OoUiWindowManager( config ) {
1015 // Configuration initialization
1016 config = config || {};
1017
1018 // Parent constructor
1019 OO.ui.WindowManager.parent.call( this, config );
1020
1021 // Mixin constructors
1022 OO.EventEmitter.call( this );
1023
1024 // Properties
1025 this.factory = config.factory;
1026 this.modal = config.modal === undefined || !!config.modal;
1027 this.windows = {};
1028 // Deprecated placeholder promise given to compatOpening in openWindow()
1029 // that is resolved in closeWindow().
1030 this.compatOpened = null;
1031 this.preparingToOpen = null;
1032 this.preparingToClose = null;
1033 this.currentWindow = null;
1034 this.globalEvents = false;
1035 this.$returnFocusTo = null;
1036 this.$ariaHidden = null;
1037 this.onWindowResizeTimeout = null;
1038 this.onWindowResizeHandler = this.onWindowResize.bind( this );
1039 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
1040
1041 // Initialization
1042 this.$element
1043 .addClass( 'oo-ui-windowManager' )
1044 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
1045 if ( this.modal ) {
1046 this.$element.attr( 'aria-hidden', true );
1047 }
1048 };
1049
1050 /* Setup */
1051
1052 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
1053 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
1054
1055 /* Events */
1056
1057 /**
1058 * An 'opening' event is emitted when the window begins to be opened.
1059 *
1060 * @event opening
1061 * @param {OO.ui.Window} win Window that's being opened
1062 * @param {jQuery.Promise} opened A promise resolved with a value when the window is opened successfully.
1063 * This promise also emits `setup` and `ready` notifications. When this promise is resolved, the first
1064 * argument of the value is an 'closed' promise, the second argument is the opening data.
1065 * @param {Object} data Window opening data
1066 */
1067
1068 /**
1069 * A 'closing' event is emitted when the window begins to be closed.
1070 *
1071 * @event closing
1072 * @param {OO.ui.Window} win Window that's being closed
1073 * @param {jQuery.Promise} closed A promise resolved with a value when the window is closed successfully.
1074 * This promise also emits `hold` and `teardown` notifications. When this promise is resolved, the first
1075 * argument of its value is the closing data.
1076 * @param {Object} data Window closing data
1077 */
1078
1079 /**
1080 * A 'resize' event is emitted when a window is resized.
1081 *
1082 * @event resize
1083 * @param {OO.ui.Window} win Window that was resized
1084 */
1085
1086 /* Static Properties */
1087
1088 /**
1089 * Map of the symbolic name of each window size and its CSS properties.
1090 *
1091 * @static
1092 * @inheritable
1093 * @property {Object}
1094 */
1095 OO.ui.WindowManager.static.sizes = {
1096 small: {
1097 width: 300
1098 },
1099 medium: {
1100 width: 500
1101 },
1102 large: {
1103 width: 700
1104 },
1105 larger: {
1106 width: 900
1107 },
1108 full: {
1109 // These can be non-numeric because they are never used in calculations
1110 width: '100%',
1111 height: '100%'
1112 }
1113 };
1114
1115 /**
1116 * Symbolic name of the default window size.
1117 *
1118 * The default size is used if the window's requested size is not recognized.
1119 *
1120 * @static
1121 * @inheritable
1122 * @property {string}
1123 */
1124 OO.ui.WindowManager.static.defaultSize = 'medium';
1125
1126 /* Methods */
1127
1128 /**
1129 * Handle window resize events.
1130 *
1131 * @private
1132 * @param {jQuery.Event} e Window resize event
1133 */
1134 OO.ui.WindowManager.prototype.onWindowResize = function () {
1135 clearTimeout( this.onWindowResizeTimeout );
1136 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
1137 };
1138
1139 /**
1140 * Handle window resize events.
1141 *
1142 * @private
1143 * @param {jQuery.Event} e Window resize event
1144 */
1145 OO.ui.WindowManager.prototype.afterWindowResize = function () {
1146 var currentFocusedElement = document.activeElement;
1147 if ( this.currentWindow ) {
1148 this.updateWindowSize( this.currentWindow );
1149
1150 // Restore focus to the original element if it has changed.
1151 // When a layout change is made on resize inputs lose focus
1152 // on Android (Chrome and Firefox). See T162127.
1153 if ( currentFocusedElement !== document.activeElement ) {
1154 currentFocusedElement.focus();
1155 }
1156 }
1157 };
1158
1159 /**
1160 * Check if window is opening.
1161 *
1162 * @param {OO.ui.Window} win Window to check
1163 * @return {boolean} Window is opening
1164 */
1165 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
1166 return win === this.currentWindow && !!this.lifecycle &&
1167 this.lifecycle.isOpening();
1168 };
1169
1170 /**
1171 * Check if window is closing.
1172 *
1173 * @param {OO.ui.Window} win Window to check
1174 * @return {boolean} Window is closing
1175 */
1176 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
1177 return win === this.currentWindow && !!this.lifecycle &&
1178 this.lifecycle.isClosing();
1179 };
1180
1181 /**
1182 * Check if window is opened.
1183 *
1184 * @param {OO.ui.Window} win Window to check
1185 * @return {boolean} Window is opened
1186 */
1187 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
1188 return win === this.currentWindow && !!this.lifecycle &&
1189 this.lifecycle.isOpened();
1190 };
1191
1192 /**
1193 * Check if a window is being managed.
1194 *
1195 * @param {OO.ui.Window} win Window to check
1196 * @return {boolean} Window is being managed
1197 */
1198 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
1199 var name;
1200
1201 for ( name in this.windows ) {
1202 if ( this.windows[ name ] === win ) {
1203 return true;
1204 }
1205 }
1206
1207 return false;
1208 };
1209
1210 /**
1211 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
1212 *
1213 * @param {OO.ui.Window} win Window being opened
1214 * @param {Object} [data] Window opening data
1215 * @return {number} Milliseconds to wait
1216 */
1217 OO.ui.WindowManager.prototype.getSetupDelay = function () {
1218 return 0;
1219 };
1220
1221 /**
1222 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
1223 *
1224 * @param {OO.ui.Window} win Window being opened
1225 * @param {Object} [data] Window opening data
1226 * @return {number} Milliseconds to wait
1227 */
1228 OO.ui.WindowManager.prototype.getReadyDelay = function () {
1229 return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0;
1230 };
1231
1232 /**
1233 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
1234 *
1235 * @param {OO.ui.Window} win Window being closed
1236 * @param {Object} [data] Window closing data
1237 * @return {number} Milliseconds to wait
1238 */
1239 OO.ui.WindowManager.prototype.getHoldDelay = function () {
1240 return 0;
1241 };
1242
1243 /**
1244 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
1245 * executing the ‘teardown’ process.
1246 *
1247 * @param {OO.ui.Window} win Window being closed
1248 * @param {Object} [data] Window closing data
1249 * @return {number} Milliseconds to wait
1250 */
1251 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
1252 return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0;
1253 };
1254
1255 /**
1256 * Get a window by its symbolic name.
1257 *
1258 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
1259 * instantiated and added to the window manager automatically. Please see the [OOUI documentation on MediaWiki][3]
1260 * for more information about using factories.
1261 * [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
1262 *
1263 * @param {string} name Symbolic name of the window
1264 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
1265 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
1266 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
1267 */
1268 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
1269 var deferred = $.Deferred(),
1270 win = this.windows[ name ];
1271
1272 if ( !( win instanceof OO.ui.Window ) ) {
1273 if ( this.factory ) {
1274 if ( !this.factory.lookup( name ) ) {
1275 deferred.reject( new OO.ui.Error(
1276 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
1277 ) );
1278 } else {
1279 win = this.factory.create( name );
1280 this.addWindows( [ win ] );
1281 deferred.resolve( win );
1282 }
1283 } else {
1284 deferred.reject( new OO.ui.Error(
1285 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
1286 ) );
1287 }
1288 } else {
1289 deferred.resolve( win );
1290 }
1291
1292 return deferred.promise();
1293 };
1294
1295 /**
1296 * Get current window.
1297 *
1298 * @return {OO.ui.Window|null} Currently opening/opened/closing window
1299 */
1300 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
1301 return this.currentWindow;
1302 };
1303
1304 /* eslint-disable valid-jsdoc */
1305 /**
1306 * Open a window.
1307 *
1308 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
1309 * @param {Object} [data] Window opening data
1310 * @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when closed.
1311 * Defaults the current activeElement. If set to null, focus isn't changed on close.
1312 * @return {OO.ui.WindowInstance} A lifecycle object representing this particular
1313 * opening of the window. For backwards-compatibility, then object is also a Thenable that is resolved
1314 * when the window is done opening, with nested promise for when closing starts. This behaviour
1315 * is deprecated and is not compatible with jQuery 3. See T163510.
1316 * @fires opening
1317 */
1318 OO.ui.WindowManager.prototype.openWindow = function ( win, data, lifecycle, compatOpening ) {
1319 /* eslint-enable valid-jsdoc */
1320 var error,
1321 manager = this;
1322 data = data || {};
1323
1324 // Internal parameter 'lifecycle' allows this method to always return
1325 // a lifecycle even if the window still needs to be created
1326 // asynchronously when 'win' is a string.
1327 lifecycle = lifecycle || new OO.ui.WindowInstance();
1328 compatOpening = compatOpening || $.Deferred();
1329
1330 // Turn lifecycle into a Thenable for backwards-compatibility with
1331 // the deprecated nested-promise behaviour, see T163510.
1332 [ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
1333 .forEach( function ( method ) {
1334 lifecycle[ method ] = function () {
1335 OO.ui.warnDeprecation(
1336 'Using the return value of openWindow as a promise is deprecated. ' +
1337 'Use .openWindow( ... ).opening.' + method + '( ... ) instead.'
1338 );
1339 return compatOpening[ method ].apply( this, arguments );
1340 };
1341 } );
1342
1343 // Argument handling
1344 if ( typeof win === 'string' ) {
1345 this.getWindow( win ).then(
1346 function ( win ) {
1347 manager.openWindow( win, data, lifecycle, compatOpening );
1348 },
1349 function ( err ) {
1350 lifecycle.deferreds.opening.reject( err );
1351 }
1352 );
1353 return lifecycle;
1354 }
1355
1356 // Error handling
1357 if ( !this.hasWindow( win ) ) {
1358 error = 'Cannot open window: window is not attached to manager';
1359 } else if ( this.lifecycle && this.lifecycle.isOpened() ) {
1360 error = 'Cannot open window: another window is open';
1361 } else if ( this.preparingToOpen || ( this.lifecycle && this.lifecycle.isOpening() ) ) {
1362 error = 'Cannot open window: another window is opening';
1363 }
1364
1365 if ( error ) {
1366 compatOpening.reject( new OO.ui.Error( error ) );
1367 lifecycle.deferreds.opening.reject( new OO.ui.Error( error ) );
1368 return lifecycle;
1369 }
1370
1371 // If a window is currently closing, wait for it to complete
1372 this.preparingToOpen = $.when( this.lifecycle && this.lifecycle.closed );
1373 // Ensure handlers get called after preparingToOpen is set
1374 this.preparingToOpen.done( function () {
1375 if ( manager.modal ) {
1376 manager.toggleGlobalEvents( true );
1377 manager.toggleAriaIsolation( true );
1378 }
1379 manager.$returnFocusTo = data.$returnFocusTo !== undefined ? data.$returnFocusTo : $( document.activeElement );
1380 manager.currentWindow = win;
1381 manager.lifecycle = lifecycle;
1382 manager.preparingToOpen = null;
1383 manager.emit( 'opening', win, compatOpening, data );
1384 lifecycle.deferreds.opening.resolve( data );
1385 setTimeout( function () {
1386 manager.compatOpened = $.Deferred();
1387 win.setup( data ).then( function () {
1388 compatOpening.notify( { state: 'setup' } );
1389 setTimeout( function () {
1390 win.ready( data ).then( function () {
1391 compatOpening.notify( { state: 'ready' } );
1392 lifecycle.deferreds.opened.resolve( data );
1393 compatOpening.resolve( manager.compatOpened.promise(), data );
1394 }, function () {
1395 lifecycle.deferreds.opened.reject();
1396 compatOpening.reject();
1397 manager.closeWindow( win );
1398 } );
1399 }, manager.getReadyDelay() );
1400 }, function () {
1401 lifecycle.deferreds.opened.reject();
1402 compatOpening.reject();
1403 manager.closeWindow( win );
1404 } );
1405 }, manager.getSetupDelay() );
1406 } );
1407
1408 return lifecycle;
1409 };
1410
1411 /**
1412 * Close a window.
1413 *
1414 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
1415 * @param {Object} [data] Window closing data
1416 * @return {OO.ui.WindowInstance} A lifecycle object representing this particular
1417 * opening of the window. For backwards-compatibility, the object is also a Thenable that is resolved
1418 * when the window is done closing, see T163510.
1419 * @fires closing
1420 */
1421 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
1422 var error,
1423 manager = this,
1424 compatClosing = $.Deferred(),
1425 lifecycle = this.lifecycle,
1426 compatOpened;
1427
1428 // Argument handling
1429 if ( typeof win === 'string' ) {
1430 win = this.windows[ win ];
1431 } else if ( !this.hasWindow( win ) ) {
1432 win = null;
1433 }
1434
1435 // Error handling
1436 if ( !lifecycle ) {
1437 error = 'Cannot close window: no window is currently open';
1438 } else if ( !win ) {
1439 error = 'Cannot close window: window is not attached to manager';
1440 } else if ( win !== this.currentWindow || this.lifecycle.isClosed() ) {
1441 error = 'Cannot close window: window already closed with different data';
1442 } else if ( this.preparingToClose || this.lifecycle.isClosing() ) {
1443 error = 'Cannot close window: window already closing with different data';
1444 }
1445
1446 if ( error ) {
1447 // This function was called for the wrong window and we don't want to mess with the current
1448 // window's state.
1449 lifecycle = new OO.ui.WindowInstance();
1450 // Pretend the window has been opened, so that we can pretend to fail to close it.
1451 lifecycle.deferreds.opening.resolve( {} );
1452 lifecycle.deferreds.opened.resolve( {} );
1453 }
1454
1455 // Turn lifecycle into a Thenable for backwards-compatibility with
1456 // the deprecated nested-promise behaviour, see T163510.
1457 [ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
1458 .forEach( function ( method ) {
1459 lifecycle[ method ] = function () {
1460 OO.ui.warnDeprecation(
1461 'Using the return value of closeWindow as a promise is deprecated. ' +
1462 'Use .closeWindow( ... ).closed.' + method + '( ... ) instead.'
1463 );
1464 return compatClosing[ method ].apply( this, arguments );
1465 };
1466 } );
1467
1468 if ( error ) {
1469 compatClosing.reject( new OO.ui.Error( error ) );
1470 lifecycle.deferreds.closing.reject( new OO.ui.Error( error ) );
1471 return lifecycle;
1472 }
1473
1474 // If the window is currently opening, close it when it's done
1475 this.preparingToClose = $.when( this.lifecycle.opened );
1476 // Ensure handlers get called after preparingToClose is set
1477 this.preparingToClose.always( function () {
1478 manager.preparingToClose = null;
1479 manager.emit( 'closing', win, compatClosing, data );
1480 lifecycle.deferreds.closing.resolve( data );
1481 compatOpened = manager.compatOpened;
1482 manager.compatOpened = null;
1483 compatOpened.resolve( compatClosing.promise(), data );
1484 setTimeout( function () {
1485 win.hold( data ).then( function () {
1486 compatClosing.notify( { state: 'hold' } );
1487 setTimeout( function () {
1488 win.teardown( data ).then( function () {
1489 compatClosing.notify( { state: 'teardown' } );
1490 if ( manager.modal ) {
1491 manager.toggleGlobalEvents( false );
1492 manager.toggleAriaIsolation( false );
1493 }
1494 if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) {
1495 manager.$returnFocusTo[ 0 ].focus();
1496 }
1497 manager.currentWindow = null;
1498 manager.lifecycle = null;
1499 lifecycle.deferreds.closed.resolve( data );
1500 compatClosing.resolve( data );
1501 } );
1502 }, manager.getTeardownDelay() );
1503 } );
1504 }, manager.getHoldDelay() );
1505 } );
1506
1507 return lifecycle;
1508 };
1509
1510 /**
1511 * Add windows to the window manager.
1512 *
1513 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
1514 * See the [OOUI documentation on MediaWiki] [2] for examples.
1515 * [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
1516 *
1517 * This function can be called in two manners:
1518 *
1519 * 1. `.addWindows( [ windowA, windowB, ... ] )` (where `windowA`, `windowB` are OO.ui.Window objects)
1520 *
1521 * This syntax registers windows under the symbolic names defined in their `.static.name`
1522 * properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling
1523 * `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the
1524 * static name to be set, otherwise an exception will be thrown.
1525 *
1526 * This is the recommended way, as it allows for an easier switch to using a window factory.
1527 *
1528 * 2. `.addWindows( { nameA: windowA, nameB: windowB, ... } )`
1529 *
1530 * This syntax registers windows under the explicitly given symbolic names. In this example,
1531 * calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what
1532 * its `.static.name` is set to. The static name is not required to be set.
1533 *
1534 * This should only be used if you need to override the default symbolic names.
1535 *
1536 * Example:
1537 *
1538 * var windowManager = new OO.ui.WindowManager();
1539 * $( document.body ).append( windowManager.$element );
1540 *
1541 * // Add a window under the default name: see OO.ui.MessageDialog.static.name
1542 * windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
1543 * // Add a window under an explicit name
1544 * windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } );
1545 *
1546 * // Open window by default name
1547 * windowManager.openWindow( 'message' );
1548 * // Open window by explicitly given name
1549 * windowManager.openWindow( 'myMessageDialog' );
1550 *
1551 *
1552 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
1553 * by reference, symbolic name, or explicitly defined symbolic names.
1554 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
1555 * explicit nor a statically configured symbolic name.
1556 */
1557 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
1558 var i, len, win, name, list;
1559
1560 if ( Array.isArray( windows ) ) {
1561 // Convert to map of windows by looking up symbolic names from static configuration
1562 list = {};
1563 for ( i = 0, len = windows.length; i < len; i++ ) {
1564 name = windows[ i ].constructor.static.name;
1565 if ( !name ) {
1566 throw new Error( 'Windows must have a `name` static property defined.' );
1567 }
1568 list[ name ] = windows[ i ];
1569 }
1570 } else if ( OO.isPlainObject( windows ) ) {
1571 list = windows;
1572 }
1573
1574 // Add windows
1575 for ( name in list ) {
1576 win = list[ name ];
1577 this.windows[ name ] = win.toggle( false );
1578 this.$element.append( win.$element );
1579 win.setManager( this );
1580 }
1581 };
1582
1583 /**
1584 * Remove the specified windows from the windows manager.
1585 *
1586 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
1587 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
1588 * longer listens to events, use the #destroy method.
1589 *
1590 * @param {string[]} names Symbolic names of windows to remove
1591 * @return {jQuery.Promise} Promise resolved when window is closed and removed
1592 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
1593 */
1594 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
1595 var i, len, win, name, cleanupWindow,
1596 manager = this,
1597 promises = [],
1598 cleanup = function ( name, win ) {
1599 delete manager.windows[ name ];
1600 win.$element.detach();
1601 };
1602
1603 for ( i = 0, len = names.length; i < len; i++ ) {
1604 name = names[ i ];
1605 win = this.windows[ name ];
1606 if ( !win ) {
1607 throw new Error( 'Cannot remove window' );
1608 }
1609 cleanupWindow = cleanup.bind( null, name, win );
1610 promises.push( this.closeWindow( name ).closed.then( cleanupWindow, cleanupWindow ) );
1611 }
1612
1613 return $.when.apply( $, promises );
1614 };
1615
1616 /**
1617 * Remove all windows from the window manager.
1618 *
1619 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
1620 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
1621 * To remove just a subset of windows, use the #removeWindows method.
1622 *
1623 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
1624 */
1625 OO.ui.WindowManager.prototype.clearWindows = function () {
1626 return this.removeWindows( Object.keys( this.windows ) );
1627 };
1628
1629 /**
1630 * Set dialog size. In general, this method should not be called directly.
1631 *
1632 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
1633 *
1634 * @param {OO.ui.Window} win Window to update, should be the current window
1635 * @chainable
1636 * @return {OO.ui.WindowManager} The manager, for chaining
1637 */
1638 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
1639 var isFullscreen;
1640
1641 // Bypass for non-current, and thus invisible, windows
1642 if ( win !== this.currentWindow ) {
1643 return;
1644 }
1645
1646 isFullscreen = win.getSize() === 'full';
1647
1648 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
1649 this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
1650 win.setDimensions( win.getSizeProperties() );
1651
1652 this.emit( 'resize', win );
1653
1654 return this;
1655 };
1656
1657 /**
1658 * Bind or unbind global events for scrolling.
1659 *
1660 * @private
1661 * @param {boolean} [on] Bind global events
1662 * @chainable
1663 * @return {OO.ui.WindowManager} The manager, for chaining
1664 */
1665 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
1666 var scrollWidth, bodyMargin,
1667 $body = $( this.getElementDocument().body ),
1668 // We could have multiple window managers open so only modify
1669 // the body css at the bottom of the stack
1670 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
1671
1672 on = on === undefined ? !!this.globalEvents : !!on;
1673
1674 if ( on ) {
1675 if ( !this.globalEvents ) {
1676 $( this.getElementWindow() ).on( {
1677 // Start listening for top-level window dimension changes
1678 'orientationchange resize': this.onWindowResizeHandler
1679 } );
1680 if ( stackDepth === 0 ) {
1681 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
1682 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
1683 $body.addClass( 'oo-ui-windowManager-modal-active' );
1684 $body.css( 'margin-right', bodyMargin + scrollWidth );
1685 }
1686 stackDepth++;
1687 this.globalEvents = true;
1688 }
1689 } else if ( this.globalEvents ) {
1690 $( this.getElementWindow() ).off( {
1691 // Stop listening for top-level window dimension changes
1692 'orientationchange resize': this.onWindowResizeHandler
1693 } );
1694 stackDepth--;
1695 if ( stackDepth === 0 ) {
1696 $body.removeClass( 'oo-ui-windowManager-modal-active' );
1697 $body.css( 'margin-right', '' );
1698 }
1699 this.globalEvents = false;
1700 }
1701 $body.data( 'windowManagerGlobalEvents', stackDepth );
1702
1703 return this;
1704 };
1705
1706 /**
1707 * Toggle screen reader visibility of content other than the window manager.
1708 *
1709 * @private
1710 * @param {boolean} [isolate] Make only the window manager visible to screen readers
1711 * @chainable
1712 * @return {OO.ui.WindowManager} The manager, for chaining
1713 */
1714 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
1715 var $topLevelElement;
1716 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
1717
1718 if ( isolate ) {
1719 if ( !this.$ariaHidden ) {
1720 // Find the top level element containing the window manager or the
1721 // window manager's element itself in case its a direct child of body
1722 $topLevelElement = this.$element.parentsUntil( 'body' ).last();
1723 $topLevelElement = $topLevelElement.length === 0 ? this.$element : $topLevelElement;
1724
1725 // In case previously set by another window manager
1726 this.$element.removeAttr( 'aria-hidden' );
1727
1728 // Hide everything other than the window manager from screen readers
1729 this.$ariaHidden = $( document.body )
1730 .children()
1731 .not( 'script' )
1732 .not( $topLevelElement )
1733 .attr( 'aria-hidden', true );
1734 }
1735 } else if ( this.$ariaHidden ) {
1736 // Restore screen reader visibility
1737 this.$ariaHidden.removeAttr( 'aria-hidden' );
1738 this.$ariaHidden = null;
1739
1740 // and hide the window manager
1741 this.$element.attr( 'aria-hidden', true );
1742 }
1743
1744 return this;
1745 };
1746
1747 /**
1748 * Destroy the window manager.
1749 *
1750 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
1751 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
1752 * instead.
1753 */
1754 OO.ui.WindowManager.prototype.destroy = function () {
1755 this.toggleGlobalEvents( false );
1756 this.toggleAriaIsolation( false );
1757 this.clearWindows();
1758 this.$element.remove();
1759 };
1760
1761 /**
1762 * A window is a container for elements that are in a child frame. They are used with
1763 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1764 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1765 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1766 * the window manager will choose a sensible fallback.
1767 *
1768 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1769 * different processes are executed:
1770 *
1771 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1772 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1773 * the window.
1774 *
1775 * - {@link #getSetupProcess} method is called and its result executed
1776 * - {@link #getReadyProcess} method is called and its result executed
1777 *
1778 * **opened**: The window is now open
1779 *
1780 * **closing**: The closing stage begins when the window manager's
1781 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1782 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1783 *
1784 * - {@link #getHoldProcess} method is called and its result executed
1785 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1786 *
1787 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1788 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1789 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1790 * processing can complete. Always assume window processes are executed asynchronously.
1791 *
1792 * For more information, please see the [OOUI documentation on MediaWiki] [1].
1793 *
1794 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows
1795 *
1796 * @abstract
1797 * @class
1798 * @extends OO.ui.Element
1799 * @mixins OO.EventEmitter
1800 *
1801 * @constructor
1802 * @param {Object} [config] Configuration options
1803 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1804 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1805 */
1806 OO.ui.Window = function OoUiWindow( config ) {
1807 // Configuration initialization
1808 config = config || {};
1809
1810 // Parent constructor
1811 OO.ui.Window.parent.call( this, config );
1812
1813 // Mixin constructors
1814 OO.EventEmitter.call( this );
1815
1816 // Properties
1817 this.manager = null;
1818 this.size = config.size || this.constructor.static.size;
1819 this.$frame = $( '<div>' );
1820 /**
1821 * Overlay element to use for the `$overlay` configuration option of widgets that support it.
1822 * Things put inside of it are overlaid on top of the window and are not bound to its dimensions.
1823 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
1824 *
1825 * MyDialog.prototype.initialize = function () {
1826 * ...
1827 * var popupButton = new OO.ui.PopupButtonWidget( {
1828 * $overlay: this.$overlay,
1829 * label: 'Popup button',
1830 * popup: {
1831 * $content: $( '<p>Popup contents.</p><p>Popup contents.</p><p>Popup contents.</p>' ),
1832 * padded: true
1833 * }
1834 * } );
1835 * ...
1836 * };
1837 *
1838 * @property {jQuery}
1839 */
1840 this.$overlay = $( '<div>' );
1841 this.$content = $( '<div>' );
1842
1843 this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
1844 this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
1845 this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
1846
1847 // Initialization
1848 this.$overlay.addClass( 'oo-ui-window-overlay' );
1849 this.$content
1850 .addClass( 'oo-ui-window-content' )
1851 .attr( 'tabindex', 0 );
1852 this.$frame
1853 .addClass( 'oo-ui-window-frame' )
1854 .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
1855
1856 this.$element
1857 .addClass( 'oo-ui-window' )
1858 .append( this.$frame, this.$overlay );
1859
1860 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1861 // that reference properties not initialized at that time of parent class construction
1862 // TODO: Find a better way to handle post-constructor setup
1863 this.visible = false;
1864 this.$element.addClass( 'oo-ui-element-hidden' );
1865 };
1866
1867 /* Setup */
1868
1869 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1870 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1871
1872 /* Static Properties */
1873
1874 /**
1875 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1876 *
1877 * The static size is used if no #size is configured during construction.
1878 *
1879 * @static
1880 * @inheritable
1881 * @property {string}
1882 */
1883 OO.ui.Window.static.size = 'medium';
1884
1885 /* Methods */
1886
1887 /**
1888 * Handle mouse down events.
1889 *
1890 * @private
1891 * @param {jQuery.Event} e Mouse down event
1892 * @return {OO.ui.Window} The window, for chaining
1893 */
1894 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1895 // Prevent clicking on the click-block from stealing focus
1896 if ( e.target === this.$element[ 0 ] ) {
1897 return false;
1898 }
1899 };
1900
1901 /**
1902 * Check if the window has been initialized.
1903 *
1904 * Initialization occurs when a window is added to a manager.
1905 *
1906 * @return {boolean} Window has been initialized
1907 */
1908 OO.ui.Window.prototype.isInitialized = function () {
1909 return !!this.manager;
1910 };
1911
1912 /**
1913 * Check if the window is visible.
1914 *
1915 * @return {boolean} Window is visible
1916 */
1917 OO.ui.Window.prototype.isVisible = function () {
1918 return this.visible;
1919 };
1920
1921 /**
1922 * Check if the window is opening.
1923 *
1924 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1925 * method.
1926 *
1927 * @return {boolean} Window is opening
1928 */
1929 OO.ui.Window.prototype.isOpening = function () {
1930 return this.manager.isOpening( this );
1931 };
1932
1933 /**
1934 * Check if the window is closing.
1935 *
1936 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1937 *
1938 * @return {boolean} Window is closing
1939 */
1940 OO.ui.Window.prototype.isClosing = function () {
1941 return this.manager.isClosing( this );
1942 };
1943
1944 /**
1945 * Check if the window is opened.
1946 *
1947 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1948 *
1949 * @return {boolean} Window is opened
1950 */
1951 OO.ui.Window.prototype.isOpened = function () {
1952 return this.manager.isOpened( this );
1953 };
1954
1955 /**
1956 * Get the window manager.
1957 *
1958 * All windows must be attached to a window manager, which is used to open
1959 * and close the window and control its presentation.
1960 *
1961 * @return {OO.ui.WindowManager} Manager of window
1962 */
1963 OO.ui.Window.prototype.getManager = function () {
1964 return this.manager;
1965 };
1966
1967 /**
1968 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1969 *
1970 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1971 */
1972 OO.ui.Window.prototype.getSize = function () {
1973 var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
1974 sizes = this.manager.constructor.static.sizes,
1975 size = this.size;
1976
1977 if ( !sizes[ size ] ) {
1978 size = this.manager.constructor.static.defaultSize;
1979 }
1980 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
1981 size = 'full';
1982 }
1983
1984 return size;
1985 };
1986
1987 /**
1988 * Get the size properties associated with the current window size
1989 *
1990 * @return {Object} Size properties
1991 */
1992 OO.ui.Window.prototype.getSizeProperties = function () {
1993 return this.manager.constructor.static.sizes[ this.getSize() ];
1994 };
1995
1996 /**
1997 * Disable transitions on window's frame for the duration of the callback function, then enable them
1998 * back.
1999 *
2000 * @private
2001 * @param {Function} callback Function to call while transitions are disabled
2002 */
2003 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
2004 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2005 // Disable transitions first, otherwise we'll get values from when the window was animating.
2006 // We need to build the transition CSS properties using these specific properties since
2007 // Firefox doesn't return anything useful when asked just for 'transition'.
2008 var oldTransition = this.$frame.css( 'transition-property' ) + ' ' +
2009 this.$frame.css( 'transition-duration' ) + ' ' +
2010 this.$frame.css( 'transition-timing-function' ) + ' ' +
2011 this.$frame.css( 'transition-delay' );
2012
2013 this.$frame.css( 'transition', 'none' );
2014 callback();
2015
2016 // Force reflow to make sure the style changes done inside callback
2017 // really are not transitioned
2018 this.$frame.height();
2019 this.$frame.css( 'transition', oldTransition );
2020 };
2021
2022 /**
2023 * Get the height of the full window contents (i.e., the window head, body and foot together).
2024 *
2025 * What constitutes the head, body, and foot varies depending on the window type.
2026 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2027 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2028 * and special actions in the head, and dialog content in the body.
2029 *
2030 * To get just the height of the dialog body, use the #getBodyHeight method.
2031 *
2032 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2033 */
2034 OO.ui.Window.prototype.getContentHeight = function () {
2035 var bodyHeight,
2036 win = this,
2037 bodyStyleObj = this.$body[ 0 ].style,
2038 frameStyleObj = this.$frame[ 0 ].style;
2039
2040 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2041 // Disable transitions first, otherwise we'll get values from when the window was animating.
2042 this.withoutSizeTransitions( function () {
2043 var oldHeight = frameStyleObj.height,
2044 oldPosition = bodyStyleObj.position;
2045 frameStyleObj.height = '1px';
2046 // Force body to resize to new width
2047 bodyStyleObj.position = 'relative';
2048 bodyHeight = win.getBodyHeight();
2049 frameStyleObj.height = oldHeight;
2050 bodyStyleObj.position = oldPosition;
2051 } );
2052
2053 return (
2054 // Add buffer for border
2055 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
2056 // Use combined heights of children
2057 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
2058 );
2059 };
2060
2061 /**
2062 * Get the height of the window body.
2063 *
2064 * To get the height of the full window contents (the window body, head, and foot together),
2065 * use #getContentHeight.
2066 *
2067 * When this function is called, the window will temporarily have been resized
2068 * to height=1px, so .scrollHeight measurements can be taken accurately.
2069 *
2070 * @return {number} Height of the window body in pixels
2071 */
2072 OO.ui.Window.prototype.getBodyHeight = function () {
2073 return this.$body[ 0 ].scrollHeight;
2074 };
2075
2076 /**
2077 * Get the directionality of the frame (right-to-left or left-to-right).
2078 *
2079 * @return {string} Directionality: `'ltr'` or `'rtl'`
2080 */
2081 OO.ui.Window.prototype.getDir = function () {
2082 return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2083 };
2084
2085 /**
2086 * Get the 'setup' process.
2087 *
2088 * The setup process is used to set up a window for use in a particular context, based on the `data`
2089 * argument. This method is called during the opening phase of the window’s lifecycle (before the
2090 * opening animation). You can add elements to the window in this process or set their default
2091 * values.
2092 *
2093 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2094 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2095 * of OO.ui.Process.
2096 *
2097 * To add window content that persists between openings, you may wish to use the #initialize method
2098 * instead.
2099 *
2100 * @param {Object} [data] Window opening data
2101 * @return {OO.ui.Process} Setup process
2102 */
2103 OO.ui.Window.prototype.getSetupProcess = function () {
2104 return new OO.ui.Process();
2105 };
2106
2107 /**
2108 * Get the ‘ready’ process.
2109 *
2110 * The ready process is used to ready a window for use in a particular context, based on the `data`
2111 * argument. This method is called during the opening phase of the window’s lifecycle, after the
2112 * window has been {@link #getSetupProcess setup} (after the opening animation). You can focus
2113 * elements in the window in this process, or open their dropdowns.
2114 *
2115 * Override this method to add additional steps to the ‘ready’ process the parent method
2116 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2117 * methods of OO.ui.Process.
2118 *
2119 * @param {Object} [data] Window opening data
2120 * @return {OO.ui.Process} Ready process
2121 */
2122 OO.ui.Window.prototype.getReadyProcess = function () {
2123 return new OO.ui.Process();
2124 };
2125
2126 /**
2127 * Get the 'hold' process.
2128 *
2129 * The hold process is used to keep a window from being used in a particular context, based on the
2130 * `data` argument. This method is called during the closing phase of the window’s lifecycle (before
2131 * the closing animation). You can close dropdowns of elements in the window in this process, if
2132 * they do not get closed automatically.
2133 *
2134 * Override this method to add additional steps to the 'hold' process the parent method provides
2135 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2136 * of OO.ui.Process.
2137 *
2138 * @param {Object} [data] Window closing data
2139 * @return {OO.ui.Process} Hold process
2140 */
2141 OO.ui.Window.prototype.getHoldProcess = function () {
2142 return new OO.ui.Process();
2143 };
2144
2145 /**
2146 * Get the ‘teardown’ process.
2147 *
2148 * The teardown process is used to teardown a window after use. During teardown, user interactions
2149 * within the window are conveyed and the window is closed, based on the `data` argument. This
2150 * method is called during the closing phase of the window’s lifecycle (after the closing
2151 * animation). You can remove elements in the window in this process or clear their values.
2152 *
2153 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2154 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2155 * of OO.ui.Process.
2156 *
2157 * @param {Object} [data] Window closing data
2158 * @return {OO.ui.Process} Teardown process
2159 */
2160 OO.ui.Window.prototype.getTeardownProcess = function () {
2161 return new OO.ui.Process();
2162 };
2163
2164 /**
2165 * Set the window manager.
2166 *
2167 * This will cause the window to initialize. Calling it more than once will cause an error.
2168 *
2169 * @param {OO.ui.WindowManager} manager Manager for this window
2170 * @throws {Error} An error is thrown if the method is called more than once
2171 * @chainable
2172 * @return {OO.ui.Window} The window, for chaining
2173 */
2174 OO.ui.Window.prototype.setManager = function ( manager ) {
2175 if ( this.manager ) {
2176 throw new Error( 'Cannot set window manager, window already has a manager' );
2177 }
2178
2179 this.manager = manager;
2180 this.initialize();
2181
2182 return this;
2183 };
2184
2185 /**
2186 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2187 *
2188 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2189 * `full`
2190 * @chainable
2191 * @return {OO.ui.Window} The window, for chaining
2192 */
2193 OO.ui.Window.prototype.setSize = function ( size ) {
2194 this.size = size;
2195 this.updateSize();
2196 return this;
2197 };
2198
2199 /**
2200 * Update the window size.
2201 *
2202 * @throws {Error} An error is thrown if the window is not attached to a window manager
2203 * @chainable
2204 * @return {OO.ui.Window} The window, for chaining
2205 */
2206 OO.ui.Window.prototype.updateSize = function () {
2207 if ( !this.manager ) {
2208 throw new Error( 'Cannot update window size, must be attached to a manager' );
2209 }
2210
2211 this.manager.updateWindowSize( this );
2212
2213 return this;
2214 };
2215
2216 /**
2217 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2218 * when the window is opening. In general, setDimensions should not be called directly.
2219 *
2220 * To set the size of the window, use the #setSize method.
2221 *
2222 * @param {Object} dim CSS dimension properties
2223 * @param {string|number} [dim.width] Width
2224 * @param {string|number} [dim.minWidth] Minimum width
2225 * @param {string|number} [dim.maxWidth] Maximum width
2226 * @param {string|number} [dim.height] Height, omit to set based on height of contents
2227 * @param {string|number} [dim.minHeight] Minimum height
2228 * @param {string|number} [dim.maxHeight] Maximum height
2229 * @chainable
2230 * @return {OO.ui.Window} The window, for chaining
2231 */
2232 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2233 var height,
2234 win = this,
2235 styleObj = this.$frame[ 0 ].style;
2236
2237 // Calculate the height we need to set using the correct width
2238 if ( dim.height === undefined ) {
2239 this.withoutSizeTransitions( function () {
2240 var oldWidth = styleObj.width;
2241 win.$frame.css( 'width', dim.width || '' );
2242 height = win.getContentHeight();
2243 styleObj.width = oldWidth;
2244 } );
2245 } else {
2246 height = dim.height;
2247 }
2248
2249 this.$frame.css( {
2250 width: dim.width || '',
2251 minWidth: dim.minWidth || '',
2252 maxWidth: dim.maxWidth || '',
2253 height: height || '',
2254 minHeight: dim.minHeight || '',
2255 maxHeight: dim.maxHeight || ''
2256 } );
2257
2258 return this;
2259 };
2260
2261 /**
2262 * Initialize window contents.
2263 *
2264 * Before the window is opened for the first time, #initialize is called so that content that
2265 * persists between openings can be added to the window.
2266 *
2267 * To set up a window with new content each time the window opens, use #getSetupProcess.
2268 *
2269 * @throws {Error} An error is thrown if the window is not attached to a window manager
2270 * @chainable
2271 * @return {OO.ui.Window} The window, for chaining
2272 */
2273 OO.ui.Window.prototype.initialize = function () {
2274 if ( !this.manager ) {
2275 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2276 }
2277
2278 // Properties
2279 this.$head = $( '<div>' );
2280 this.$body = $( '<div>' );
2281 this.$foot = $( '<div>' );
2282 this.$document = $( this.getElementDocument() );
2283
2284 // Events
2285 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2286
2287 // Initialization
2288 this.$head.addClass( 'oo-ui-window-head' );
2289 this.$body.addClass( 'oo-ui-window-body' );
2290 this.$foot.addClass( 'oo-ui-window-foot' );
2291 this.$content.append( this.$head, this.$body, this.$foot );
2292
2293 return this;
2294 };
2295
2296 /**
2297 * Called when someone tries to focus the hidden element at the end of the dialog.
2298 * Sends focus back to the start of the dialog.
2299 *
2300 * @param {jQuery.Event} event Focus event
2301 */
2302 OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
2303 var backwards = this.$focusTrapBefore.is( event.target ),
2304 element = OO.ui.findFocusable( this.$content, backwards );
2305 if ( element ) {
2306 // There's a focusable element inside the content, at the front or
2307 // back depending on which focus trap we hit; select it.
2308 element.focus();
2309 } else {
2310 // There's nothing focusable inside the content. As a fallback,
2311 // this.$content is focusable, and focusing it will keep our focus
2312 // properly trapped. It's not a *meaningful* focus, since it's just
2313 // the content-div for the Window, but it's better than letting focus
2314 // escape into the page.
2315 this.$content.trigger( 'focus' );
2316 }
2317 };
2318
2319 /**
2320 * Open the window.
2321 *
2322 * This method is a wrapper around a call to the window
2323 * manager’s {@link OO.ui.WindowManager#openWindow openWindow} method.
2324 *
2325 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2326 *
2327 * @param {Object} [data] Window opening data
2328 * @return {OO.ui.WindowInstance} See OO.ui.WindowManager#openWindow
2329 * @throws {Error} An error is thrown if the window is not attached to a window manager
2330 */
2331 OO.ui.Window.prototype.open = function ( data ) {
2332 if ( !this.manager ) {
2333 throw new Error( 'Cannot open window, must be attached to a manager' );
2334 }
2335
2336 return this.manager.openWindow( this, data );
2337 };
2338
2339 /**
2340 * Close the window.
2341 *
2342 * This method is a wrapper around a call to the window
2343 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method.
2344 *
2345 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2346 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2347 * the window closes.
2348 *
2349 * @param {Object} [data] Window closing data
2350 * @return {OO.ui.WindowInstance} See OO.ui.WindowManager#closeWindow
2351 * @throws {Error} An error is thrown if the window is not attached to a window manager
2352 */
2353 OO.ui.Window.prototype.close = function ( data ) {
2354 if ( !this.manager ) {
2355 throw new Error( 'Cannot close window, must be attached to a manager' );
2356 }
2357
2358 return this.manager.closeWindow( this, data );
2359 };
2360
2361 /**
2362 * Setup window.
2363 *
2364 * This is called by OO.ui.WindowManager during window opening (before the animation), and should
2365 * not be called directly by other systems.
2366 *
2367 * @param {Object} [data] Window opening data
2368 * @return {jQuery.Promise} Promise resolved when window is setup
2369 */
2370 OO.ui.Window.prototype.setup = function ( data ) {
2371 var win = this;
2372
2373 this.toggle( true );
2374
2375 this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
2376 this.$focusTraps.on( 'focus', this.focusTrapHandler );
2377
2378 return this.getSetupProcess( data ).execute().then( function () {
2379 win.updateSize();
2380 // Force redraw by asking the browser to measure the elements' widths
2381 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2382 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2383 } );
2384 };
2385
2386 /**
2387 * Ready window.
2388 *
2389 * This is called by OO.ui.WindowManager during window opening (after the animation), and should not
2390 * be called directly by other systems.
2391 *
2392 * @param {Object} [data] Window opening data
2393 * @return {jQuery.Promise} Promise resolved when window is ready
2394 */
2395 OO.ui.Window.prototype.ready = function ( data ) {
2396 var win = this;
2397
2398 this.$content.trigger( 'focus' );
2399 return this.getReadyProcess( data ).execute().then( function () {
2400 // Force redraw by asking the browser to measure the elements' widths
2401 win.$element.addClass( 'oo-ui-window-ready' ).width();
2402 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2403 } );
2404 };
2405
2406 /**
2407 * Hold window.
2408 *
2409 * This is called by OO.ui.WindowManager during window closing (before the animation), and should
2410 * not be called directly by other systems.
2411 *
2412 * @param {Object} [data] Window closing data
2413 * @return {jQuery.Promise} Promise resolved when window is held
2414 */
2415 OO.ui.Window.prototype.hold = function ( data ) {
2416 var win = this;
2417
2418 return this.getHoldProcess( data ).execute().then( function () {
2419 // Get the focused element within the window's content
2420 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2421
2422 // Blur the focused element
2423 if ( $focus.length ) {
2424 $focus[ 0 ].blur();
2425 }
2426
2427 // Force redraw by asking the browser to measure the elements' widths
2428 win.$element.removeClass( 'oo-ui-window-ready oo-ui-window-setup' ).width();
2429 win.$content.removeClass( 'oo-ui-window-content-ready oo-ui-window-content-setup' ).width();
2430 } );
2431 };
2432
2433 /**
2434 * Teardown window.
2435 *
2436 * This is called by OO.ui.WindowManager during window closing (after the animation), and should not be called directly
2437 * by other systems.
2438 *
2439 * @param {Object} [data] Window closing data
2440 * @return {jQuery.Promise} Promise resolved when window is torn down
2441 */
2442 OO.ui.Window.prototype.teardown = function ( data ) {
2443 var win = this;
2444
2445 return this.getTeardownProcess( data ).execute().then( function () {
2446 // Force redraw by asking the browser to measure the elements' widths
2447 win.$element.removeClass( 'oo-ui-window-active' ).width();
2448
2449 win.$focusTraps.off( 'focus', win.focusTrapHandler );
2450 win.toggle( false );
2451 } );
2452 };
2453
2454 /**
2455 * The Dialog class serves as the base class for the other types of dialogs.
2456 * Unless extended to include controls, the rendered dialog box is a simple window
2457 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2458 * which opens, closes, and controls the presentation of the window. See the
2459 * [OOUI documentation on MediaWiki] [1] for more information.
2460 *
2461 * @example
2462 * // A simple dialog window.
2463 * function MyDialog( config ) {
2464 * MyDialog.parent.call( this, config );
2465 * }
2466 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2467 * MyDialog.static.name = 'myDialog';
2468 * MyDialog.prototype.initialize = function () {
2469 * MyDialog.parent.prototype.initialize.call( this );
2470 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2471 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2472 * this.$body.append( this.content.$element );
2473 * };
2474 * MyDialog.prototype.getBodyHeight = function () {
2475 * return this.content.$element.outerHeight( true );
2476 * };
2477 * var myDialog = new MyDialog( {
2478 * size: 'medium'
2479 * } );
2480 * // Create and append a window manager, which opens and closes the window.
2481 * var windowManager = new OO.ui.WindowManager();
2482 * $( document.body ).append( windowManager.$element );
2483 * windowManager.addWindows( [ myDialog ] );
2484 * // Open the window!
2485 * windowManager.openWindow( myDialog );
2486 *
2487 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Dialogs
2488 *
2489 * @abstract
2490 * @class
2491 * @extends OO.ui.Window
2492 * @mixins OO.ui.mixin.PendingElement
2493 *
2494 * @constructor
2495 * @param {Object} [config] Configuration options
2496 */
2497 OO.ui.Dialog = function OoUiDialog( config ) {
2498 // Parent constructor
2499 OO.ui.Dialog.parent.call( this, config );
2500
2501 // Mixin constructors
2502 OO.ui.mixin.PendingElement.call( this );
2503
2504 // Properties
2505 this.actions = new OO.ui.ActionSet();
2506 this.attachedActions = [];
2507 this.currentAction = null;
2508 this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
2509
2510 // Events
2511 this.actions.connect( this, {
2512 click: 'onActionClick',
2513 change: 'onActionsChange'
2514 } );
2515
2516 // Initialization
2517 this.$element
2518 .addClass( 'oo-ui-dialog' )
2519 .attr( 'role', 'dialog' );
2520 };
2521
2522 /* Setup */
2523
2524 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2525 OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
2526
2527 /* Static Properties */
2528
2529 /**
2530 * Symbolic name of dialog.
2531 *
2532 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2533 * Please see the [OOUI documentation on MediaWiki] [3] for more information.
2534 *
2535 * [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
2536 *
2537 * @abstract
2538 * @static
2539 * @inheritable
2540 * @property {string}
2541 */
2542 OO.ui.Dialog.static.name = '';
2543
2544 /**
2545 * The dialog title.
2546 *
2547 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2548 * that will produce a Label node or string. The title can also be specified with data passed to the
2549 * constructor (see #getSetupProcess). In this case, the static value will be overridden.
2550 *
2551 * @abstract
2552 * @static
2553 * @inheritable
2554 * @property {jQuery|string|Function}
2555 */
2556 OO.ui.Dialog.static.title = '';
2557
2558 /**
2559 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2560 *
2561 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2562 * value will be overridden.
2563 *
2564 * [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
2565 *
2566 * @static
2567 * @inheritable
2568 * @property {Object[]}
2569 */
2570 OO.ui.Dialog.static.actions = [];
2571
2572 /**
2573 * Close the dialog when the 'Esc' key is pressed.
2574 *
2575 * @static
2576 * @abstract
2577 * @inheritable
2578 * @property {boolean}
2579 */
2580 OO.ui.Dialog.static.escapable = true;
2581
2582 /* Methods */
2583
2584 /**
2585 * Handle frame document key down events.
2586 *
2587 * @private
2588 * @param {jQuery.Event} e Key down event
2589 */
2590 OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
2591 var actions;
2592 if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
2593 this.executeAction( '' );
2594 e.preventDefault();
2595 e.stopPropagation();
2596 } else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) {
2597 actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
2598 if ( actions.length > 0 ) {
2599 this.executeAction( actions[ 0 ].getAction() );
2600 e.preventDefault();
2601 e.stopPropagation();
2602 }
2603 }
2604 };
2605
2606 /**
2607 * Handle action click events.
2608 *
2609 * @private
2610 * @param {OO.ui.ActionWidget} action Action that was clicked
2611 */
2612 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2613 if ( !this.isPending() ) {
2614 this.executeAction( action.getAction() );
2615 }
2616 };
2617
2618 /**
2619 * Handle actions change event.
2620 *
2621 * @private
2622 */
2623 OO.ui.Dialog.prototype.onActionsChange = function () {
2624 this.detachActions();
2625 if ( !this.isClosing() ) {
2626 this.attachActions();
2627 if ( !this.isOpening() ) {
2628 // If the dialog is currently opening, this will be called automatically soon.
2629 this.updateSize();
2630 }
2631 }
2632 };
2633
2634 /**
2635 * Get the set of actions used by the dialog.
2636 *
2637 * @return {OO.ui.ActionSet}
2638 */
2639 OO.ui.Dialog.prototype.getActions = function () {
2640 return this.actions;
2641 };
2642
2643 /**
2644 * Get a process for taking action.
2645 *
2646 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2647 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2648 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2649 *
2650 * @param {string} [action] Symbolic name of action
2651 * @return {OO.ui.Process} Action process
2652 */
2653 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2654 return new OO.ui.Process()
2655 .next( function () {
2656 if ( !action ) {
2657 // An empty action always closes the dialog without data, which should always be
2658 // safe and make no changes
2659 this.close();
2660 }
2661 }, this );
2662 };
2663
2664 /**
2665 * @inheritdoc
2666 *
2667 * @param {Object} [data] Dialog opening data
2668 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2669 * the {@link #static-title static title}
2670 * @param {Object[]} [data.actions] List of configuration options for each
2671 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2672 */
2673 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2674 data = data || {};
2675
2676 // Parent method
2677 return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
2678 .next( function () {
2679 var config = this.constructor.static,
2680 actions = data.actions !== undefined ? data.actions : config.actions,
2681 title = data.title !== undefined ? data.title : config.title;
2682
2683 this.title.setLabel( title ).setTitle( title );
2684 this.actions.add( this.getActionWidgets( actions ) );
2685
2686 this.$element.on( 'keydown', this.onDialogKeyDownHandler );
2687 }, this );
2688 };
2689
2690 /**
2691 * @inheritdoc
2692 */
2693 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2694 // Parent method
2695 return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
2696 .first( function () {
2697 this.$element.off( 'keydown', this.onDialogKeyDownHandler );
2698
2699 this.actions.clear();
2700 this.currentAction = null;
2701 }, this );
2702 };
2703
2704 /**
2705 * @inheritdoc
2706 */
2707 OO.ui.Dialog.prototype.initialize = function () {
2708 // Parent method
2709 OO.ui.Dialog.parent.prototype.initialize.call( this );
2710
2711 // Properties
2712 this.title = new OO.ui.LabelWidget();
2713
2714 // Initialization
2715 this.$content.addClass( 'oo-ui-dialog-content' );
2716 this.$element.attr( 'aria-labelledby', this.title.getElementId() );
2717 this.setPendingElement( this.$head );
2718 };
2719
2720 /**
2721 * Get action widgets from a list of configs
2722 *
2723 * @param {Object[]} actions Action widget configs
2724 * @return {OO.ui.ActionWidget[]} Action widgets
2725 */
2726 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2727 var i, len, widgets = [];
2728 for ( i = 0, len = actions.length; i < len; i++ ) {
2729 widgets.push( this.getActionWidget( actions[ i ] ) );
2730 }
2731 return widgets;
2732 };
2733
2734 /**
2735 * Get action widget from config
2736 *
2737 * Override this method to change the action widget class used.
2738 *
2739 * @param {Object} config Action widget config
2740 * @return {OO.ui.ActionWidget} Action widget
2741 */
2742 OO.ui.Dialog.prototype.getActionWidget = function ( config ) {
2743 return new OO.ui.ActionWidget( this.getActionWidgetConfig( config ) );
2744 };
2745
2746 /**
2747 * Get action widget config
2748 *
2749 * Override this method to modify the action widget config
2750 *
2751 * @param {Object} config Initial action widget config
2752 * @return {Object} Action widget config
2753 */
2754 OO.ui.Dialog.prototype.getActionWidgetConfig = function ( config ) {
2755 return config;
2756 };
2757
2758 /**
2759 * Attach action actions.
2760 *
2761 * @protected
2762 */
2763 OO.ui.Dialog.prototype.attachActions = function () {
2764 // Remember the list of potentially attached actions
2765 this.attachedActions = this.actions.get();
2766 };
2767
2768 /**
2769 * Detach action actions.
2770 *
2771 * @protected
2772 * @chainable
2773 * @return {OO.ui.Dialog} The dialog, for chaining
2774 */
2775 OO.ui.Dialog.prototype.detachActions = function () {
2776 var i, len;
2777
2778 // Detach all actions that may have been previously attached
2779 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2780 this.attachedActions[ i ].$element.detach();
2781 }
2782 this.attachedActions = [];
2783
2784 return this;
2785 };
2786
2787 /**
2788 * Execute an action.
2789 *
2790 * @param {string} action Symbolic name of action to execute
2791 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2792 */
2793 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2794 this.pushPending();
2795 this.currentAction = action;
2796 return this.getActionProcess( action ).execute()
2797 .always( this.popPending.bind( this ) );
2798 };
2799
2800 /**
2801 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
2802 * consists of a header that contains the dialog title, a body with the message, and a footer that
2803 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
2804 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
2805 *
2806 * There are two basic types of message dialogs, confirmation and alert:
2807 *
2808 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
2809 * more details about the consequences.
2810 * - **alert**: the dialog title describes which event occurred and the message provides more information
2811 * about why the event occurred.
2812 *
2813 * The MessageDialog class specifies two actions: ‘accept’, the primary
2814 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
2815 * passing along the selected action.
2816 *
2817 * For more information and examples, please see the [OOUI documentation on MediaWiki][1].
2818 *
2819 * @example
2820 * // Example: Creating and opening a message dialog window.
2821 * var messageDialog = new OO.ui.MessageDialog();
2822 *
2823 * // Create and append a window manager.
2824 * var windowManager = new OO.ui.WindowManager();
2825 * $( document.body ).append( windowManager.$element );
2826 * windowManager.addWindows( [ messageDialog ] );
2827 * // Open the window.
2828 * windowManager.openWindow( messageDialog, {
2829 * title: 'Basic message dialog',
2830 * message: 'This is the message'
2831 * } );
2832 *
2833 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Message_Dialogs
2834 *
2835 * @class
2836 * @extends OO.ui.Dialog
2837 *
2838 * @constructor
2839 * @param {Object} [config] Configuration options
2840 */
2841 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
2842 // Parent constructor
2843 OO.ui.MessageDialog.parent.call( this, config );
2844
2845 // Properties
2846 this.verticalActionLayout = null;
2847
2848 // Initialization
2849 this.$element.addClass( 'oo-ui-messageDialog' );
2850 };
2851
2852 /* Setup */
2853
2854 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
2855
2856 /* Static Properties */
2857
2858 /**
2859 * @static
2860 * @inheritdoc
2861 */
2862 OO.ui.MessageDialog.static.name = 'message';
2863
2864 /**
2865 * @static
2866 * @inheritdoc
2867 */
2868 OO.ui.MessageDialog.static.size = 'small';
2869
2870 /**
2871 * Dialog title.
2872 *
2873 * The title of a confirmation dialog describes what a progressive action will do. The
2874 * title of an alert dialog describes which event occurred.
2875 *
2876 * @static
2877 * @inheritable
2878 * @property {jQuery|string|Function|null}
2879 */
2880 OO.ui.MessageDialog.static.title = null;
2881
2882 /**
2883 * The message displayed in the dialog body.
2884 *
2885 * A confirmation message describes the consequences of a progressive action. An alert
2886 * message describes why an event occurred.
2887 *
2888 * @static
2889 * @inheritable
2890 * @property {jQuery|string|Function|null}
2891 */
2892 OO.ui.MessageDialog.static.message = null;
2893
2894 /**
2895 * @static
2896 * @inheritdoc
2897 */
2898 OO.ui.MessageDialog.static.actions = [
2899 // Note that OO.ui.alert() and OO.ui.confirm() rely on these.
2900 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
2901 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
2902 ];
2903
2904 /* Methods */
2905
2906 /**
2907 * Toggle action layout between vertical and horizontal.
2908 *
2909 * @private
2910 * @param {boolean} [value] Layout actions vertically, omit to toggle
2911 * @chainable
2912 * @return {OO.ui.MessageDialog} The dialog, for chaining
2913 */
2914 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
2915 value = value === undefined ? !this.verticalActionLayout : !!value;
2916
2917 if ( value !== this.verticalActionLayout ) {
2918 this.verticalActionLayout = value;
2919 this.$actions
2920 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
2921 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
2922 }
2923
2924 return this;
2925 };
2926
2927 /**
2928 * @inheritdoc
2929 */
2930 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
2931 if ( action ) {
2932 return new OO.ui.Process( function () {
2933 this.close( { action: action } );
2934 }, this );
2935 }
2936 return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
2937 };
2938
2939 /**
2940 * @inheritdoc
2941 *
2942 * @param {Object} [data] Dialog opening data
2943 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
2944 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
2945 * @param {string} [data.size] Symbolic name of the dialog size, see OO.ui.Window
2946 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
2947 * action item
2948 */
2949 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
2950 data = data || {};
2951
2952 // Parent method
2953 return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
2954 .next( function () {
2955 this.title.setLabel(
2956 data.title !== undefined ? data.title : this.constructor.static.title
2957 );
2958 this.message.setLabel(
2959 data.message !== undefined ? data.message : this.constructor.static.message
2960 );
2961 this.size = data.size !== undefined ? data.size : this.constructor.static.size;
2962 }, this );
2963 };
2964
2965 /**
2966 * @inheritdoc
2967 */
2968 OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
2969 data = data || {};
2970
2971 // Parent method
2972 return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
2973 .next( function () {
2974 // Focus the primary action button
2975 var actions = this.actions.get();
2976 actions = actions.filter( function ( action ) {
2977 return action.getFlags().indexOf( 'primary' ) > -1;
2978 } );
2979 if ( actions.length > 0 ) {
2980 actions[ 0 ].focus();
2981 }
2982 }, this );
2983 };
2984
2985 /**
2986 * @inheritdoc
2987 */
2988 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
2989 var bodyHeight, oldOverflow,
2990 $scrollable = this.container.$element;
2991
2992 oldOverflow = $scrollable[ 0 ].style.overflow;
2993 $scrollable[ 0 ].style.overflow = 'hidden';
2994
2995 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
2996
2997 bodyHeight = this.text.$element.outerHeight( true );
2998 $scrollable[ 0 ].style.overflow = oldOverflow;
2999
3000 return bodyHeight;
3001 };
3002
3003 /**
3004 * @inheritdoc
3005 */
3006 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
3007 var
3008 dialog = this,
3009 $scrollable = this.container.$element;
3010 OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
3011
3012 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
3013 // Need to do it after transition completes (250ms), add 50ms just in case.
3014 setTimeout( function () {
3015 var oldOverflow = $scrollable[ 0 ].style.overflow,
3016 activeElement = document.activeElement;
3017
3018 $scrollable[ 0 ].style.overflow = 'hidden';
3019
3020 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
3021
3022 // Check reconsiderScrollbars didn't destroy our focus, as we
3023 // are doing this after the ready process.
3024 if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) {
3025 activeElement.focus();
3026 }
3027
3028 $scrollable[ 0 ].style.overflow = oldOverflow;
3029 }, 300 );
3030
3031 dialog.fitActions();
3032 // Wait for CSS transition to finish and do it again :(
3033 setTimeout( function () {
3034 dialog.fitActions();
3035 }, 300 );
3036
3037 return this;
3038 };
3039
3040 /**
3041 * @inheritdoc
3042 */
3043 OO.ui.MessageDialog.prototype.initialize = function () {
3044 // Parent method
3045 OO.ui.MessageDialog.parent.prototype.initialize.call( this );
3046
3047 // Properties
3048 this.$actions = $( '<div>' );
3049 this.container = new OO.ui.PanelLayout( {
3050 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
3051 } );
3052 this.text = new OO.ui.PanelLayout( {
3053 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
3054 } );
3055 this.message = new OO.ui.LabelWidget( {
3056 classes: [ 'oo-ui-messageDialog-message' ]
3057 } );
3058
3059 // Initialization
3060 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
3061 this.$content.addClass( 'oo-ui-messageDialog-content' );
3062 this.container.$element.append( this.text.$element );
3063 this.text.$element.append( this.title.$element, this.message.$element );
3064 this.$body.append( this.container.$element );
3065 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
3066 this.$foot.append( this.$actions );
3067 };
3068
3069 /**
3070 * @inheritdoc
3071 */
3072 OO.ui.MessageDialog.prototype.getActionWidgetConfig = function ( config ) {
3073 // Force unframed
3074 return $.extend( {}, config, { framed: false } );
3075 };
3076
3077 /**
3078 * @inheritdoc
3079 */
3080 OO.ui.MessageDialog.prototype.attachActions = function () {
3081 var i, len, special, others;
3082
3083 // Parent method
3084 OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
3085
3086 special = this.actions.getSpecial();
3087 others = this.actions.getOthers();
3088
3089 if ( special.safe ) {
3090 this.$actions.append( special.safe.$element );
3091 special.safe.toggleFramed( true );
3092 }
3093 for ( i = 0, len = others.length; i < len; i++ ) {
3094 this.$actions.append( others[ i ].$element );
3095 others[ i ].toggleFramed( true );
3096 }
3097 if ( special.primary ) {
3098 this.$actions.append( special.primary.$element );
3099 special.primary.toggleFramed( true );
3100 }
3101 };
3102
3103 /**
3104 * Fit action actions into columns or rows.
3105 *
3106 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
3107 *
3108 * @private
3109 */
3110 OO.ui.MessageDialog.prototype.fitActions = function () {
3111 var i, len, action,
3112 previous = this.verticalActionLayout,
3113 actions = this.actions.get();
3114
3115 // Detect clipping
3116 this.toggleVerticalActionLayout( false );
3117 for ( i = 0, len = actions.length; i < len; i++ ) {
3118 action = actions[ i ];
3119 if ( action.$element[ 0 ].scrollWidth > action.$element[ 0 ].clientWidth ) {
3120 this.toggleVerticalActionLayout( true );
3121 break;
3122 }
3123 }
3124
3125 // Move the body out of the way of the foot
3126 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
3127
3128 if ( this.verticalActionLayout !== previous ) {
3129 // We changed the layout, window height might need to be updated.
3130 this.updateSize();
3131 }
3132 };
3133
3134 /**
3135 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
3136 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
3137 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
3138 * relevant. The ProcessDialog class is always extended and customized with the actions and content
3139 * required for each process.
3140 *
3141 * The process dialog box consists of a header that visually represents the ‘working’ state of long
3142 * processes with an animation. The header contains the dialog title as well as
3143 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
3144 * a ‘primary’ action on the right (e.g., ‘Done’).
3145 *
3146 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
3147 * Please see the [OOUI documentation on MediaWiki][1] for more information and examples.
3148 *
3149 * @example
3150 * // Example: Creating and opening a process dialog window.
3151 * function MyProcessDialog( config ) {
3152 * MyProcessDialog.parent.call( this, config );
3153 * }
3154 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
3155 *
3156 * MyProcessDialog.static.name = 'myProcessDialog';
3157 * MyProcessDialog.static.title = 'Process dialog';
3158 * MyProcessDialog.static.actions = [
3159 * { action: 'save', label: 'Done', flags: 'primary' },
3160 * { label: 'Cancel', flags: 'safe' }
3161 * ];
3162 *
3163 * MyProcessDialog.prototype.initialize = function () {
3164 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
3165 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
3166 * 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>' );
3167 * this.$body.append( this.content.$element );
3168 * };
3169 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
3170 * var dialog = this;
3171 * if ( action ) {
3172 * return new OO.ui.Process( function () {
3173 * dialog.close( { action: action } );
3174 * } );
3175 * }
3176 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
3177 * };
3178 *
3179 * var windowManager = new OO.ui.WindowManager();
3180 * $( document.body ).append( windowManager.$element );
3181 *
3182 * var dialog = new MyProcessDialog();
3183 * windowManager.addWindows( [ dialog ] );
3184 * windowManager.openWindow( dialog );
3185 *
3186 * [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs
3187 *
3188 * @abstract
3189 * @class
3190 * @extends OO.ui.Dialog
3191 *
3192 * @constructor
3193 * @param {Object} [config] Configuration options
3194 */
3195 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
3196 // Parent constructor
3197 OO.ui.ProcessDialog.parent.call( this, config );
3198
3199 // Properties
3200 this.fitOnOpen = false;
3201
3202 // Initialization
3203 this.$element.addClass( 'oo-ui-processDialog' );
3204 };
3205
3206 /* Setup */
3207
3208 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
3209
3210 /* Methods */
3211
3212 /**
3213 * Handle dismiss button click events.
3214 *
3215 * Hides errors.
3216 *
3217 * @private
3218 */
3219 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
3220 this.hideErrors();
3221 };
3222
3223 /**
3224 * Handle retry button click events.
3225 *
3226 * Hides errors and then tries again.
3227 *
3228 * @private
3229 */
3230 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
3231 this.hideErrors();
3232 this.executeAction( this.currentAction );
3233 };
3234
3235 /**
3236 * @inheritdoc
3237 */
3238 OO.ui.ProcessDialog.prototype.initialize = function () {
3239 // Parent method
3240 OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
3241
3242 // Properties
3243 this.$navigation = $( '<div>' );
3244 this.$location = $( '<div>' );
3245 this.$safeActions = $( '<div>' );
3246 this.$primaryActions = $( '<div>' );
3247 this.$otherActions = $( '<div>' );
3248 this.dismissButton = new OO.ui.ButtonWidget( {
3249 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
3250 } );
3251 this.retryButton = new OO.ui.ButtonWidget();
3252 this.$errors = $( '<div>' );
3253 this.$errorsTitle = $( '<div>' );
3254
3255 // Events
3256 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
3257 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
3258 this.title.connect( this, { labelChange: 'fitLabel' } );
3259
3260 // Initialization
3261 this.title.$element.addClass( 'oo-ui-processDialog-title' );
3262 this.$location
3263 .append( this.title.$element )
3264 .addClass( 'oo-ui-processDialog-location' );
3265 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
3266 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
3267 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
3268 this.$errorsTitle
3269 .addClass( 'oo-ui-processDialog-errors-title' )
3270 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
3271 this.$errors
3272 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
3273 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
3274 this.$content
3275 .addClass( 'oo-ui-processDialog-content' )
3276 .append( this.$errors );
3277 this.$navigation
3278 .addClass( 'oo-ui-processDialog-navigation' )
3279 // Note: Order of appends below is important. These are in the order
3280 // we want tab to go through them. Display-order is handled entirely
3281 // by CSS absolute-positioning. As such, primary actions like "done"
3282 // should go first.
3283 .append( this.$primaryActions, this.$location, this.$safeActions );
3284 this.$head.append( this.$navigation );
3285 this.$foot.append( this.$otherActions );
3286 };
3287
3288 /**
3289 * @inheritdoc
3290 */
3291 OO.ui.ProcessDialog.prototype.getActionWidgetConfig = function ( config ) {
3292 var isMobile = OO.ui.isMobile();
3293
3294 // Default to unframed on mobile
3295 config = $.extend( { framed: !isMobile }, config );
3296 // Change back buttons to icon only on mobile
3297 if (
3298 isMobile &&
3299 ( config.flags === 'back' || ( Array.isArray( config.flags ) && config.flags.indexOf( 'back' ) !== -1 ) )
3300 ) {
3301 $.extend( config, {
3302 icon: 'previous',
3303 label: ''
3304 } );
3305 }
3306
3307 return config;
3308 };
3309
3310 /**
3311 * @inheritdoc
3312 */
3313 OO.ui.ProcessDialog.prototype.attachActions = function () {
3314 var i, len, other, special, others;
3315
3316 // Parent method
3317 OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
3318
3319 special = this.actions.getSpecial();
3320 others = this.actions.getOthers();
3321 if ( special.primary ) {
3322 this.$primaryActions.append( special.primary.$element );
3323 }
3324 for ( i = 0, len = others.length; i < len; i++ ) {
3325 other = others[ i ];
3326 this.$otherActions.append( other.$element );
3327 }
3328 if ( special.safe ) {
3329 this.$safeActions.append( special.safe.$element );
3330 }
3331 };
3332
3333 /**
3334 * @inheritdoc
3335 */
3336 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
3337 var process = this;
3338 return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
3339 .fail( function ( errors ) {
3340 process.showErrors( errors || [] );
3341 } );
3342 };
3343
3344 /**
3345 * @inheritdoc
3346 */
3347 OO.ui.ProcessDialog.prototype.setDimensions = function () {
3348 var dialog = this;
3349
3350 // Parent method
3351 OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
3352
3353 this.fitLabel();
3354
3355 // If there are many actions, they might be shown on multiple lines. Their layout can change when
3356 // resizing the dialog and when changing the actions. Adjust the height of the footer to fit them.
3357 dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) );
3358 // Wait for CSS transition to finish and do it again :(
3359 setTimeout( function () {
3360 dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) );
3361 }, 300 );
3362 };
3363
3364 /**
3365 * Fit label between actions.
3366 *
3367 * @private
3368 * @chainable
3369 * @return {OO.ui.MessageDialog} The dialog, for chaining
3370 */
3371 OO.ui.ProcessDialog.prototype.fitLabel = function () {
3372 var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
3373 size = this.getSizeProperties();
3374
3375 if ( typeof size.width !== 'number' ) {
3376 if ( this.isOpened() ) {
3377 navigationWidth = this.$head.width() - 20;
3378 } else if ( this.isOpening() ) {
3379 if ( !this.fitOnOpen ) {
3380 // Size is relative and the dialog isn't open yet, so wait.
3381 // FIXME: This should ideally be handled by setup somehow.
3382 this.manager.lifecycle.opened.done( this.fitLabel.bind( this ) );
3383 this.fitOnOpen = true;
3384 }
3385 return;
3386 } else {
3387 return;
3388 }
3389 } else {
3390 navigationWidth = size.width - 20;
3391 }
3392
3393 safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
3394 primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
3395 biggerWidth = Math.max( safeWidth, primaryWidth );
3396
3397 labelWidth = this.title.$element.width();
3398
3399 if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
3400 // We have enough space to center the label
3401 leftWidth = rightWidth = biggerWidth;
3402 } else {
3403 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
3404 if ( this.getDir() === 'ltr' ) {
3405 leftWidth = safeWidth;
3406 rightWidth = primaryWidth;
3407 } else {
3408 leftWidth = primaryWidth;
3409 rightWidth = safeWidth;
3410 }
3411 }
3412
3413 this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
3414
3415 return this;
3416 };
3417
3418 /**
3419 * Handle errors that occurred during accept or reject processes.
3420 *
3421 * @private
3422 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
3423 */
3424 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
3425 var i, len, $item, actions,
3426 items = [],
3427 abilities = {},
3428 recoverable = true,
3429 warning = false;
3430
3431 if ( errors instanceof OO.ui.Error ) {
3432 errors = [ errors ];
3433 }
3434
3435 for ( i = 0, len = errors.length; i < len; i++ ) {
3436 if ( !errors[ i ].isRecoverable() ) {
3437 recoverable = false;
3438 }
3439 if ( errors[ i ].isWarning() ) {
3440 warning = true;
3441 }
3442 $item = $( '<div>' )
3443 .addClass( 'oo-ui-processDialog-error' )
3444 .append( errors[ i ].getMessage() );
3445 items.push( $item[ 0 ] );
3446 }
3447 this.$errorItems = $( items );
3448 if ( recoverable ) {
3449 abilities[ this.currentAction ] = true;
3450 // Copy the flags from the first matching action
3451 actions = this.actions.get( { actions: this.currentAction } );
3452 if ( actions.length ) {
3453 this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
3454 }
3455 } else {
3456 abilities[ this.currentAction ] = false;
3457 this.actions.setAbilities( abilities );
3458 }
3459 if ( warning ) {
3460 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
3461 } else {
3462 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
3463 }
3464 this.retryButton.toggle( recoverable );
3465 this.$errorsTitle.after( this.$errorItems );
3466 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
3467 };
3468
3469 /**
3470 * Hide errors.
3471 *
3472 * @private
3473 */
3474 OO.ui.ProcessDialog.prototype.hideErrors = function () {
3475 this.$errors.addClass( 'oo-ui-element-hidden' );
3476 if ( this.$errorItems ) {
3477 this.$errorItems.remove();
3478 this.$errorItems = null;
3479 }
3480 };
3481
3482 /**
3483 * @inheritdoc
3484 */
3485 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
3486 // Parent method
3487 return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
3488 .first( function () {
3489 // Make sure to hide errors
3490 this.hideErrors();
3491 this.fitOnOpen = false;
3492 }, this );
3493 };
3494
3495 /**
3496 * @class OO.ui
3497 */
3498
3499 /**
3500 * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
3501 * OO.ui.confirm.
3502 *
3503 * @private
3504 * @return {OO.ui.WindowManager}
3505 */
3506 OO.ui.getWindowManager = function () {
3507 if ( !OO.ui.windowManager ) {
3508 OO.ui.windowManager = new OO.ui.WindowManager();
3509 $( document.body ).append( OO.ui.windowManager.$element );
3510 OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
3511 }
3512 return OO.ui.windowManager;
3513 };
3514
3515 /**
3516 * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
3517 * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
3518 * has only one action button, labelled "OK", clicking it will simply close the dialog.
3519 *
3520 * A window manager is created automatically when this function is called for the first time.
3521 *
3522 * @example
3523 * OO.ui.alert( 'Something happened!' ).done( function () {
3524 * console.log( 'User closed the dialog.' );
3525 * } );
3526 *
3527 * OO.ui.alert( 'Something larger happened!', { size: 'large' } );
3528 *
3529 * @param {jQuery|string} text Message text to display
3530 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
3531 * @return {jQuery.Promise} Promise resolved when the user closes the dialog
3532 */
3533 OO.ui.alert = function ( text, options ) {
3534 return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
3535 message: text,
3536 actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
3537 }, options ) ).closed.then( function () {
3538 return undefined;
3539 } );
3540 };
3541
3542 /**
3543 * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
3544 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
3545 * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
3546 * (labelled "Cancel").
3547 *
3548 * A window manager is created automatically when this function is called for the first time.
3549 *
3550 * @example
3551 * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
3552 * if ( confirmed ) {
3553 * console.log( 'User clicked "OK"!' );
3554 * } else {
3555 * console.log( 'User clicked "Cancel" or closed the dialog.' );
3556 * }
3557 * } );
3558 *
3559 * @param {jQuery|string} text Message text to display
3560 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
3561 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
3562 * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
3563 * `false`.
3564 */
3565 OO.ui.confirm = function ( text, options ) {
3566 return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
3567 message: text
3568 }, options ) ).closed.then( function ( data ) {
3569 return !!( data && data.action === 'accept' );
3570 } );
3571 };
3572
3573 /**
3574 * Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open,
3575 * the rest of the page will be dimmed out and the user won't be able to interact with it. The
3576 * dialog has a text input widget and two action buttons, one to confirm an operation (labelled "OK")
3577 * and one to cancel it (labelled "Cancel").
3578 *
3579 * A window manager is created automatically when this function is called for the first time.
3580 *
3581 * @example
3582 * OO.ui.prompt( 'Choose a line to go to', { textInput: { placeholder: 'Line number' } } ).done( function ( result ) {
3583 * if ( result !== null ) {
3584 * console.log( 'User typed "' + result + '" then clicked "OK".' );
3585 * } else {
3586 * console.log( 'User clicked "Cancel" or closed the dialog.' );
3587 * }
3588 * } );
3589 *
3590 * @param {jQuery|string} text Message text to display
3591 * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
3592 * @param {Object} [options.textInput] Additional options for text input widget, see OO.ui.TextInputWidget
3593 * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
3594 * confirm, the promise will resolve with the value of the text input widget; otherwise, it will
3595 * resolve to `null`.
3596 */
3597 OO.ui.prompt = function ( text, options ) {
3598 var instance,
3599 manager = OO.ui.getWindowManager(),
3600 textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ),
3601 textField = new OO.ui.FieldLayout( textInput, {
3602 align: 'top',
3603 label: text
3604 } );
3605
3606 instance = manager.openWindow( 'message', $.extend( {
3607 message: textField.$element
3608 }, options ) );
3609
3610 // TODO: This is a little hacky, and could be done by extending MessageDialog instead.
3611 instance.opened.then( function () {
3612 textInput.on( 'enter', function () {
3613 manager.getCurrentWindow().close( { action: 'accept' } );
3614 } );
3615 textInput.focus();
3616 } );
3617
3618 return instance.closed.then( function ( data ) {
3619 return data && data.action === 'accept' ? textInput.getValue() : null;
3620 } );
3621 };
3622
3623 }( OO ) );
3624
3625 //# sourceMappingURL=oojs-ui-windows.js.map.json