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