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