Merge "Update redirect arrows to use SVG versions"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.2.4
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2014 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2014-12-02T18:45:19Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Get the user's language and any fallback languages.
49 *
50 * These language codes are used to localize user interface elements in the user's language.
51 *
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
54 *
55 * @return {string[]} Language codes, in descending order of priority
56 */
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
59 };
60
61 /**
62 * Get a value in an object keyed by language code.
63 *
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
68 */
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
71
72 // Requested language
73 if ( obj[lang] ) {
74 return obj[lang];
75 }
76 // Known user language
77 langs = OO.ui.getUserLanguages();
78 for ( i = 0, len = langs.length; i < len; i++ ) {
79 lang = langs[i];
80 if ( obj[lang] ) {
81 return obj[lang];
82 }
83 }
84 // Fallback language
85 if ( obj[fallback] ) {
86 return obj[fallback];
87 }
88 // First existing language
89 for ( lang in obj ) {
90 return obj[lang];
91 }
92
93 return undefined;
94 };
95
96 /**
97 * Check if a node is contained within another node
98 *
99 * Similar to jQuery#contains except a list of containers can be supplied
100 * and a boolean argument allows you to include the container in the match list
101 *
102 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
103 * @param {HTMLElement} contained Node to find
104 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
105 * @return {boolean} The node is in the list of target nodes
106 */
107 OO.ui.contains = function ( containers, contained, matchContainers ) {
108 var i;
109 if ( !Array.isArray( containers ) ) {
110 containers = [ containers ];
111 }
112 for ( i = containers.length - 1; i >= 0; i-- ) {
113 if ( ( matchContainers && contained === containers[i] ) || $.contains( containers[i], contained ) ) {
114 return true;
115 }
116 }
117 return false;
118 };
119
120 ( function () {
121 /**
122 * Message store for the default implementation of OO.ui.msg
123 *
124 * Environments that provide a localization system should not use this, but should override
125 * OO.ui.msg altogether.
126 *
127 * @private
128 */
129 var messages = {
130 // Tool tip for a button that moves items in a list down one place
131 'ooui-outline-control-move-down': 'Move item down',
132 // Tool tip for a button that moves items in a list up one place
133 'ooui-outline-control-move-up': 'Move item up',
134 // Tool tip for a button that removes items from a list
135 'ooui-outline-control-remove': 'Remove item',
136 // Label for the toolbar group that contains a list of all other available tools
137 'ooui-toolbar-more': 'More',
138 // Label for the fake tool that expands the full list of tools in a toolbar group
139 'ooui-toolgroup-expand': 'More',
140 // Label for the fake tool that collapses the full list of tools in a toolbar group
141 'ooui-toolgroup-collapse': 'Fewer',
142 // Default label for the accept button of a confirmation dialog
143 'ooui-dialog-message-accept': 'OK',
144 // Default label for the reject button of a confirmation dialog
145 'ooui-dialog-message-reject': 'Cancel',
146 // Title for process dialog error description
147 'ooui-dialog-process-error': 'Something went wrong',
148 // Label for process dialog dismiss error button, visible when describing errors
149 'ooui-dialog-process-dismiss': 'Dismiss',
150 // Label for process dialog retry action button, visible when describing only recoverable errors
151 'ooui-dialog-process-retry': 'Try again',
152 // Label for process dialog retry action button, visible when describing only warnings
153 'ooui-dialog-process-continue': 'Continue'
154 };
155
156 /**
157 * Get a localized message.
158 *
159 * In environments that provide a localization system, this function should be overridden to
160 * return the message translated in the user's language. The default implementation always returns
161 * English messages.
162 *
163 * After the message key, message parameters may optionally be passed. In the default implementation,
164 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
165 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
166 * they support unnamed, ordered message parameters.
167 *
168 * @abstract
169 * @param {string} key Message key
170 * @param {Mixed...} [params] Message parameters
171 * @return {string} Translated message with parameters substituted
172 */
173 OO.ui.msg = function ( key ) {
174 var message = messages[key], params = Array.prototype.slice.call( arguments, 1 );
175 if ( typeof message === 'string' ) {
176 // Perform $1 substitution
177 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
178 var i = parseInt( n, 10 );
179 return params[i - 1] !== undefined ? params[i - 1] : '$' + n;
180 } );
181 } else {
182 // Return placeholder if message not found
183 message = '[' + key + ']';
184 }
185 return message;
186 };
187
188 /**
189 * Package a message and arguments for deferred resolution.
190 *
191 * Use this when you are statically specifying a message and the message may not yet be present.
192 *
193 * @param {string} key Message key
194 * @param {Mixed...} [params] Message parameters
195 * @return {Function} Function that returns the resolved message when executed
196 */
197 OO.ui.deferMsg = function () {
198 var args = arguments;
199 return function () {
200 return OO.ui.msg.apply( OO.ui, args );
201 };
202 };
203
204 /**
205 * Resolve a message.
206 *
207 * If the message is a function it will be executed, otherwise it will pass through directly.
208 *
209 * @param {Function|string} msg Deferred message, or message text
210 * @return {string} Resolved message
211 */
212 OO.ui.resolveMsg = function ( msg ) {
213 if ( $.isFunction( msg ) ) {
214 return msg();
215 }
216 return msg;
217 };
218
219 } )();
220
221 /**
222 * Element that can be marked as pending.
223 *
224 * @abstract
225 * @class
226 *
227 * @constructor
228 * @param {Object} [config] Configuration options
229 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
230 */
231 OO.ui.PendingElement = function OoUiPendingElement( config ) {
232 // Configuration initialization
233 config = config || {};
234
235 // Properties
236 this.pending = 0;
237 this.$pending = null;
238
239 // Initialisation
240 this.setPendingElement( config.$pending || this.$element );
241 };
242
243 /* Setup */
244
245 OO.initClass( OO.ui.PendingElement );
246
247 /* Methods */
248
249 /**
250 * Set the pending element (and clean up any existing one).
251 *
252 * @param {jQuery} $pending The element to set to pending.
253 */
254 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
255 if ( this.$pending ) {
256 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
257 }
258
259 this.$pending = $pending;
260 if ( this.pending > 0 ) {
261 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
262 }
263 };
264
265 /**
266 * Check if input is pending.
267 *
268 * @return {boolean}
269 */
270 OO.ui.PendingElement.prototype.isPending = function () {
271 return !!this.pending;
272 };
273
274 /**
275 * Increase the pending stack.
276 *
277 * @chainable
278 */
279 OO.ui.PendingElement.prototype.pushPending = function () {
280 if ( this.pending === 0 ) {
281 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
282 this.updateThemeClasses();
283 }
284 this.pending++;
285
286 return this;
287 };
288
289 /**
290 * Reduce the pending stack.
291 *
292 * Clamped at zero.
293 *
294 * @chainable
295 */
296 OO.ui.PendingElement.prototype.popPending = function () {
297 if ( this.pending === 1 ) {
298 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
299 this.updateThemeClasses();
300 }
301 this.pending = Math.max( 0, this.pending - 1 );
302
303 return this;
304 };
305
306 /**
307 * List of actions.
308 *
309 * @abstract
310 * @class
311 * @mixins OO.EventEmitter
312 *
313 * @constructor
314 * @param {Object} [config] Configuration options
315 */
316 OO.ui.ActionSet = function OoUiActionSet( config ) {
317 // Configuration initialization
318 config = config || {};
319
320 // Mixin constructors
321 OO.EventEmitter.call( this );
322
323 // Properties
324 this.list = [];
325 this.categories = {
326 actions: 'getAction',
327 flags: 'getFlags',
328 modes: 'getModes'
329 };
330 this.categorized = {};
331 this.special = {};
332 this.others = [];
333 this.organized = false;
334 this.changing = false;
335 this.changed = false;
336 };
337
338 /* Setup */
339
340 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
341
342 /* Static Properties */
343
344 /**
345 * Symbolic name of dialog.
346 *
347 * @abstract
348 * @static
349 * @inheritable
350 * @property {string}
351 */
352 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
353
354 /* Events */
355
356 /**
357 * @event click
358 * @param {OO.ui.ActionWidget} action Action that was clicked
359 */
360
361 /**
362 * @event resize
363 * @param {OO.ui.ActionWidget} action Action that was resized
364 */
365
366 /**
367 * @event add
368 * @param {OO.ui.ActionWidget[]} added Actions added
369 */
370
371 /**
372 * @event remove
373 * @param {OO.ui.ActionWidget[]} added Actions removed
374 */
375
376 /**
377 * @event change
378 */
379
380 /* Methods */
381
382 /**
383 * Handle action change events.
384 *
385 * @fires change
386 */
387 OO.ui.ActionSet.prototype.onActionChange = function () {
388 this.organized = false;
389 if ( this.changing ) {
390 this.changed = true;
391 } else {
392 this.emit( 'change' );
393 }
394 };
395
396 /**
397 * Check if a action is one of the special actions.
398 *
399 * @param {OO.ui.ActionWidget} action Action to check
400 * @return {boolean} Action is special
401 */
402 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
403 var flag;
404
405 for ( flag in this.special ) {
406 if ( action === this.special[flag] ) {
407 return true;
408 }
409 }
410
411 return false;
412 };
413
414 /**
415 * Get actions.
416 *
417 * @param {Object} [filters] Filters to use, omit to get all actions
418 * @param {string|string[]} [filters.actions] Actions that actions must have
419 * @param {string|string[]} [filters.flags] Flags that actions must have
420 * @param {string|string[]} [filters.modes] Modes that actions must have
421 * @param {boolean} [filters.visible] Actions must be visible
422 * @param {boolean} [filters.disabled] Actions must be disabled
423 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
424 */
425 OO.ui.ActionSet.prototype.get = function ( filters ) {
426 var i, len, list, category, actions, index, match, matches;
427
428 if ( filters ) {
429 this.organize();
430
431 // Collect category candidates
432 matches = [];
433 for ( category in this.categorized ) {
434 list = filters[category];
435 if ( list ) {
436 if ( !Array.isArray( list ) ) {
437 list = [ list ];
438 }
439 for ( i = 0, len = list.length; i < len; i++ ) {
440 actions = this.categorized[category][list[i]];
441 if ( Array.isArray( actions ) ) {
442 matches.push.apply( matches, actions );
443 }
444 }
445 }
446 }
447 // Remove by boolean filters
448 for ( i = 0, len = matches.length; i < len; i++ ) {
449 match = matches[i];
450 if (
451 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
452 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
453 ) {
454 matches.splice( i, 1 );
455 len--;
456 i--;
457 }
458 }
459 // Remove duplicates
460 for ( i = 0, len = matches.length; i < len; i++ ) {
461 match = matches[i];
462 index = matches.lastIndexOf( match );
463 while ( index !== i ) {
464 matches.splice( index, 1 );
465 len--;
466 index = matches.lastIndexOf( match );
467 }
468 }
469 return matches;
470 }
471 return this.list.slice();
472 };
473
474 /**
475 * Get special actions.
476 *
477 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
478 * Special flags can be configured by changing #static-specialFlags in a subclass.
479 *
480 * @return {OO.ui.ActionWidget|null} Safe action
481 */
482 OO.ui.ActionSet.prototype.getSpecial = function () {
483 this.organize();
484 return $.extend( {}, this.special );
485 };
486
487 /**
488 * Get other actions.
489 *
490 * Other actions include all non-special visible actions.
491 *
492 * @return {OO.ui.ActionWidget[]} Other actions
493 */
494 OO.ui.ActionSet.prototype.getOthers = function () {
495 this.organize();
496 return this.others.slice();
497 };
498
499 /**
500 * Toggle actions based on their modes.
501 *
502 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
503 * visibility; matching actions will be shown, non-matching actions will be hidden.
504 *
505 * @param {string} mode Mode actions must have
506 * @chainable
507 * @fires toggle
508 * @fires change
509 */
510 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
511 var i, len, action;
512
513 this.changing = true;
514 for ( i = 0, len = this.list.length; i < len; i++ ) {
515 action = this.list[i];
516 action.toggle( action.hasMode( mode ) );
517 }
518
519 this.organized = false;
520 this.changing = false;
521 this.emit( 'change' );
522
523 return this;
524 };
525
526 /**
527 * Change which actions are able to be performed.
528 *
529 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
530 *
531 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
532 * indicate actions are able to be performed
533 * @chainable
534 */
535 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
536 var i, len, action, item;
537
538 for ( i = 0, len = this.list.length; i < len; i++ ) {
539 item = this.list[i];
540 action = item.getAction();
541 if ( actions[action] !== undefined ) {
542 item.setDisabled( !actions[action] );
543 }
544 }
545
546 return this;
547 };
548
549 /**
550 * Executes a function once per action.
551 *
552 * When making changes to multiple actions, use this method instead of iterating over the actions
553 * manually to defer emitting a change event until after all actions have been changed.
554 *
555 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
556 * @param {Function} callback Callback to run for each action; callback is invoked with three
557 * arguments: the action, the action's index, the list of actions being iterated over
558 * @chainable
559 */
560 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
561 this.changed = false;
562 this.changing = true;
563 this.get( filter ).forEach( callback );
564 this.changing = false;
565 if ( this.changed ) {
566 this.emit( 'change' );
567 }
568
569 return this;
570 };
571
572 /**
573 * Add actions.
574 *
575 * @param {OO.ui.ActionWidget[]} actions Actions to add
576 * @chainable
577 * @fires add
578 * @fires change
579 */
580 OO.ui.ActionSet.prototype.add = function ( actions ) {
581 var i, len, action;
582
583 this.changing = true;
584 for ( i = 0, len = actions.length; i < len; i++ ) {
585 action = actions[i];
586 action.connect( this, {
587 click: [ 'emit', 'click', action ],
588 resize: [ 'emit', 'resize', action ],
589 toggle: [ 'onActionChange' ]
590 } );
591 this.list.push( action );
592 }
593 this.organized = false;
594 this.emit( 'add', actions );
595 this.changing = false;
596 this.emit( 'change' );
597
598 return this;
599 };
600
601 /**
602 * Remove actions.
603 *
604 * @param {OO.ui.ActionWidget[]} actions Actions to remove
605 * @chainable
606 * @fires remove
607 * @fires change
608 */
609 OO.ui.ActionSet.prototype.remove = function ( actions ) {
610 var i, len, index, action;
611
612 this.changing = true;
613 for ( i = 0, len = actions.length; i < len; i++ ) {
614 action = actions[i];
615 index = this.list.indexOf( action );
616 if ( index !== -1 ) {
617 action.disconnect( this );
618 this.list.splice( index, 1 );
619 }
620 }
621 this.organized = false;
622 this.emit( 'remove', actions );
623 this.changing = false;
624 this.emit( 'change' );
625
626 return this;
627 };
628
629 /**
630 * Remove all actions.
631 *
632 * @chainable
633 * @fires remove
634 * @fires change
635 */
636 OO.ui.ActionSet.prototype.clear = function () {
637 var i, len, action,
638 removed = this.list.slice();
639
640 this.changing = true;
641 for ( i = 0, len = this.list.length; i < len; i++ ) {
642 action = this.list[i];
643 action.disconnect( this );
644 }
645
646 this.list = [];
647
648 this.organized = false;
649 this.emit( 'remove', removed );
650 this.changing = false;
651 this.emit( 'change' );
652
653 return this;
654 };
655
656 /**
657 * Organize actions.
658 *
659 * This is called whenever organized information is requested. It will only reorganize the actions
660 * if something has changed since the last time it ran.
661 *
662 * @private
663 * @chainable
664 */
665 OO.ui.ActionSet.prototype.organize = function () {
666 var i, iLen, j, jLen, flag, action, category, list, item, special,
667 specialFlags = this.constructor.static.specialFlags;
668
669 if ( !this.organized ) {
670 this.categorized = {};
671 this.special = {};
672 this.others = [];
673 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
674 action = this.list[i];
675 if ( action.isVisible() ) {
676 // Populate categories
677 for ( category in this.categories ) {
678 if ( !this.categorized[category] ) {
679 this.categorized[category] = {};
680 }
681 list = action[this.categories[category]]();
682 if ( !Array.isArray( list ) ) {
683 list = [ list ];
684 }
685 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
686 item = list[j];
687 if ( !this.categorized[category][item] ) {
688 this.categorized[category][item] = [];
689 }
690 this.categorized[category][item].push( action );
691 }
692 }
693 // Populate special/others
694 special = false;
695 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
696 flag = specialFlags[j];
697 if ( !this.special[flag] && action.hasFlag( flag ) ) {
698 this.special[flag] = action;
699 special = true;
700 break;
701 }
702 }
703 if ( !special ) {
704 this.others.push( action );
705 }
706 }
707 }
708 this.organized = true;
709 }
710
711 return this;
712 };
713
714 /**
715 * DOM element abstraction.
716 *
717 * @abstract
718 * @class
719 *
720 * @constructor
721 * @param {Object} [config] Configuration options
722 * @cfg {Function} [$] jQuery for the frame the widget is in
723 * @cfg {string[]} [classes] CSS class names to add
724 * @cfg {string} [text] Text to insert
725 * @cfg {jQuery} [$content] Content elements to append (after text)
726 * @cfg {Mixed} [data] Element data
727 */
728 OO.ui.Element = function OoUiElement( config ) {
729 // Configuration initialization
730 config = config || {};
731
732 // Properties
733 this.$ = config.$ || OO.ui.Element.getJQuery( document );
734 this.data = config.data;
735 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
736 this.elementGroup = null;
737 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
738 this.updateThemeClassesPending = false;
739
740 // Initialization
741 if ( $.isArray( config.classes ) ) {
742 this.$element.addClass( config.classes.join( ' ' ) );
743 }
744 if ( config.text ) {
745 this.$element.text( config.text );
746 }
747 if ( config.$content ) {
748 this.$element.append( config.$content );
749 }
750 };
751
752 /* Setup */
753
754 OO.initClass( OO.ui.Element );
755
756 /* Static Properties */
757
758 /**
759 * HTML tag name.
760 *
761 * This may be ignored if #getTagName is overridden.
762 *
763 * @static
764 * @inheritable
765 * @property {string}
766 */
767 OO.ui.Element.static.tagName = 'div';
768
769 /* Static Methods */
770
771 /**
772 * Get a jQuery function within a specific document.
773 *
774 * @static
775 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
776 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
777 * not in an iframe
778 * @return {Function} Bound jQuery function
779 */
780 OO.ui.Element.getJQuery = function ( context, $iframe ) {
781 function wrapper( selector ) {
782 return $( selector, wrapper.context );
783 }
784
785 wrapper.context = this.getDocument( context );
786
787 if ( $iframe ) {
788 wrapper.$iframe = $iframe;
789 }
790
791 return wrapper;
792 };
793
794 /**
795 * Get the document of an element.
796 *
797 * @static
798 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
799 * @return {HTMLDocument|null} Document object
800 */
801 OO.ui.Element.getDocument = function ( obj ) {
802 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
803 return ( obj[0] && obj[0].ownerDocument ) ||
804 // Empty jQuery selections might have a context
805 obj.context ||
806 // HTMLElement
807 obj.ownerDocument ||
808 // Window
809 obj.document ||
810 // HTMLDocument
811 ( obj.nodeType === 9 && obj ) ||
812 null;
813 };
814
815 /**
816 * Get the window of an element or document.
817 *
818 * @static
819 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
820 * @return {Window} Window object
821 */
822 OO.ui.Element.getWindow = function ( obj ) {
823 var doc = this.getDocument( obj );
824 return doc.parentWindow || doc.defaultView;
825 };
826
827 /**
828 * Get the direction of an element or document.
829 *
830 * @static
831 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
832 * @return {string} Text direction, either 'ltr' or 'rtl'
833 */
834 OO.ui.Element.getDir = function ( obj ) {
835 var isDoc, isWin;
836
837 if ( obj instanceof jQuery ) {
838 obj = obj[0];
839 }
840 isDoc = obj.nodeType === 9;
841 isWin = obj.document !== undefined;
842 if ( isDoc || isWin ) {
843 if ( isWin ) {
844 obj = obj.document;
845 }
846 obj = obj.body;
847 }
848 return $( obj ).css( 'direction' );
849 };
850
851 /**
852 * Get the offset between two frames.
853 *
854 * TODO: Make this function not use recursion.
855 *
856 * @static
857 * @param {Window} from Window of the child frame
858 * @param {Window} [to=window] Window of the parent frame
859 * @param {Object} [offset] Offset to start with, used internally
860 * @return {Object} Offset object, containing left and top properties
861 */
862 OO.ui.Element.getFrameOffset = function ( from, to, offset ) {
863 var i, len, frames, frame, rect;
864
865 if ( !to ) {
866 to = window;
867 }
868 if ( !offset ) {
869 offset = { top: 0, left: 0 };
870 }
871 if ( from.parent === from ) {
872 return offset;
873 }
874
875 // Get iframe element
876 frames = from.parent.document.getElementsByTagName( 'iframe' );
877 for ( i = 0, len = frames.length; i < len; i++ ) {
878 if ( frames[i].contentWindow === from ) {
879 frame = frames[i];
880 break;
881 }
882 }
883
884 // Recursively accumulate offset values
885 if ( frame ) {
886 rect = frame.getBoundingClientRect();
887 offset.left += rect.left;
888 offset.top += rect.top;
889 if ( from !== to ) {
890 this.getFrameOffset( from.parent, offset );
891 }
892 }
893 return offset;
894 };
895
896 /**
897 * Get the offset between two elements.
898 *
899 * The two elements may be in a different frame, but in that case the frame $element is in must
900 * be contained in the frame $anchor is in.
901 *
902 * @static
903 * @param {jQuery} $element Element whose position to get
904 * @param {jQuery} $anchor Element to get $element's position relative to
905 * @return {Object} Translated position coordinates, containing top and left properties
906 */
907 OO.ui.Element.getRelativePosition = function ( $element, $anchor ) {
908 var iframe, iframePos,
909 pos = $element.offset(),
910 anchorPos = $anchor.offset(),
911 elementDocument = this.getDocument( $element ),
912 anchorDocument = this.getDocument( $anchor );
913
914 // If $element isn't in the same document as $anchor, traverse up
915 while ( elementDocument !== anchorDocument ) {
916 iframe = elementDocument.defaultView.frameElement;
917 if ( !iframe ) {
918 throw new Error( '$element frame is not contained in $anchor frame' );
919 }
920 iframePos = $( iframe ).offset();
921 pos.left += iframePos.left;
922 pos.top += iframePos.top;
923 elementDocument = iframe.ownerDocument;
924 }
925 pos.left -= anchorPos.left;
926 pos.top -= anchorPos.top;
927 return pos;
928 };
929
930 /**
931 * Get element border sizes.
932 *
933 * @static
934 * @param {HTMLElement} el Element to measure
935 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
936 */
937 OO.ui.Element.getBorders = function ( el ) {
938 var doc = el.ownerDocument,
939 win = doc.parentWindow || doc.defaultView,
940 style = win && win.getComputedStyle ?
941 win.getComputedStyle( el, null ) :
942 el.currentStyle,
943 $el = $( el ),
944 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
945 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
946 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
947 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
948
949 return {
950 top: Math.round( top ),
951 left: Math.round( left ),
952 bottom: Math.round( bottom ),
953 right: Math.round( right )
954 };
955 };
956
957 /**
958 * Get dimensions of an element or window.
959 *
960 * @static
961 * @param {HTMLElement|Window} el Element to measure
962 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
963 */
964 OO.ui.Element.getDimensions = function ( el ) {
965 var $el, $win,
966 doc = el.ownerDocument || el.document,
967 win = doc.parentWindow || doc.defaultView;
968
969 if ( win === el || el === doc.documentElement ) {
970 $win = $( win );
971 return {
972 borders: { top: 0, left: 0, bottom: 0, right: 0 },
973 scroll: {
974 top: $win.scrollTop(),
975 left: $win.scrollLeft()
976 },
977 scrollbar: { right: 0, bottom: 0 },
978 rect: {
979 top: 0,
980 left: 0,
981 bottom: $win.innerHeight(),
982 right: $win.innerWidth()
983 }
984 };
985 } else {
986 $el = $( el );
987 return {
988 borders: this.getBorders( el ),
989 scroll: {
990 top: $el.scrollTop(),
991 left: $el.scrollLeft()
992 },
993 scrollbar: {
994 right: $el.innerWidth() - el.clientWidth,
995 bottom: $el.innerHeight() - el.clientHeight
996 },
997 rect: el.getBoundingClientRect()
998 };
999 }
1000 };
1001
1002 /**
1003 * Get closest scrollable container.
1004 *
1005 * Traverses up until either a scrollable element or the root is reached, in which case the window
1006 * will be returned.
1007 *
1008 * @static
1009 * @param {HTMLElement} el Element to find scrollable container for
1010 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1011 * @return {HTMLElement} Closest scrollable container
1012 */
1013 OO.ui.Element.getClosestScrollableContainer = function ( el, dimension ) {
1014 var i, val,
1015 props = [ 'overflow' ],
1016 $parent = $( el ).parent();
1017
1018 if ( dimension === 'x' || dimension === 'y' ) {
1019 props.push( 'overflow-' + dimension );
1020 }
1021
1022 while ( $parent.length ) {
1023 if ( $parent[0] === el.ownerDocument.body ) {
1024 return $parent[0];
1025 }
1026 i = props.length;
1027 while ( i-- ) {
1028 val = $parent.css( props[i] );
1029 if ( val === 'auto' || val === 'scroll' ) {
1030 return $parent[0];
1031 }
1032 }
1033 $parent = $parent.parent();
1034 }
1035 return this.getDocument( el ).body;
1036 };
1037
1038 /**
1039 * Scroll element into view.
1040 *
1041 * @static
1042 * @param {HTMLElement} el Element to scroll into view
1043 * @param {Object} [config] Configuration options
1044 * @param {string} [config.duration] jQuery animation duration value
1045 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1046 * to scroll in both directions
1047 * @param {Function} [config.complete] Function to call when scrolling completes
1048 */
1049 OO.ui.Element.scrollIntoView = function ( el, config ) {
1050 // Configuration initialization
1051 config = config || {};
1052
1053 var rel, anim = {},
1054 callback = typeof config.complete === 'function' && config.complete,
1055 sc = this.getClosestScrollableContainer( el, config.direction ),
1056 $sc = $( sc ),
1057 eld = this.getDimensions( el ),
1058 scd = this.getDimensions( sc ),
1059 $win = $( this.getWindow( el ) );
1060
1061 // Compute the distances between the edges of el and the edges of the scroll viewport
1062 if ( $sc.is( 'body' ) ) {
1063 // If the scrollable container is the <body> this is easy
1064 rel = {
1065 top: eld.rect.top,
1066 bottom: $win.innerHeight() - eld.rect.bottom,
1067 left: eld.rect.left,
1068 right: $win.innerWidth() - eld.rect.right
1069 };
1070 } else {
1071 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1072 rel = {
1073 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1074 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1075 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1076 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1077 };
1078 }
1079
1080 if ( !config.direction || config.direction === 'y' ) {
1081 if ( rel.top < 0 ) {
1082 anim.scrollTop = scd.scroll.top + rel.top;
1083 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1084 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1085 }
1086 }
1087 if ( !config.direction || config.direction === 'x' ) {
1088 if ( rel.left < 0 ) {
1089 anim.scrollLeft = scd.scroll.left + rel.left;
1090 } else if ( rel.left > 0 && rel.right < 0 ) {
1091 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1092 }
1093 }
1094 if ( !$.isEmptyObject( anim ) ) {
1095 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1096 if ( callback ) {
1097 $sc.queue( function ( next ) {
1098 callback();
1099 next();
1100 } );
1101 }
1102 } else {
1103 if ( callback ) {
1104 callback();
1105 }
1106 }
1107 };
1108
1109 /**
1110 * Bind a handler for an event on a DOM element.
1111 *
1112 * Used to be for working around a jQuery bug (jqbug.com/14180),
1113 * but obsolete as of jQuery 1.11.0.
1114 *
1115 * @static
1116 * @deprecated Use jQuery#on instead.
1117 * @param {HTMLElement|jQuery} el DOM element
1118 * @param {string} event Event to bind
1119 * @param {Function} callback Callback to call when the event fires
1120 */
1121 OO.ui.Element.onDOMEvent = function ( el, event, callback ) {
1122 $( el ).on( event, callback );
1123 };
1124
1125 /**
1126 * Unbind a handler bound with #static-method-onDOMEvent.
1127 *
1128 * @deprecated Use jQuery#off instead.
1129 * @static
1130 * @param {HTMLElement|jQuery} el DOM element
1131 * @param {string} event Event to unbind
1132 * @param {Function} [callback] Callback to unbind
1133 */
1134 OO.ui.Element.offDOMEvent = function ( el, event, callback ) {
1135 $( el ).off( event, callback );
1136 };
1137
1138 /* Methods */
1139
1140 /**
1141 * Get element data.
1142 *
1143 * @return {Mixed} Element data
1144 */
1145 OO.ui.Element.prototype.getData = function () {
1146 return this.data;
1147 };
1148
1149 /**
1150 * Set element data.
1151 *
1152 * @param {Mixed} Element data
1153 * @chainable
1154 */
1155 OO.ui.Element.prototype.setData = function ( data ) {
1156 this.data = data;
1157 return this;
1158 };
1159
1160 /**
1161 * Check if element supports one or more methods.
1162 *
1163 * @param {string|string[]} methods Method or list of methods to check
1164 * @return {boolean} All methods are supported
1165 */
1166 OO.ui.Element.prototype.supports = function ( methods ) {
1167 var i, len,
1168 support = 0;
1169
1170 methods = $.isArray( methods ) ? methods : [ methods ];
1171 for ( i = 0, len = methods.length; i < len; i++ ) {
1172 if ( $.isFunction( this[methods[i]] ) ) {
1173 support++;
1174 }
1175 }
1176
1177 return methods.length === support;
1178 };
1179
1180 /**
1181 * Update the theme-provided classes.
1182 *
1183 * @localdoc This is called in element mixins and widget classes any time state changes.
1184 * Updating is debounced, minimizing overhead of changing multiple attributes and
1185 * guaranteeing that theme updates do not occur within an element's constructor
1186 */
1187 OO.ui.Element.prototype.updateThemeClasses = function () {
1188 if ( !this.updateThemeClassesPending ) {
1189 this.updateThemeClassesPending = true;
1190 setTimeout( this.debouncedUpdateThemeClassesHandler );
1191 }
1192 };
1193
1194 /**
1195 * @private
1196 */
1197 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1198 OO.ui.theme.updateElementClasses( this );
1199 this.updateThemeClassesPending = false;
1200 };
1201
1202 /**
1203 * Get the HTML tag name.
1204 *
1205 * Override this method to base the result on instance information.
1206 *
1207 * @return {string} HTML tag name
1208 */
1209 OO.ui.Element.prototype.getTagName = function () {
1210 return this.constructor.static.tagName;
1211 };
1212
1213 /**
1214 * Check if the element is attached to the DOM
1215 * @return {boolean} The element is attached to the DOM
1216 */
1217 OO.ui.Element.prototype.isElementAttached = function () {
1218 return $.contains( this.getElementDocument(), this.$element[0] );
1219 };
1220
1221 /**
1222 * Get the DOM document.
1223 *
1224 * @return {HTMLDocument} Document object
1225 */
1226 OO.ui.Element.prototype.getElementDocument = function () {
1227 return OO.ui.Element.getDocument( this.$element );
1228 };
1229
1230 /**
1231 * Get the DOM window.
1232 *
1233 * @return {Window} Window object
1234 */
1235 OO.ui.Element.prototype.getElementWindow = function () {
1236 return OO.ui.Element.getWindow( this.$element );
1237 };
1238
1239 /**
1240 * Get closest scrollable container.
1241 */
1242 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1243 return OO.ui.Element.getClosestScrollableContainer( this.$element[0] );
1244 };
1245
1246 /**
1247 * Get group element is in.
1248 *
1249 * @return {OO.ui.GroupElement|null} Group element, null if none
1250 */
1251 OO.ui.Element.prototype.getElementGroup = function () {
1252 return this.elementGroup;
1253 };
1254
1255 /**
1256 * Set group element is in.
1257 *
1258 * @param {OO.ui.GroupElement|null} group Group element, null if none
1259 * @chainable
1260 */
1261 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1262 this.elementGroup = group;
1263 return this;
1264 };
1265
1266 /**
1267 * Scroll element into view.
1268 *
1269 * @param {Object} [config] Configuration options
1270 */
1271 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1272 return OO.ui.Element.scrollIntoView( this.$element[0], config );
1273 };
1274
1275 /**
1276 * Bind a handler for an event on this.$element
1277 *
1278 * @deprecated Use jQuery#on instead.
1279 * @param {string} event
1280 * @param {Function} callback
1281 */
1282 OO.ui.Element.prototype.onDOMEvent = function ( event, callback ) {
1283 OO.ui.Element.onDOMEvent( this.$element, event, callback );
1284 };
1285
1286 /**
1287 * Unbind a handler bound with #offDOMEvent
1288 *
1289 * @deprecated Use jQuery#off instead.
1290 * @param {string} event
1291 * @param {Function} callback
1292 */
1293 OO.ui.Element.prototype.offDOMEvent = function ( event, callback ) {
1294 OO.ui.Element.offDOMEvent( this.$element, event, callback );
1295 };
1296
1297 /**
1298 * Container for elements.
1299 *
1300 * @abstract
1301 * @class
1302 * @extends OO.ui.Element
1303 * @mixins OO.EventEmitter
1304 *
1305 * @constructor
1306 * @param {Object} [config] Configuration options
1307 */
1308 OO.ui.Layout = function OoUiLayout( config ) {
1309 // Configuration initialization
1310 config = config || {};
1311
1312 // Parent constructor
1313 OO.ui.Layout.super.call( this, config );
1314
1315 // Mixin constructors
1316 OO.EventEmitter.call( this );
1317
1318 // Initialization
1319 this.$element.addClass( 'oo-ui-layout' );
1320 };
1321
1322 /* Setup */
1323
1324 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1325 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1326
1327 /**
1328 * User interface control.
1329 *
1330 * @abstract
1331 * @class
1332 * @extends OO.ui.Element
1333 * @mixins OO.EventEmitter
1334 *
1335 * @constructor
1336 * @param {Object} [config] Configuration options
1337 * @cfg {boolean} [disabled=false] Disable
1338 */
1339 OO.ui.Widget = function OoUiWidget( config ) {
1340 // Initialize config
1341 config = $.extend( { disabled: false }, config );
1342
1343 // Parent constructor
1344 OO.ui.Widget.super.call( this, config );
1345
1346 // Mixin constructors
1347 OO.EventEmitter.call( this );
1348
1349 // Properties
1350 this.visible = true;
1351 this.disabled = null;
1352 this.wasDisabled = null;
1353
1354 // Initialization
1355 this.$element.addClass( 'oo-ui-widget' );
1356 this.setDisabled( !!config.disabled );
1357 };
1358
1359 /* Setup */
1360
1361 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1362 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1363
1364 /* Events */
1365
1366 /**
1367 * @event disable
1368 * @param {boolean} disabled Widget is disabled
1369 */
1370
1371 /**
1372 * @event toggle
1373 * @param {boolean} visible Widget is visible
1374 */
1375
1376 /* Methods */
1377
1378 /**
1379 * Check if the widget is disabled.
1380 *
1381 * @return {boolean} Button is disabled
1382 */
1383 OO.ui.Widget.prototype.isDisabled = function () {
1384 return this.disabled;
1385 };
1386
1387 /**
1388 * Check if widget is visible.
1389 *
1390 * @return {boolean} Widget is visible
1391 */
1392 OO.ui.Widget.prototype.isVisible = function () {
1393 return this.visible;
1394 };
1395
1396 /**
1397 * Set the disabled state of the widget.
1398 *
1399 * This should probably change the widgets' appearance and prevent it from being used.
1400 *
1401 * @param {boolean} disabled Disable widget
1402 * @chainable
1403 */
1404 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1405 var isDisabled;
1406
1407 this.disabled = !!disabled;
1408 isDisabled = this.isDisabled();
1409 if ( isDisabled !== this.wasDisabled ) {
1410 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1411 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1412 this.emit( 'disable', isDisabled );
1413 this.updateThemeClasses();
1414 }
1415 this.wasDisabled = isDisabled;
1416
1417 return this;
1418 };
1419
1420 /**
1421 * Toggle visibility of widget.
1422 *
1423 * @param {boolean} [show] Make widget visible, omit to toggle visibility
1424 * @fires visible
1425 * @chainable
1426 */
1427 OO.ui.Widget.prototype.toggle = function ( show ) {
1428 show = show === undefined ? !this.visible : !!show;
1429
1430 if ( show !== this.isVisible() ) {
1431 this.visible = show;
1432 this.$element.toggle( show );
1433 this.emit( 'toggle', show );
1434 }
1435
1436 return this;
1437 };
1438
1439 /**
1440 * Update the disabled state, in case of changes in parent widget.
1441 *
1442 * @chainable
1443 */
1444 OO.ui.Widget.prototype.updateDisabled = function () {
1445 this.setDisabled( this.disabled );
1446 return this;
1447 };
1448
1449 /**
1450 * Container for elements in a child frame.
1451 *
1452 * Use together with OO.ui.WindowManager.
1453 *
1454 * @abstract
1455 * @class
1456 * @extends OO.ui.Element
1457 * @mixins OO.EventEmitter
1458 *
1459 * When a window is opened, the setup and ready processes are executed. Similarly, the hold and
1460 * teardown processes are executed when the window is closed.
1461 *
1462 * - {@link OO.ui.WindowManager#openWindow} or {@link #open} methods are used to start opening
1463 * - Window manager begins opening window
1464 * - {@link #getSetupProcess} method is called and its result executed
1465 * - {@link #getReadyProcess} method is called and its result executed
1466 * - Window is now open
1467 *
1468 * - {@link OO.ui.WindowManager#closeWindow} or {@link #close} methods are used to start closing
1469 * - Window manager begins closing window
1470 * - {@link #getHoldProcess} method is called and its result executed
1471 * - {@link #getTeardownProcess} method is called and its result executed
1472 * - Window is now closed
1473 *
1474 * Each process (setup, ready, hold and teardown) can be extended in subclasses by overriding
1475 * {@link #getSetupProcess}, {@link #getReadyProcess}, {@link #getHoldProcess} and
1476 * {@link #getTeardownProcess} respectively. Each process is executed in series, so asynchronous
1477 * processing can complete. Always assume window processes are executed asynchronously. See
1478 * OO.ui.Process for more details about how to work with processes. Some events, as well as the
1479 * #open and #close methods, provide promises which are resolved when the window enters a new state.
1480 *
1481 * Sizing of windows is specified using symbolic names which are interpreted by the window manager.
1482 * If the requested size is not recognized, the window manager will choose a sensible fallback.
1483 *
1484 * @constructor
1485 * @param {Object} [config] Configuration options
1486 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large` or `full`; omit to
1487 * use #static-size
1488 */
1489 OO.ui.Window = function OoUiWindow( config ) {
1490 // Configuration initialization
1491 config = config || {};
1492
1493 // Parent constructor
1494 OO.ui.Window.super.call( this, config );
1495
1496 // Mixin constructors
1497 OO.EventEmitter.call( this );
1498
1499 // Properties
1500 this.manager = null;
1501 this.initialized = false;
1502 this.visible = false;
1503 this.opening = null;
1504 this.closing = null;
1505 this.opened = null;
1506 this.timing = null;
1507 this.loading = null;
1508 this.size = config.size || this.constructor.static.size;
1509 this.$frame = this.$( '<div>' );
1510 this.$overlay = this.$( '<div>' );
1511
1512 // Initialization
1513 this.$element
1514 .addClass( 'oo-ui-window' )
1515 .append( this.$frame, this.$overlay );
1516 this.$frame.addClass( 'oo-ui-window-frame' );
1517 this.$overlay.addClass( 'oo-ui-window-overlay' );
1518
1519 // NOTE: Additional initialization will occur when #setManager is called
1520 };
1521
1522 /* Setup */
1523
1524 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1525 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1526
1527 /* Static Properties */
1528
1529 /**
1530 * Symbolic name of size.
1531 *
1532 * Size is used if no size is configured during construction.
1533 *
1534 * @static
1535 * @inheritable
1536 * @property {string}
1537 */
1538 OO.ui.Window.static.size = 'medium';
1539
1540 /* Static Methods */
1541
1542 /**
1543 * Transplant the CSS styles from as parent document to a frame's document.
1544 *
1545 * This loops over the style sheets in the parent document, and copies their nodes to the
1546 * frame's document. It then polls the document to see when all styles have loaded, and once they
1547 * have, resolves the promise.
1548 *
1549 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
1550 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
1551 * Firefox, where the styles won't load until the iframe becomes visible.
1552 *
1553 * For details of how we arrived at the strategy used in this function, see #load.
1554 *
1555 * @static
1556 * @inheritable
1557 * @param {HTMLDocument} parentDoc Document to transplant styles from
1558 * @param {HTMLDocument} frameDoc Document to transplant styles to
1559 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
1560 * @return {jQuery.Promise} Promise resolved when styles have loaded
1561 */
1562 OO.ui.Window.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
1563 var i, numSheets, styleNode, styleText, newNode, timeoutID, pollNodeId, $pendingPollNodes,
1564 $pollNodes = $( [] ),
1565 // Fake font-family value
1566 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
1567 nextIndex = parentDoc.oouiFrameTransplantStylesNextIndex || 0,
1568 deferred = $.Deferred();
1569
1570 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
1571 styleNode = parentDoc.styleSheets[i].ownerNode;
1572 if ( styleNode.disabled ) {
1573 continue;
1574 }
1575
1576 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
1577 // External stylesheet; use @import
1578 styleText = '@import url(' + styleNode.href + ');';
1579 } else {
1580 // Internal stylesheet; just copy the text
1581 // For IE10 we need to fall back to .cssText, BUT that's undefined in
1582 // other browsers, so fall back to '' rather than 'undefined'
1583 styleText = styleNode.textContent || parentDoc.styleSheets[i].cssText || '';
1584 }
1585
1586 // Create a node with a unique ID that we're going to monitor to see when the CSS
1587 // has loaded
1588 if ( styleNode.oouiFrameTransplantStylesId ) {
1589 // If we're nesting transplantStyles operations and this node already has
1590 // a CSS rule to wait for loading, reuse it
1591 pollNodeId = styleNode.oouiFrameTransplantStylesId;
1592 } else {
1593 // Otherwise, create a new ID
1594 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + nextIndex;
1595 nextIndex++;
1596
1597 // Add #pollNodeId { font-family: ... } to the end of the stylesheet / after the @import
1598 // The font-family rule will only take effect once the @import finishes
1599 styleText += '\n' + '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
1600 }
1601
1602 // Create a node with id=pollNodeId
1603 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
1604 .attr( 'id', pollNodeId )
1605 .appendTo( frameDoc.body )
1606 );
1607
1608 // Add our modified CSS as a <style> tag
1609 newNode = frameDoc.createElement( 'style' );
1610 newNode.textContent = styleText;
1611 newNode.oouiFrameTransplantStylesId = pollNodeId;
1612 frameDoc.head.appendChild( newNode );
1613 }
1614 frameDoc.oouiFrameTransplantStylesNextIndex = nextIndex;
1615
1616 // Poll every 100ms until all external stylesheets have loaded
1617 $pendingPollNodes = $pollNodes;
1618 timeoutID = setTimeout( function pollExternalStylesheets() {
1619 while (
1620 $pendingPollNodes.length > 0 &&
1621 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
1622 ) {
1623 $pendingPollNodes = $pendingPollNodes.slice( 1 );
1624 }
1625
1626 if ( $pendingPollNodes.length === 0 ) {
1627 // We're done!
1628 if ( timeoutID !== null ) {
1629 timeoutID = null;
1630 $pollNodes.remove();
1631 deferred.resolve();
1632 }
1633 } else {
1634 timeoutID = setTimeout( pollExternalStylesheets, 100 );
1635 }
1636 }, 100 );
1637 // ...but give up after a while
1638 if ( timeout !== 0 ) {
1639 setTimeout( function () {
1640 if ( timeoutID ) {
1641 clearTimeout( timeoutID );
1642 timeoutID = null;
1643 $pollNodes.remove();
1644 deferred.reject();
1645 }
1646 }, timeout || 5000 );
1647 }
1648
1649 return deferred.promise();
1650 };
1651
1652 /* Methods */
1653
1654 /**
1655 * Handle mouse down events.
1656 *
1657 * @param {jQuery.Event} e Mouse down event
1658 */
1659 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1660 // Prevent clicking on the click-block from stealing focus
1661 if ( e.target === this.$element[0] ) {
1662 return false;
1663 }
1664 };
1665
1666 /**
1667 * Check if window has been initialized.
1668 *
1669 * @return {boolean} Window has been initialized
1670 */
1671 OO.ui.Window.prototype.isInitialized = function () {
1672 return this.initialized;
1673 };
1674
1675 /**
1676 * Check if window is visible.
1677 *
1678 * @return {boolean} Window is visible
1679 */
1680 OO.ui.Window.prototype.isVisible = function () {
1681 return this.visible;
1682 };
1683
1684 /**
1685 * Check if window is loading.
1686 *
1687 * @return {boolean} Window is loading
1688 */
1689 OO.ui.Window.prototype.isLoading = function () {
1690 return this.loading && this.loading.state() === 'pending';
1691 };
1692
1693 /**
1694 * Check if window is loaded.
1695 *
1696 * @return {boolean} Window is loaded
1697 */
1698 OO.ui.Window.prototype.isLoaded = function () {
1699 return this.loading && this.loading.state() === 'resolved';
1700 };
1701
1702 /**
1703 * Check if window is opening.
1704 *
1705 * This is a wrapper around OO.ui.WindowManager#isOpening.
1706 *
1707 * @return {boolean} Window is opening
1708 */
1709 OO.ui.Window.prototype.isOpening = function () {
1710 return this.manager.isOpening( this );
1711 };
1712
1713 /**
1714 * Check if window is closing.
1715 *
1716 * This is a wrapper around OO.ui.WindowManager#isClosing.
1717 *
1718 * @return {boolean} Window is closing
1719 */
1720 OO.ui.Window.prototype.isClosing = function () {
1721 return this.manager.isClosing( this );
1722 };
1723
1724 /**
1725 * Check if window is opened.
1726 *
1727 * This is a wrapper around OO.ui.WindowManager#isOpened.
1728 *
1729 * @return {boolean} Window is opened
1730 */
1731 OO.ui.Window.prototype.isOpened = function () {
1732 return this.manager.isOpened( this );
1733 };
1734
1735 /**
1736 * Get the window manager.
1737 *
1738 * @return {OO.ui.WindowManager} Manager of window
1739 */
1740 OO.ui.Window.prototype.getManager = function () {
1741 return this.manager;
1742 };
1743
1744 /**
1745 * Get the window size.
1746 *
1747 * @return {string} Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1748 */
1749 OO.ui.Window.prototype.getSize = function () {
1750 return this.size;
1751 };
1752
1753 /**
1754 * Disable transitions on window's frame for the duration of the callback function, then enable them
1755 * back.
1756 *
1757 * @private
1758 * @param {Function} callback Function to call while transitions are disabled
1759 */
1760 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1761 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1762 // Disable transitions first, otherwise we'll get values from when the window was animating.
1763 var oldTransition,
1764 styleObj = this.$frame[0].style;
1765 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1766 styleObj.MozTransition || styleObj.WebkitTransition;
1767 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1768 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1769 callback();
1770 // Force reflow to make sure the style changes done inside callback really are not transitioned
1771 this.$frame.height();
1772 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1773 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1774 };
1775
1776 /**
1777 * Get the height of the dialog contents.
1778 *
1779 * @return {number} Content height
1780 */
1781 OO.ui.Window.prototype.getContentHeight = function () {
1782 var bodyHeight,
1783 win = this,
1784 styleObj = this.$frame[0].style;
1785
1786 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1787 // Disable transitions first, otherwise we'll get values from when the window was animating.
1788 this.withoutSizeTransitions( function () {
1789 var oldHeight = styleObj.height;
1790 styleObj.height = '1px';
1791 bodyHeight = win.getBodyHeight();
1792 styleObj.height = oldHeight;
1793 } );
1794
1795 return Math.round(
1796 // Add buffer for border
1797 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1798 // Use combined heights of children
1799 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1800 );
1801 };
1802
1803 /**
1804 * Get the height of the dialog contents.
1805 *
1806 * When this function is called, the dialog will temporarily have been resized
1807 * to height=1px, so .scrollHeight measurements can be taken accurately.
1808 *
1809 * @return {number} Height of content
1810 */
1811 OO.ui.Window.prototype.getBodyHeight = function () {
1812 return this.$body[0].scrollHeight;
1813 };
1814
1815 /**
1816 * Get the directionality of the frame
1817 *
1818 * @return {string} Directionality, 'ltr' or 'rtl'
1819 */
1820 OO.ui.Window.prototype.getDir = function () {
1821 return this.dir;
1822 };
1823
1824 /**
1825 * Get a process for setting up a window for use.
1826 *
1827 * Each time the window is opened this process will set it up for use in a particular context, based
1828 * on the `data` argument.
1829 *
1830 * When you override this method, you can add additional setup steps to the process the parent
1831 * method provides using the 'first' and 'next' methods.
1832 *
1833 * @abstract
1834 * @param {Object} [data] Window opening data
1835 * @return {OO.ui.Process} Setup process
1836 */
1837 OO.ui.Window.prototype.getSetupProcess = function () {
1838 return new OO.ui.Process();
1839 };
1840
1841 /**
1842 * Get a process for readying a window for use.
1843 *
1844 * Each time the window is open and setup, this process will ready it up for use in a particular
1845 * context, based on the `data` argument.
1846 *
1847 * When you override this method, you can add additional setup steps to the process the parent
1848 * method provides using the 'first' and 'next' methods.
1849 *
1850 * @abstract
1851 * @param {Object} [data] Window opening data
1852 * @return {OO.ui.Process} Setup process
1853 */
1854 OO.ui.Window.prototype.getReadyProcess = function () {
1855 return new OO.ui.Process();
1856 };
1857
1858 /**
1859 * Get a process for holding a window from use.
1860 *
1861 * Each time the window is closed, this process will hold it from use in a particular context, based
1862 * on the `data` argument.
1863 *
1864 * When you override this method, you can add additional setup steps to the process the parent
1865 * method provides using the 'first' and 'next' methods.
1866 *
1867 * @abstract
1868 * @param {Object} [data] Window closing data
1869 * @return {OO.ui.Process} Hold process
1870 */
1871 OO.ui.Window.prototype.getHoldProcess = function () {
1872 return new OO.ui.Process();
1873 };
1874
1875 /**
1876 * Get a process for tearing down a window after use.
1877 *
1878 * Each time the window is closed this process will tear it down and do something with the user's
1879 * interactions within the window, based on the `data` argument.
1880 *
1881 * When you override this method, you can add additional teardown steps to the process the parent
1882 * method provides using the 'first' and 'next' methods.
1883 *
1884 * @abstract
1885 * @param {Object} [data] Window closing data
1886 * @return {OO.ui.Process} Teardown process
1887 */
1888 OO.ui.Window.prototype.getTeardownProcess = function () {
1889 return new OO.ui.Process();
1890 };
1891
1892 /**
1893 * Toggle visibility of window.
1894 *
1895 * If the window is isolated and hasn't fully loaded yet, the visibility property will be used
1896 * instead of display.
1897 *
1898 * @param {boolean} [show] Make window visible, omit to toggle visibility
1899 * @fires toggle
1900 * @chainable
1901 */
1902 OO.ui.Window.prototype.toggle = function ( show ) {
1903 show = show === undefined ? !this.visible : !!show;
1904
1905 if ( show !== this.isVisible() ) {
1906 this.visible = show;
1907
1908 if ( this.isolated && !this.isLoaded() ) {
1909 // Hide the window using visibility instead of display until loading is complete
1910 // Can't use display: none; because that prevents the iframe from loading in Firefox
1911 this.$element.css( 'visibility', show ? 'visible' : 'hidden' );
1912 } else {
1913 this.$element.toggle( show ).css( 'visibility', '' );
1914 }
1915 this.emit( 'toggle', show );
1916 }
1917
1918 return this;
1919 };
1920
1921 /**
1922 * Set the window manager.
1923 *
1924 * This must be called before initialize. Calling it more than once will cause an error.
1925 *
1926 * @param {OO.ui.WindowManager} manager Manager for this window
1927 * @throws {Error} If called more than once
1928 * @chainable
1929 */
1930 OO.ui.Window.prototype.setManager = function ( manager ) {
1931 if ( this.manager ) {
1932 throw new Error( 'Cannot set window manager, window already has a manager' );
1933 }
1934
1935 // Properties
1936 this.manager = manager;
1937 this.isolated = manager.shouldIsolate();
1938
1939 // Initialization
1940 if ( this.isolated ) {
1941 this.$iframe = this.$( '<iframe>' );
1942 this.$iframe.attr( { frameborder: 0, scrolling: 'no' } );
1943 this.$frame.append( this.$iframe );
1944 this.$ = function () {
1945 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
1946 };
1947 // WARNING: Do not use this.$ again until #initialize is called
1948 } else {
1949 this.$content = this.$( '<div>' );
1950 this.$document = $( this.getElementDocument() );
1951 this.$content.addClass( 'oo-ui-window-content' );
1952 this.$frame.append( this.$content );
1953 }
1954 this.toggle( false );
1955
1956 // Figure out directionality:
1957 this.dir = OO.ui.Element.getDir( this.$iframe || this.$content ) || 'ltr';
1958
1959 return this;
1960 };
1961
1962 /**
1963 * Set the window size.
1964 *
1965 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1966 * @chainable
1967 */
1968 OO.ui.Window.prototype.setSize = function ( size ) {
1969 this.size = size;
1970 this.manager.updateWindowSize( this );
1971 return this;
1972 };
1973
1974 /**
1975 * Set window dimensions.
1976 *
1977 * Properties are applied to the frame container.
1978 *
1979 * @param {Object} dim CSS dimension properties
1980 * @param {string|number} [dim.width] Width
1981 * @param {string|number} [dim.minWidth] Minimum width
1982 * @param {string|number} [dim.maxWidth] Maximum width
1983 * @param {string|number} [dim.width] Height, omit to set based on height of contents
1984 * @param {string|number} [dim.minWidth] Minimum height
1985 * @param {string|number} [dim.maxWidth] Maximum height
1986 * @chainable
1987 */
1988 OO.ui.Window.prototype.setDimensions = function ( dim ) {
1989 var height,
1990 win = this,
1991 styleObj = this.$frame[0].style;
1992
1993 // Calculate the height we need to set using the correct width
1994 if ( dim.height === undefined ) {
1995 this.withoutSizeTransitions( function () {
1996 var oldWidth = styleObj.width;
1997 win.$frame.css( 'width', dim.width || '' );
1998 height = win.getContentHeight();
1999 styleObj.width = oldWidth;
2000 } );
2001 } else {
2002 height = dim.height;
2003 }
2004
2005 this.$frame.css( {
2006 width: dim.width || '',
2007 minWidth: dim.minWidth || '',
2008 maxWidth: dim.maxWidth || '',
2009 height: height || '',
2010 minHeight: dim.minHeight || '',
2011 maxHeight: dim.maxHeight || ''
2012 } );
2013
2014 return this;
2015 };
2016
2017 /**
2018 * Initialize window contents.
2019 *
2020 * The first time the window is opened, #initialize is called when it's safe to begin populating
2021 * its contents. See #getSetupProcess for a way to make changes each time the window opens.
2022 *
2023 * Once this method is called, this.$ can be used to create elements within the frame.
2024 *
2025 * @throws {Error} If not attached to a manager
2026 * @chainable
2027 */
2028 OO.ui.Window.prototype.initialize = function () {
2029 if ( !this.manager ) {
2030 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2031 }
2032
2033 // Properties
2034 this.$head = this.$( '<div>' );
2035 this.$body = this.$( '<div>' );
2036 this.$foot = this.$( '<div>' );
2037 this.$innerOverlay = this.$( '<div>' );
2038
2039 // Events
2040 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2041
2042 // Initialization
2043 this.$head.addClass( 'oo-ui-window-head' );
2044 this.$body.addClass( 'oo-ui-window-body' );
2045 this.$foot.addClass( 'oo-ui-window-foot' );
2046 this.$innerOverlay.addClass( 'oo-ui-window-inner-overlay' );
2047 this.$content.append( this.$head, this.$body, this.$foot, this.$innerOverlay );
2048
2049 return this;
2050 };
2051
2052 /**
2053 * Open window.
2054 *
2055 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
2056 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
2057 *
2058 * @param {Object} [data] Window opening data
2059 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
2060 * first argument will be a promise which will be resolved when the window begins closing
2061 */
2062 OO.ui.Window.prototype.open = function ( data ) {
2063 return this.manager.openWindow( this, data );
2064 };
2065
2066 /**
2067 * Close window.
2068 *
2069 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
2070 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
2071 *
2072 * @param {Object} [data] Window closing data
2073 * @return {jQuery.Promise} Promise resolved when window is closed
2074 */
2075 OO.ui.Window.prototype.close = function ( data ) {
2076 return this.manager.closeWindow( this, data );
2077 };
2078
2079 /**
2080 * Setup window.
2081 *
2082 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2083 * by other systems.
2084 *
2085 * @param {Object} [data] Window opening data
2086 * @return {jQuery.Promise} Promise resolved when window is setup
2087 */
2088 OO.ui.Window.prototype.setup = function ( data ) {
2089 var win = this,
2090 deferred = $.Deferred();
2091
2092 this.$element.show();
2093 this.visible = true;
2094 this.getSetupProcess( data ).execute().done( function () {
2095 // Force redraw by asking the browser to measure the elements' widths
2096 win.$element.addClass( 'oo-ui-window-setup' ).width();
2097 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2098 deferred.resolve();
2099 } );
2100
2101 return deferred.promise();
2102 };
2103
2104 /**
2105 * Ready window.
2106 *
2107 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2108 * by other systems.
2109 *
2110 * @param {Object} [data] Window opening data
2111 * @return {jQuery.Promise} Promise resolved when window is ready
2112 */
2113 OO.ui.Window.prototype.ready = function ( data ) {
2114 var win = this,
2115 deferred = $.Deferred();
2116
2117 this.$content.focus();
2118 this.getReadyProcess( data ).execute().done( function () {
2119 // Force redraw by asking the browser to measure the elements' widths
2120 win.$element.addClass( 'oo-ui-window-ready' ).width();
2121 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2122 deferred.resolve();
2123 } );
2124
2125 return deferred.promise();
2126 };
2127
2128 /**
2129 * Hold window.
2130 *
2131 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2132 * by other systems.
2133 *
2134 * @param {Object} [data] Window closing data
2135 * @return {jQuery.Promise} Promise resolved when window is held
2136 */
2137 OO.ui.Window.prototype.hold = function ( data ) {
2138 var win = this,
2139 deferred = $.Deferred();
2140
2141 this.getHoldProcess( data ).execute().done( function () {
2142 // Get the focused element within the window's content
2143 var $focus = win.$content.find( OO.ui.Element.getDocument( win.$content ).activeElement );
2144
2145 // Blur the focused element
2146 if ( $focus.length ) {
2147 $focus[0].blur();
2148 }
2149
2150 // Force redraw by asking the browser to measure the elements' widths
2151 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2152 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2153 deferred.resolve();
2154 } );
2155
2156 return deferred.promise();
2157 };
2158
2159 /**
2160 * Teardown window.
2161 *
2162 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2163 * by other systems.
2164 *
2165 * @param {Object} [data] Window closing data
2166 * @return {jQuery.Promise} Promise resolved when window is torn down
2167 */
2168 OO.ui.Window.prototype.teardown = function ( data ) {
2169 var win = this,
2170 deferred = $.Deferred();
2171
2172 this.getTeardownProcess( data ).execute().done( function () {
2173 // Force redraw by asking the browser to measure the elements' widths
2174 win.$element.removeClass( 'oo-ui-window-load oo-ui-window-setup' ).width();
2175 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2176 win.$element.hide();
2177 win.visible = false;
2178 deferred.resolve();
2179 } );
2180
2181 return deferred.promise();
2182 };
2183
2184 /**
2185 * Load the frame contents.
2186 *
2187 * Once the iframe's stylesheets are loaded the returned promise will be resolved. Calling while
2188 * loading will return a promise but not trigger a new loading cycle. Calling after loading is
2189 * complete will return a promise that's already been resolved.
2190 *
2191 * Sounds simple right? Read on...
2192 *
2193 * When you create a dynamic iframe using open/write/close, the window.load event for the
2194 * iframe is triggered when you call close, and there's no further load event to indicate that
2195 * everything is actually loaded.
2196 *
2197 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
2198 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
2199 * are added to document.styleSheets immediately, and the only way you can determine whether they've
2200 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
2201 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
2202 *
2203 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>`
2204 * tags. Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets
2205 * until the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the
2206 * `@import` has finished. And because the contents of the `<style>` tag are from the same origin,
2207 * accessing .cssRules is allowed.
2208 *
2209 * However, now that we control the styles we're injecting, we might as well do away with
2210 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
2211 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
2212 * and wait for its font-family to change to someValue. Because `@import` is blocking, the
2213 * font-family rule is not applied until after the `@import` finishes.
2214 *
2215 * All this stylesheet injection and polling magic is in #transplantStyles.
2216 *
2217 * @return {jQuery.Promise} Promise resolved when loading is complete
2218 */
2219 OO.ui.Window.prototype.load = function () {
2220 var sub, doc, loading,
2221 win = this;
2222
2223 this.$element.addClass( 'oo-ui-window-load' );
2224
2225 // Non-isolated windows are already "loaded"
2226 if ( !this.loading && !this.isolated ) {
2227 this.loading = $.Deferred().resolve();
2228 this.initialize();
2229 // Set initialized state after so sub-classes aren't confused by it being set by calling
2230 // their parent initialize method
2231 this.initialized = true;
2232 }
2233
2234 // Return existing promise if already loading or loaded
2235 if ( this.loading ) {
2236 return this.loading.promise();
2237 }
2238
2239 // Load the frame
2240 loading = this.loading = $.Deferred();
2241 sub = this.$iframe.prop( 'contentWindow' );
2242 doc = sub.document;
2243
2244 // Initialize contents
2245 doc.open();
2246 doc.write(
2247 '<!doctype html>' +
2248 '<html>' +
2249 '<body class="oo-ui-window-isolated oo-ui-' + this.dir + '"' +
2250 ' style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
2251 '<div class="oo-ui-window-content"></div>' +
2252 '</body>' +
2253 '</html>'
2254 );
2255 doc.close();
2256
2257 // Properties
2258 this.$ = OO.ui.Element.getJQuery( doc, this.$iframe );
2259 this.$content = this.$( '.oo-ui-window-content' ).attr( 'tabIndex', 0 );
2260 this.$document = this.$( doc );
2261
2262 // Initialization
2263 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[0] )
2264 .always( function () {
2265 // Initialize isolated windows
2266 win.initialize();
2267 // Set initialized state after so sub-classes aren't confused by it being set by calling
2268 // their parent initialize method
2269 win.initialized = true;
2270 // Undo the visibility: hidden; hack and apply display: none;
2271 // We can do this safely now that the iframe has initialized
2272 // (don't do this from within #initialize because it has to happen
2273 // after the all subclasses have been handled as well).
2274 win.toggle( win.isVisible() );
2275
2276 loading.resolve();
2277 } );
2278
2279 return loading.promise();
2280 };
2281
2282 /**
2283 * Base class for all dialogs.
2284 *
2285 * Logic:
2286 * - Manage the window (open and close, etc.).
2287 * - Store the internal name and display title.
2288 * - A stack to track one or more pending actions.
2289 * - Manage a set of actions that can be performed.
2290 * - Configure and create action widgets.
2291 *
2292 * User interface:
2293 * - Close the dialog with Escape key.
2294 * - Visually lock the dialog while an action is in
2295 * progress (aka "pending").
2296 *
2297 * Subclass responsibilities:
2298 * - Display the title somewhere.
2299 * - Add content to the dialog.
2300 * - Provide a UI to close the dialog.
2301 * - Display the action widgets somewhere.
2302 *
2303 * @abstract
2304 * @class
2305 * @extends OO.ui.Window
2306 * @mixins OO.ui.PendingElement
2307 *
2308 * @constructor
2309 * @param {Object} [config] Configuration options
2310 */
2311 OO.ui.Dialog = function OoUiDialog( config ) {
2312 // Parent constructor
2313 OO.ui.Dialog.super.call( this, config );
2314
2315 // Mixin constructors
2316 OO.ui.PendingElement.call( this );
2317
2318 // Properties
2319 this.actions = new OO.ui.ActionSet();
2320 this.attachedActions = [];
2321 this.currentAction = null;
2322 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2323
2324 // Events
2325 this.actions.connect( this, {
2326 click: 'onActionClick',
2327 resize: 'onActionResize',
2328 change: 'onActionsChange'
2329 } );
2330
2331 // Initialization
2332 this.$element
2333 .addClass( 'oo-ui-dialog' )
2334 .attr( 'role', 'dialog' );
2335 };
2336
2337 /* Setup */
2338
2339 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2340 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2341
2342 /* Static Properties */
2343
2344 /**
2345 * Symbolic name of dialog.
2346 *
2347 * @abstract
2348 * @static
2349 * @inheritable
2350 * @property {string}
2351 */
2352 OO.ui.Dialog.static.name = '';
2353
2354 /**
2355 * Dialog title.
2356 *
2357 * @abstract
2358 * @static
2359 * @inheritable
2360 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2361 */
2362 OO.ui.Dialog.static.title = '';
2363
2364 /**
2365 * List of OO.ui.ActionWidget configuration options.
2366 *
2367 * @static
2368 * inheritable
2369 * @property {Object[]}
2370 */
2371 OO.ui.Dialog.static.actions = [];
2372
2373 /**
2374 * Close dialog when the escape key is pressed.
2375 *
2376 * @static
2377 * @abstract
2378 * @inheritable
2379 * @property {boolean}
2380 */
2381 OO.ui.Dialog.static.escapable = true;
2382
2383 /* Methods */
2384
2385 /**
2386 * Handle frame document key down events.
2387 *
2388 * @param {jQuery.Event} e Key down event
2389 */
2390 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2391 if ( e.which === OO.ui.Keys.ESCAPE ) {
2392 this.close();
2393 return false;
2394 }
2395 };
2396
2397 /**
2398 * Handle action resized events.
2399 *
2400 * @param {OO.ui.ActionWidget} action Action that was resized
2401 */
2402 OO.ui.Dialog.prototype.onActionResize = function () {
2403 // Override in subclass
2404 };
2405
2406 /**
2407 * Handle action click events.
2408 *
2409 * @param {OO.ui.ActionWidget} action Action that was clicked
2410 */
2411 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2412 if ( !this.isPending() ) {
2413 this.currentAction = action;
2414 this.executeAction( action.getAction() );
2415 }
2416 };
2417
2418 /**
2419 * Handle actions change event.
2420 */
2421 OO.ui.Dialog.prototype.onActionsChange = function () {
2422 this.detachActions();
2423 if ( !this.isClosing() ) {
2424 this.attachActions();
2425 }
2426 };
2427
2428 /**
2429 * Get set of actions.
2430 *
2431 * @return {OO.ui.ActionSet}
2432 */
2433 OO.ui.Dialog.prototype.getActions = function () {
2434 return this.actions;
2435 };
2436
2437 /**
2438 * Get a process for taking action.
2439 *
2440 * When you override this method, you can add additional accept steps to the process the parent
2441 * method provides using the 'first' and 'next' methods.
2442 *
2443 * @abstract
2444 * @param {string} [action] Symbolic name of action
2445 * @return {OO.ui.Process} Action process
2446 */
2447 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2448 return new OO.ui.Process()
2449 .next( function () {
2450 if ( !action ) {
2451 // An empty action always closes the dialog without data, which should always be
2452 // safe and make no changes
2453 this.close();
2454 }
2455 }, this );
2456 };
2457
2458 /**
2459 * @inheritdoc
2460 *
2461 * @param {Object} [data] Dialog opening data
2462 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use #static-title
2463 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2464 * action item, omit to use #static-actions
2465 */
2466 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2467 data = data || {};
2468
2469 // Parent method
2470 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2471 .next( function () {
2472 var i, len,
2473 items = [],
2474 config = this.constructor.static,
2475 actions = data.actions !== undefined ? data.actions : config.actions;
2476
2477 this.title.setLabel(
2478 data.title !== undefined ? data.title : this.constructor.static.title
2479 );
2480 for ( i = 0, len = actions.length; i < len; i++ ) {
2481 items.push(
2482 new OO.ui.ActionWidget( $.extend( { $: this.$ }, actions[i] ) )
2483 );
2484 }
2485 this.actions.add( items );
2486
2487 if ( this.constructor.static.escapable ) {
2488 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2489 }
2490 }, this );
2491 };
2492
2493 /**
2494 * @inheritdoc
2495 */
2496 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2497 // Parent method
2498 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2499 .first( function () {
2500 if ( this.constructor.static.escapable ) {
2501 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2502 }
2503
2504 this.actions.clear();
2505 this.currentAction = null;
2506 }, this );
2507 };
2508
2509 /**
2510 * @inheritdoc
2511 */
2512 OO.ui.Dialog.prototype.initialize = function () {
2513 // Parent method
2514 OO.ui.Dialog.super.prototype.initialize.call( this );
2515
2516 // Properties
2517 this.title = new OO.ui.LabelWidget( { $: this.$ } );
2518
2519 // Initialization
2520 this.$content.addClass( 'oo-ui-dialog-content' );
2521 this.setPendingElement( this.$head );
2522 };
2523
2524 /**
2525 * Attach action actions.
2526 */
2527 OO.ui.Dialog.prototype.attachActions = function () {
2528 // Remember the list of potentially attached actions
2529 this.attachedActions = this.actions.get();
2530 };
2531
2532 /**
2533 * Detach action actions.
2534 *
2535 * @chainable
2536 */
2537 OO.ui.Dialog.prototype.detachActions = function () {
2538 var i, len;
2539
2540 // Detach all actions that may have been previously attached
2541 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2542 this.attachedActions[i].$element.detach();
2543 }
2544 this.attachedActions = [];
2545 };
2546
2547 /**
2548 * Execute an action.
2549 *
2550 * @param {string} action Symbolic name of action to execute
2551 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2552 */
2553 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2554 this.pushPending();
2555 return this.getActionProcess( action ).execute()
2556 .always( this.popPending.bind( this ) );
2557 };
2558
2559 /**
2560 * Collection of windows.
2561 *
2562 * @class
2563 * @extends OO.ui.Element
2564 * @mixins OO.EventEmitter
2565 *
2566 * Managed windows are mutually exclusive. If a window is opened while there is a current window
2567 * already opening or opened, the current window will be closed without data. Empty closing data
2568 * should always result in the window being closed without causing constructive or destructive
2569 * action.
2570 *
2571 * As a window is opened and closed, it passes through several stages and the manager emits several
2572 * corresponding events.
2573 *
2574 * - {@link #openWindow} or {@link OO.ui.Window#open} methods are used to start opening
2575 * - {@link #event-opening} is emitted with `opening` promise
2576 * - {@link #getSetupDelay} is called the returned value is used to time a pause in execution
2577 * - {@link OO.ui.Window#getSetupProcess} method is called on the window and its result executed
2578 * - `setup` progress notification is emitted from opening promise
2579 * - {@link #getReadyDelay} is called the returned value is used to time a pause in execution
2580 * - {@link OO.ui.Window#getReadyProcess} method is called on the window and its result executed
2581 * - `ready` progress notification is emitted from opening promise
2582 * - `opening` promise is resolved with `opened` promise
2583 * - Window is now open
2584 *
2585 * - {@link #closeWindow} or {@link OO.ui.Window#close} methods are used to start closing
2586 * - `opened` promise is resolved with `closing` promise
2587 * - {@link #event-closing} is emitted with `closing` promise
2588 * - {@link #getHoldDelay} is called the returned value is used to time a pause in execution
2589 * - {@link OO.ui.Window#getHoldProcess} method is called on the window and its result executed
2590 * - `hold` progress notification is emitted from opening promise
2591 * - {@link #getTeardownDelay} is called the returned value is used to time a pause in execution
2592 * - {@link OO.ui.Window#getTeardownProcess} method is called on the window and its result executed
2593 * - `teardown` progress notification is emitted from opening promise
2594 * - Closing promise is resolved
2595 * - Window is now closed
2596 *
2597 * @constructor
2598 * @param {Object} [config] Configuration options
2599 * @cfg {boolean} [isolate] Configure managed windows to isolate their content using inline frames
2600 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2601 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2602 */
2603 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2604 // Configuration initialization
2605 config = config || {};
2606
2607 // Parent constructor
2608 OO.ui.WindowManager.super.call( this, config );
2609
2610 // Mixin constructors
2611 OO.EventEmitter.call( this );
2612
2613 // Properties
2614 this.factory = config.factory;
2615 this.modal = config.modal === undefined || !!config.modal;
2616 this.isolate = !!config.isolate;
2617 this.windows = {};
2618 this.opening = null;
2619 this.opened = null;
2620 this.closing = null;
2621 this.preparingToOpen = null;
2622 this.preparingToClose = null;
2623 this.size = null;
2624 this.currentWindow = null;
2625 this.$ariaHidden = null;
2626 this.requestedSize = null;
2627 this.onWindowResizeTimeout = null;
2628 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2629 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2630 this.onWindowMouseWheelHandler = this.onWindowMouseWheel.bind( this );
2631 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2632
2633 // Initialization
2634 this.$element
2635 .addClass( 'oo-ui-windowManager' )
2636 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2637 };
2638
2639 /* Setup */
2640
2641 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2642 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2643
2644 /* Events */
2645
2646 /**
2647 * Window is opening.
2648 *
2649 * Fired when the window begins to be opened.
2650 *
2651 * @event opening
2652 * @param {OO.ui.Window} win Window that's being opened
2653 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2654 * resolved the first argument will be a promise which will be resolved when the window begins
2655 * closing, the second argument will be the opening data; progress notifications will be fired on
2656 * the promise for `setup` and `ready` when those processes are completed respectively.
2657 * @param {Object} data Window opening data
2658 */
2659
2660 /**
2661 * Window is closing.
2662 *
2663 * Fired when the window begins to be closed.
2664 *
2665 * @event closing
2666 * @param {OO.ui.Window} win Window that's being closed
2667 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2668 * is resolved the first argument will be a the closing data; progress notifications will be fired
2669 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2670 * @param {Object} data Window closing data
2671 */
2672
2673 /**
2674 * Window was resized.
2675 *
2676 * @event resize
2677 * @param {OO.ui.Window} win Window that was resized
2678 */
2679
2680 /* Static Properties */
2681
2682 /**
2683 * Map of symbolic size names and CSS properties.
2684 *
2685 * @static
2686 * @inheritable
2687 * @property {Object}
2688 */
2689 OO.ui.WindowManager.static.sizes = {
2690 small: {
2691 width: 300
2692 },
2693 medium: {
2694 width: 500
2695 },
2696 large: {
2697 width: 700
2698 },
2699 full: {
2700 // These can be non-numeric because they are never used in calculations
2701 width: '100%',
2702 height: '100%'
2703 }
2704 };
2705
2706 /**
2707 * Symbolic name of default size.
2708 *
2709 * Default size is used if the window's requested size is not recognized.
2710 *
2711 * @static
2712 * @inheritable
2713 * @property {string}
2714 */
2715 OO.ui.WindowManager.static.defaultSize = 'medium';
2716
2717 /* Methods */
2718
2719 /**
2720 * Handle window resize events.
2721 *
2722 * @param {jQuery.Event} e Window resize event
2723 */
2724 OO.ui.WindowManager.prototype.onWindowResize = function () {
2725 clearTimeout( this.onWindowResizeTimeout );
2726 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2727 };
2728
2729 /**
2730 * Handle window resize events.
2731 *
2732 * @param {jQuery.Event} e Window resize event
2733 */
2734 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2735 if ( this.currentWindow ) {
2736 this.updateWindowSize( this.currentWindow );
2737 }
2738 };
2739
2740 /**
2741 * Handle window mouse wheel events.
2742 *
2743 * @param {jQuery.Event} e Mouse wheel event
2744 */
2745 OO.ui.WindowManager.prototype.onWindowMouseWheel = function ( e ) {
2746 // Kill all events in the parent window if the child window is isolated,
2747 // or if the event didn't come from the child window
2748 return !( this.shouldIsolate() || !$.contains( this.getCurrentWindow().$frame[0], e.target ) );
2749 };
2750
2751 /**
2752 * Handle document key down events.
2753 *
2754 * @param {jQuery.Event} e Key down event
2755 */
2756 OO.ui.WindowManager.prototype.onDocumentKeyDown = function ( e ) {
2757 switch ( e.which ) {
2758 case OO.ui.Keys.PAGEUP:
2759 case OO.ui.Keys.PAGEDOWN:
2760 case OO.ui.Keys.END:
2761 case OO.ui.Keys.HOME:
2762 case OO.ui.Keys.LEFT:
2763 case OO.ui.Keys.UP:
2764 case OO.ui.Keys.RIGHT:
2765 case OO.ui.Keys.DOWN:
2766 // Kill all events in the parent window if the child window is isolated,
2767 // or if the event didn't come from the child window
2768 return !( this.shouldIsolate() || !$.contains( this.getCurrentWindow().$frame[0], e.target ) );
2769 }
2770 };
2771
2772 /**
2773 * Check if window is opening.
2774 *
2775 * @return {boolean} Window is opening
2776 */
2777 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2778 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2779 };
2780
2781 /**
2782 * Check if window is closing.
2783 *
2784 * @return {boolean} Window is closing
2785 */
2786 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2787 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2788 };
2789
2790 /**
2791 * Check if window is opened.
2792 *
2793 * @return {boolean} Window is opened
2794 */
2795 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2796 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2797 };
2798
2799 /**
2800 * Check if window contents should be isolated.
2801 *
2802 * Window content isolation is done using inline frames.
2803 *
2804 * @return {boolean} Window contents should be isolated
2805 */
2806 OO.ui.WindowManager.prototype.shouldIsolate = function () {
2807 return this.isolate;
2808 };
2809
2810 /**
2811 * Check if a window is being managed.
2812 *
2813 * @param {OO.ui.Window} win Window to check
2814 * @return {boolean} Window is being managed
2815 */
2816 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2817 var name;
2818
2819 for ( name in this.windows ) {
2820 if ( this.windows[name] === win ) {
2821 return true;
2822 }
2823 }
2824
2825 return false;
2826 };
2827
2828 /**
2829 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2830 *
2831 * @param {OO.ui.Window} win Window being opened
2832 * @param {Object} [data] Window opening data
2833 * @return {number} Milliseconds to wait
2834 */
2835 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2836 return 0;
2837 };
2838
2839 /**
2840 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2841 *
2842 * @param {OO.ui.Window} win Window being opened
2843 * @param {Object} [data] Window opening data
2844 * @return {number} Milliseconds to wait
2845 */
2846 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2847 return 0;
2848 };
2849
2850 /**
2851 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2852 *
2853 * @param {OO.ui.Window} win Window being closed
2854 * @param {Object} [data] Window closing data
2855 * @return {number} Milliseconds to wait
2856 */
2857 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2858 return 0;
2859 };
2860
2861 /**
2862 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2863 *
2864 * @param {OO.ui.Window} win Window being closed
2865 * @param {Object} [data] Window closing data
2866 * @return {number} Milliseconds to wait
2867 */
2868 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2869 return this.modal ? 250 : 0;
2870 };
2871
2872 /**
2873 * Get managed window by symbolic name.
2874 *
2875 * If window is not yet instantiated, it will be instantiated and added automatically.
2876 *
2877 * @param {string} name Symbolic window name
2878 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2879 * @throws {Error} If the symbolic name is unrecognized by the factory
2880 * @throws {Error} If the symbolic name unrecognized as a managed window
2881 */
2882 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2883 var deferred = $.Deferred(),
2884 win = this.windows[name];
2885
2886 if ( !( win instanceof OO.ui.Window ) ) {
2887 if ( this.factory ) {
2888 if ( !this.factory.lookup( name ) ) {
2889 deferred.reject( new OO.ui.Error(
2890 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2891 ) );
2892 } else {
2893 win = this.factory.create( name, this, { $: this.$ } );
2894 this.addWindows( [ win ] );
2895 deferred.resolve( win );
2896 }
2897 } else {
2898 deferred.reject( new OO.ui.Error(
2899 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2900 ) );
2901 }
2902 } else {
2903 deferred.resolve( win );
2904 }
2905
2906 return deferred.promise();
2907 };
2908
2909 /**
2910 * Get current window.
2911 *
2912 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2913 */
2914 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2915 return this.currentWindow;
2916 };
2917
2918 /**
2919 * Open a window.
2920 *
2921 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2922 * @param {Object} [data] Window opening data
2923 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2924 * for more details about the `opening` promise
2925 * @fires opening
2926 */
2927 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2928 var manager = this,
2929 preparing = [],
2930 opening = $.Deferred();
2931
2932 // Argument handling
2933 if ( typeof win === 'string' ) {
2934 return this.getWindow( win ).then( function ( win ) {
2935 return manager.openWindow( win, data );
2936 } );
2937 }
2938
2939 // Error handling
2940 if ( !this.hasWindow( win ) ) {
2941 opening.reject( new OO.ui.Error(
2942 'Cannot open window: window is not attached to manager'
2943 ) );
2944 } else if ( this.preparingToOpen || this.opening || this.opened ) {
2945 opening.reject( new OO.ui.Error(
2946 'Cannot open window: another window is opening or open'
2947 ) );
2948 }
2949
2950 // Window opening
2951 if ( opening.state() !== 'rejected' ) {
2952 if ( !win.getManager() ) {
2953 win.setManager( this );
2954 }
2955 preparing.push( win.load() );
2956
2957 if ( this.closing ) {
2958 // If a window is currently closing, wait for it to complete
2959 preparing.push( this.closing );
2960 }
2961
2962 this.preparingToOpen = $.when.apply( $, preparing );
2963 // Ensure handlers get called after preparingToOpen is set
2964 this.preparingToOpen.done( function () {
2965 if ( manager.modal ) {
2966 manager.toggleGlobalEvents( true );
2967 manager.toggleAriaIsolation( true );
2968 }
2969 manager.currentWindow = win;
2970 manager.opening = opening;
2971 manager.preparingToOpen = null;
2972 manager.emit( 'opening', win, opening, data );
2973 setTimeout( function () {
2974 win.setup( data ).then( function () {
2975 manager.updateWindowSize( win );
2976 manager.opening.notify( { state: 'setup' } );
2977 setTimeout( function () {
2978 win.ready( data ).then( function () {
2979 manager.opening.notify( { state: 'ready' } );
2980 manager.opening = null;
2981 manager.opened = $.Deferred();
2982 opening.resolve( manager.opened.promise(), data );
2983 } );
2984 }, manager.getReadyDelay() );
2985 } );
2986 }, manager.getSetupDelay() );
2987 } );
2988 }
2989
2990 return opening.promise();
2991 };
2992
2993 /**
2994 * Close a window.
2995 *
2996 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
2997 * @param {Object} [data] Window closing data
2998 * @return {jQuery.Promise} Promise resolved when window is done closing; see {@link #event-closing}
2999 * for more details about the `closing` promise
3000 * @throws {Error} If no window by that name is being managed
3001 * @fires closing
3002 */
3003 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3004 var manager = this,
3005 preparing = [],
3006 closing = $.Deferred(),
3007 opened;
3008
3009 // Argument handling
3010 if ( typeof win === 'string' ) {
3011 win = this.windows[win];
3012 } else if ( !this.hasWindow( win ) ) {
3013 win = null;
3014 }
3015
3016 // Error handling
3017 if ( !win ) {
3018 closing.reject( new OO.ui.Error(
3019 'Cannot close window: window is not attached to manager'
3020 ) );
3021 } else if ( win !== this.currentWindow ) {
3022 closing.reject( new OO.ui.Error(
3023 'Cannot close window: window already closed with different data'
3024 ) );
3025 } else if ( this.preparingToClose || this.closing ) {
3026 closing.reject( new OO.ui.Error(
3027 'Cannot close window: window already closing with different data'
3028 ) );
3029 }
3030
3031 // Window closing
3032 if ( closing.state() !== 'rejected' ) {
3033 if ( this.opening ) {
3034 // If the window is currently opening, close it when it's done
3035 preparing.push( this.opening );
3036 }
3037
3038 this.preparingToClose = $.when.apply( $, preparing );
3039 // Ensure handlers get called after preparingToClose is set
3040 this.preparingToClose.done( function () {
3041 manager.closing = closing;
3042 manager.preparingToClose = null;
3043 manager.emit( 'closing', win, closing, data );
3044 opened = manager.opened;
3045 manager.opened = null;
3046 opened.resolve( closing.promise(), data );
3047 setTimeout( function () {
3048 win.hold( data ).then( function () {
3049 closing.notify( { state: 'hold' } );
3050 setTimeout( function () {
3051 win.teardown( data ).then( function () {
3052 closing.notify( { state: 'teardown' } );
3053 if ( manager.modal ) {
3054 manager.toggleGlobalEvents( false );
3055 manager.toggleAriaIsolation( false );
3056 }
3057 manager.closing = null;
3058 manager.currentWindow = null;
3059 closing.resolve( data );
3060 } );
3061 }, manager.getTeardownDelay() );
3062 } );
3063 }, manager.getHoldDelay() );
3064 } );
3065 }
3066
3067 return closing.promise();
3068 };
3069
3070 /**
3071 * Add windows.
3072 *
3073 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
3074 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
3075 * a statically configured symbolic name
3076 */
3077 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3078 var i, len, win, name, list;
3079
3080 if ( $.isArray( windows ) ) {
3081 // Convert to map of windows by looking up symbolic names from static configuration
3082 list = {};
3083 for ( i = 0, len = windows.length; i < len; i++ ) {
3084 name = windows[i].constructor.static.name;
3085 if ( typeof name !== 'string' ) {
3086 throw new Error( 'Cannot add window' );
3087 }
3088 list[name] = windows[i];
3089 }
3090 } else if ( $.isPlainObject( windows ) ) {
3091 list = windows;
3092 }
3093
3094 // Add windows
3095 for ( name in list ) {
3096 win = list[name];
3097 this.windows[name] = win;
3098 this.$element.append( win.$element );
3099 }
3100 };
3101
3102 /**
3103 * Remove windows.
3104 *
3105 * Windows will be closed before they are removed.
3106 *
3107 * @param {string} name Symbolic name of window to remove
3108 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3109 * @throws {Error} If windows being removed are not being managed
3110 */
3111 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3112 var i, len, win, name,
3113 manager = this,
3114 promises = [],
3115 cleanup = function ( name, win ) {
3116 delete manager.windows[name];
3117 win.$element.detach();
3118 };
3119
3120 for ( i = 0, len = names.length; i < len; i++ ) {
3121 name = names[i];
3122 win = this.windows[name];
3123 if ( !win ) {
3124 throw new Error( 'Cannot remove window' );
3125 }
3126 promises.push( this.closeWindow( name ).then( cleanup.bind( null, name, win ) ) );
3127 }
3128
3129 return $.when.apply( $, promises );
3130 };
3131
3132 /**
3133 * Remove all windows.
3134 *
3135 * Windows will be closed before they are removed.
3136 *
3137 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3138 */
3139 OO.ui.WindowManager.prototype.clearWindows = function () {
3140 return this.removeWindows( Object.keys( this.windows ) );
3141 };
3142
3143 /**
3144 * Set dialog size.
3145 *
3146 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3147 *
3148 * @chainable
3149 */
3150 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3151 // Bypass for non-current, and thus invisible, windows
3152 if ( win !== this.currentWindow ) {
3153 return;
3154 }
3155
3156 var viewport = OO.ui.Element.getDimensions( win.getElementWindow() ),
3157 sizes = this.constructor.static.sizes,
3158 size = win.getSize();
3159
3160 if ( !sizes[size] ) {
3161 size = this.constructor.static.defaultSize;
3162 }
3163 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[size].width ) {
3164 size = 'full';
3165 }
3166
3167 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3168 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3169 win.setDimensions( sizes[size] );
3170
3171 this.emit( 'resize', win );
3172
3173 return this;
3174 };
3175
3176 /**
3177 * Bind or unbind global events for scrolling.
3178 *
3179 * @param {boolean} [on] Bind global events
3180 * @chainable
3181 */
3182 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3183 on = on === undefined ? !!this.globalEvents : !!on;
3184
3185 if ( on ) {
3186 if ( !this.globalEvents ) {
3187 this.$( this.getElementDocument() ).on( {
3188 // Prevent scrolling by keys in top-level window
3189 keydown: this.onDocumentKeyDownHandler
3190 } );
3191 this.$( this.getElementWindow() ).on( {
3192 // Prevent scrolling by wheel in top-level window
3193 mousewheel: this.onWindowMouseWheelHandler,
3194 // Start listening for top-level window dimension changes
3195 'orientationchange resize': this.onWindowResizeHandler
3196 } );
3197 this.globalEvents = true;
3198 }
3199 } else if ( this.globalEvents ) {
3200 // Unbind global events
3201 this.$( this.getElementDocument() ).off( {
3202 // Allow scrolling by keys in top-level window
3203 keydown: this.onDocumentKeyDownHandler
3204 } );
3205 this.$( this.getElementWindow() ).off( {
3206 // Allow scrolling by wheel in top-level window
3207 mousewheel: this.onWindowMouseWheelHandler,
3208 // Stop listening for top-level window dimension changes
3209 'orientationchange resize': this.onWindowResizeHandler
3210 } );
3211 this.globalEvents = false;
3212 }
3213
3214 return this;
3215 };
3216
3217 /**
3218 * Toggle screen reader visibility of content other than the window manager.
3219 *
3220 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3221 * @chainable
3222 */
3223 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3224 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3225
3226 if ( isolate ) {
3227 if ( !this.$ariaHidden ) {
3228 // Hide everything other than the window manager from screen readers
3229 this.$ariaHidden = $( 'body' )
3230 .children()
3231 .not( this.$element.parentsUntil( 'body' ).last() )
3232 .attr( 'aria-hidden', '' );
3233 }
3234 } else if ( this.$ariaHidden ) {
3235 // Restore screen reader visibility
3236 this.$ariaHidden.removeAttr( 'aria-hidden' );
3237 this.$ariaHidden = null;
3238 }
3239
3240 return this;
3241 };
3242
3243 /**
3244 * Destroy window manager.
3245 *
3246 * Windows will not be closed, only removed from the DOM.
3247 */
3248 OO.ui.WindowManager.prototype.destroy = function () {
3249 this.toggleGlobalEvents( false );
3250 this.toggleAriaIsolation( false );
3251 this.$element.remove();
3252 };
3253
3254 /**
3255 * @abstract
3256 * @class
3257 *
3258 * @constructor
3259 * @param {string|jQuery} message Description of error
3260 * @param {Object} [config] Configuration options
3261 * @cfg {boolean} [recoverable=true] Error is recoverable
3262 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3263 */
3264 OO.ui.Error = function OoUiElement( message, config ) {
3265 // Configuration initialization
3266 config = config || {};
3267
3268 // Properties
3269 this.message = message instanceof jQuery ? message : String( message );
3270 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3271 this.warning = !!config.warning;
3272 };
3273
3274 /* Setup */
3275
3276 OO.initClass( OO.ui.Error );
3277
3278 /* Methods */
3279
3280 /**
3281 * Check if error can be recovered from.
3282 *
3283 * @return {boolean} Error is recoverable
3284 */
3285 OO.ui.Error.prototype.isRecoverable = function () {
3286 return this.recoverable;
3287 };
3288
3289 /**
3290 * Check if the error is a warning
3291 *
3292 * @return {boolean} Error is warning
3293 */
3294 OO.ui.Error.prototype.isWarning = function () {
3295 return this.warning;
3296 };
3297
3298 /**
3299 * Get error message as DOM nodes.
3300 *
3301 * @return {jQuery} Error message in DOM nodes
3302 */
3303 OO.ui.Error.prototype.getMessage = function () {
3304 return this.message instanceof jQuery ?
3305 this.message.clone() :
3306 $( '<div>' ).text( this.message ).contents();
3307 };
3308
3309 /**
3310 * Get error message as text.
3311 *
3312 * @return {string} Error message
3313 */
3314 OO.ui.Error.prototype.getMessageText = function () {
3315 return this.message instanceof jQuery ? this.message.text() : this.message;
3316 };
3317
3318 /**
3319 * A list of functions, called in sequence.
3320 *
3321 * If a function added to a process returns boolean false the process will stop; if it returns an
3322 * object with a `promise` method the process will use the promise to either continue to the next
3323 * step when the promise is resolved or stop when the promise is rejected.
3324 *
3325 * @class
3326 *
3327 * @constructor
3328 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3329 * call, see #createStep for more information
3330 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3331 * or a promise
3332 * @return {Object} Step object, with `callback` and `context` properties
3333 */
3334 OO.ui.Process = function ( step, context ) {
3335 // Properties
3336 this.steps = [];
3337
3338 // Initialization
3339 if ( step !== undefined ) {
3340 this.next( step, context );
3341 }
3342 };
3343
3344 /* Setup */
3345
3346 OO.initClass( OO.ui.Process );
3347
3348 /* Methods */
3349
3350 /**
3351 * Start the process.
3352 *
3353 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3354 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3355 * process, the remaining steps will not be taken
3356 */
3357 OO.ui.Process.prototype.execute = function () {
3358 var i, len, promise;
3359
3360 /**
3361 * Continue execution.
3362 *
3363 * @ignore
3364 * @param {Array} step A function and the context it should be called in
3365 * @return {Function} Function that continues the process
3366 */
3367 function proceed( step ) {
3368 return function () {
3369 // Execute step in the correct context
3370 var deferred,
3371 result = step.callback.call( step.context );
3372
3373 if ( result === false ) {
3374 // Use rejected promise for boolean false results
3375 return $.Deferred().reject( [] ).promise();
3376 }
3377 if ( typeof result === 'number' ) {
3378 if ( result < 0 ) {
3379 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3380 }
3381 // Use a delayed promise for numbers, expecting them to be in milliseconds
3382 deferred = $.Deferred();
3383 setTimeout( deferred.resolve, result );
3384 return deferred.promise();
3385 }
3386 if ( result instanceof OO.ui.Error ) {
3387 // Use rejected promise for error
3388 return $.Deferred().reject( [ result ] ).promise();
3389 }
3390 if ( $.isArray( result ) && result.length && result[0] instanceof OO.ui.Error ) {
3391 // Use rejected promise for list of errors
3392 return $.Deferred().reject( result ).promise();
3393 }
3394 // Duck-type the object to see if it can produce a promise
3395 if ( result && $.isFunction( result.promise ) ) {
3396 // Use a promise generated from the result
3397 return result.promise();
3398 }
3399 // Use resolved promise for other results
3400 return $.Deferred().resolve().promise();
3401 };
3402 }
3403
3404 if ( this.steps.length ) {
3405 // Generate a chain reaction of promises
3406 promise = proceed( this.steps[0] )();
3407 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3408 promise = promise.then( proceed( this.steps[i] ) );
3409 }
3410 } else {
3411 promise = $.Deferred().resolve().promise();
3412 }
3413
3414 return promise;
3415 };
3416
3417 /**
3418 * Create a process step.
3419 *
3420 * @private
3421 * @param {number|jQuery.Promise|Function} step
3422 *
3423 * - Number of milliseconds to wait; or
3424 * - Promise to wait to be resolved; or
3425 * - Function to execute
3426 * - If it returns boolean false the process will stop
3427 * - If it returns an object with a `promise` method the process will use the promise to either
3428 * continue to the next step when the promise is resolved or stop when the promise is rejected
3429 * - If it returns a number, the process will wait for that number of milliseconds before
3430 * proceeding
3431 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3432 * or a promise
3433 * @return {Object} Step object, with `callback` and `context` properties
3434 */
3435 OO.ui.Process.prototype.createStep = function ( step, context ) {
3436 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3437 return {
3438 callback: function () {
3439 return step;
3440 },
3441 context: null
3442 };
3443 }
3444 if ( $.isFunction( step ) ) {
3445 return {
3446 callback: step,
3447 context: context
3448 };
3449 }
3450 throw new Error( 'Cannot create process step: number, promise or function expected' );
3451 };
3452
3453 /**
3454 * Add step to the beginning of the process.
3455 *
3456 * @inheritdoc #createStep
3457 * @return {OO.ui.Process} this
3458 * @chainable
3459 */
3460 OO.ui.Process.prototype.first = function ( step, context ) {
3461 this.steps.unshift( this.createStep( step, context ) );
3462 return this;
3463 };
3464
3465 /**
3466 * Add step to the end of the process.
3467 *
3468 * @inheritdoc #createStep
3469 * @return {OO.ui.Process} this
3470 * @chainable
3471 */
3472 OO.ui.Process.prototype.next = function ( step, context ) {
3473 this.steps.push( this.createStep( step, context ) );
3474 return this;
3475 };
3476
3477 /**
3478 * Factory for tools.
3479 *
3480 * @class
3481 * @extends OO.Factory
3482 * @constructor
3483 */
3484 OO.ui.ToolFactory = function OoUiToolFactory() {
3485 // Parent constructor
3486 OO.ui.ToolFactory.super.call( this );
3487 };
3488
3489 /* Setup */
3490
3491 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3492
3493 /* Methods */
3494
3495 /**
3496 * Get tools from the factory
3497 *
3498 * @param {Array} include Included tools
3499 * @param {Array} exclude Excluded tools
3500 * @param {Array} promote Promoted tools
3501 * @param {Array} demote Demoted tools
3502 * @return {string[]} List of tools
3503 */
3504 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3505 var i, len, included, promoted, demoted,
3506 auto = [],
3507 used = {};
3508
3509 // Collect included and not excluded tools
3510 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3511
3512 // Promotion
3513 promoted = this.extract( promote, used );
3514 demoted = this.extract( demote, used );
3515
3516 // Auto
3517 for ( i = 0, len = included.length; i < len; i++ ) {
3518 if ( !used[included[i]] ) {
3519 auto.push( included[i] );
3520 }
3521 }
3522
3523 return promoted.concat( auto ).concat( demoted );
3524 };
3525
3526 /**
3527 * Get a flat list of names from a list of names or groups.
3528 *
3529 * Tools can be specified in the following ways:
3530 *
3531 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3532 * - All tools in a group: `{ group: 'group-name' }`
3533 * - All tools: `'*'`
3534 *
3535 * @private
3536 * @param {Array|string} collection List of tools
3537 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3538 * names will be added as properties
3539 * @return {string[]} List of extracted names
3540 */
3541 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3542 var i, len, item, name, tool,
3543 names = [];
3544
3545 if ( collection === '*' ) {
3546 for ( name in this.registry ) {
3547 tool = this.registry[name];
3548 if (
3549 // Only add tools by group name when auto-add is enabled
3550 tool.static.autoAddToCatchall &&
3551 // Exclude already used tools
3552 ( !used || !used[name] )
3553 ) {
3554 names.push( name );
3555 if ( used ) {
3556 used[name] = true;
3557 }
3558 }
3559 }
3560 } else if ( $.isArray( collection ) ) {
3561 for ( i = 0, len = collection.length; i < len; i++ ) {
3562 item = collection[i];
3563 // Allow plain strings as shorthand for named tools
3564 if ( typeof item === 'string' ) {
3565 item = { name: item };
3566 }
3567 if ( OO.isPlainObject( item ) ) {
3568 if ( item.group ) {
3569 for ( name in this.registry ) {
3570 tool = this.registry[name];
3571 if (
3572 // Include tools with matching group
3573 tool.static.group === item.group &&
3574 // Only add tools by group name when auto-add is enabled
3575 tool.static.autoAddToGroup &&
3576 // Exclude already used tools
3577 ( !used || !used[name] )
3578 ) {
3579 names.push( name );
3580 if ( used ) {
3581 used[name] = true;
3582 }
3583 }
3584 }
3585 // Include tools with matching name and exclude already used tools
3586 } else if ( item.name && ( !used || !used[item.name] ) ) {
3587 names.push( item.name );
3588 if ( used ) {
3589 used[item.name] = true;
3590 }
3591 }
3592 }
3593 }
3594 }
3595 return names;
3596 };
3597
3598 /**
3599 * Factory for tool groups.
3600 *
3601 * @class
3602 * @extends OO.Factory
3603 * @constructor
3604 */
3605 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3606 // Parent constructor
3607 OO.Factory.call( this );
3608
3609 var i, l,
3610 defaultClasses = this.constructor.static.getDefaultClasses();
3611
3612 // Register default toolgroups
3613 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3614 this.register( defaultClasses[i] );
3615 }
3616 };
3617
3618 /* Setup */
3619
3620 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3621
3622 /* Static Methods */
3623
3624 /**
3625 * Get a default set of classes to be registered on construction
3626 *
3627 * @return {Function[]} Default classes
3628 */
3629 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3630 return [
3631 OO.ui.BarToolGroup,
3632 OO.ui.ListToolGroup,
3633 OO.ui.MenuToolGroup
3634 ];
3635 };
3636
3637 /**
3638 * Theme logic.
3639 *
3640 * @abstract
3641 * @class
3642 *
3643 * @constructor
3644 * @param {Object} [config] Configuration options
3645 */
3646 OO.ui.Theme = function OoUiTheme( config ) {
3647 // Configuration initialization
3648 config = config || {};
3649 };
3650
3651 /* Setup */
3652
3653 OO.initClass( OO.ui.Theme );
3654
3655 /* Methods */
3656
3657 /**
3658 * Get a list of classes to be applied to a widget.
3659 *
3660 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3661 * otherwise state transitions will not work properly.
3662 *
3663 * @param {OO.ui.Element} element Element for which to get classes
3664 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3665 */
3666 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3667 return { on: [], off: [] };
3668 };
3669
3670 /**
3671 * Update CSS classes provided by the theme.
3672 *
3673 * For elements with theme logic hooks, this should be called any time there's a state change.
3674 *
3675 * @param {OO.ui.Element} element Element for which to update classes
3676 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3677 */
3678 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3679 var classes = this.getElementClasses( element );
3680
3681 element.$element
3682 .removeClass( classes.off.join( ' ' ) )
3683 .addClass( classes.on.join( ' ' ) );
3684 };
3685
3686 /**
3687 * Element with a button.
3688 *
3689 * Buttons are used for controls which can be clicked. They can be configured to use tab indexing
3690 * and access keys for accessibility purposes.
3691 *
3692 * @abstract
3693 * @class
3694 *
3695 * @constructor
3696 * @param {Object} [config] Configuration options
3697 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3698 * @cfg {boolean} [framed=true] Render button with a frame
3699 * @cfg {number} [tabIndex=0] Button's tab index. Use 0 to use default ordering, use -1 to prevent
3700 * tab focusing.
3701 * @cfg {string} [accessKey] Button's access key
3702 */
3703 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3704 // Configuration initialization
3705 config = config || {};
3706
3707 // Properties
3708 this.$button = null;
3709 this.framed = null;
3710 this.tabIndex = null;
3711 this.accessKey = null;
3712 this.active = false;
3713 this.onMouseUpHandler = this.onMouseUp.bind( this );
3714 this.onMouseDownHandler = this.onMouseDown.bind( this );
3715
3716 // Initialization
3717 this.$element.addClass( 'oo-ui-buttonElement' );
3718 this.toggleFramed( config.framed === undefined || config.framed );
3719 this.setTabIndex( config.tabIndex || 0 );
3720 this.setAccessKey( config.accessKey );
3721 this.setButtonElement( config.$button || this.$( '<a>' ) );
3722 };
3723
3724 /* Setup */
3725
3726 OO.initClass( OO.ui.ButtonElement );
3727
3728 /* Static Properties */
3729
3730 /**
3731 * Cancel mouse down events.
3732 *
3733 * @static
3734 * @inheritable
3735 * @property {boolean}
3736 */
3737 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
3738
3739 /* Methods */
3740
3741 /**
3742 * Set the button element.
3743 *
3744 * If an element is already set, it will be cleaned up before setting up the new element.
3745 *
3746 * @param {jQuery} $button Element to use as button
3747 */
3748 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
3749 if ( this.$button ) {
3750 this.$button
3751 .removeClass( 'oo-ui-buttonElement-button' )
3752 .removeAttr( 'role accesskey tabindex' )
3753 .off( this.onMouseDownHandler );
3754 }
3755
3756 this.$button = $button
3757 .addClass( 'oo-ui-buttonElement-button' )
3758 .attr( { role: 'button', accesskey: this.accessKey, tabindex: this.tabIndex } )
3759 .on( 'mousedown', this.onMouseDownHandler );
3760 };
3761
3762 /**
3763 * Handles mouse down events.
3764 *
3765 * @param {jQuery.Event} e Mouse down event
3766 */
3767 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
3768 if ( this.isDisabled() || e.which !== 1 ) {
3769 return false;
3770 }
3771 // Remove the tab-index while the button is down to prevent the button from stealing focus
3772 this.$button.removeAttr( 'tabindex' );
3773 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
3774 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
3775 // reliably reapply the tabindex and remove the pressed class
3776 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
3777 // Prevent change of focus unless specifically configured otherwise
3778 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3779 return false;
3780 }
3781 };
3782
3783 /**
3784 * Handles mouse up events.
3785 *
3786 * @param {jQuery.Event} e Mouse up event
3787 */
3788 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
3789 if ( this.isDisabled() || e.which !== 1 ) {
3790 return false;
3791 }
3792 // Restore the tab-index after the button is up to restore the button's accessibility
3793 this.$button.attr( 'tabindex', this.tabIndex );
3794 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
3795 // Stop listening for mouseup, since we only needed this once
3796 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
3797 };
3798
3799 /**
3800 * Check if button has a frame.
3801 *
3802 * @return {boolean} Button is framed
3803 */
3804 OO.ui.ButtonElement.prototype.isFramed = function () {
3805 return this.framed;
3806 };
3807
3808 /**
3809 * Toggle frame.
3810 *
3811 * @param {boolean} [framed] Make button framed, omit to toggle
3812 * @chainable
3813 */
3814 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
3815 framed = framed === undefined ? !this.framed : !!framed;
3816 if ( framed !== this.framed ) {
3817 this.framed = framed;
3818 this.$element
3819 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
3820 .toggleClass( 'oo-ui-buttonElement-framed', framed );
3821 this.updateThemeClasses();
3822 }
3823
3824 return this;
3825 };
3826
3827 /**
3828 * Set tab index.
3829 *
3830 * @param {number|null} tabIndex Button's tab index, use null to remove
3831 * @chainable
3832 */
3833 OO.ui.ButtonElement.prototype.setTabIndex = function ( tabIndex ) {
3834 tabIndex = typeof tabIndex === 'number' && tabIndex >= 0 ? tabIndex : null;
3835
3836 if ( this.tabIndex !== tabIndex ) {
3837 if ( this.$button ) {
3838 if ( tabIndex !== null ) {
3839 this.$button.attr( 'tabindex', tabIndex );
3840 } else {
3841 this.$button.removeAttr( 'tabindex' );
3842 }
3843 }
3844 this.tabIndex = tabIndex;
3845 }
3846
3847 return this;
3848 };
3849
3850 /**
3851 * Set access key.
3852 *
3853 * @param {string} accessKey Button's access key, use empty string to remove
3854 * @chainable
3855 */
3856 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
3857 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
3858
3859 if ( this.accessKey !== accessKey ) {
3860 if ( this.$button ) {
3861 if ( accessKey !== null ) {
3862 this.$button.attr( 'accesskey', accessKey );
3863 } else {
3864 this.$button.removeAttr( 'accesskey' );
3865 }
3866 }
3867 this.accessKey = accessKey;
3868 }
3869
3870 return this;
3871 };
3872
3873 /**
3874 * Set active state.
3875 *
3876 * @param {boolean} [value] Make button active
3877 * @chainable
3878 */
3879 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
3880 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
3881 return this;
3882 };
3883
3884 /**
3885 * Element containing a sequence of child elements.
3886 *
3887 * @abstract
3888 * @class
3889 *
3890 * @constructor
3891 * @param {Object} [config] Configuration options
3892 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
3893 */
3894 OO.ui.GroupElement = function OoUiGroupElement( config ) {
3895 // Configuration initialization
3896 config = config || {};
3897
3898 // Properties
3899 this.$group = null;
3900 this.items = [];
3901 this.aggregateItemEvents = {};
3902
3903 // Initialization
3904 this.setGroupElement( config.$group || this.$( '<div>' ) );
3905 };
3906
3907 /* Methods */
3908
3909 /**
3910 * Set the group element.
3911 *
3912 * If an element is already set, items will be moved to the new element.
3913 *
3914 * @param {jQuery} $group Element to use as group
3915 */
3916 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
3917 var i, len;
3918
3919 this.$group = $group;
3920 for ( i = 0, len = this.items.length; i < len; i++ ) {
3921 this.$group.append( this.items[i].$element );
3922 }
3923 };
3924
3925 /**
3926 * Check if there are no items.
3927 *
3928 * @return {boolean} Group is empty
3929 */
3930 OO.ui.GroupElement.prototype.isEmpty = function () {
3931 return !this.items.length;
3932 };
3933
3934 /**
3935 * Get items.
3936 *
3937 * @return {OO.ui.Element[]} Items
3938 */
3939 OO.ui.GroupElement.prototype.getItems = function () {
3940 return this.items.slice( 0 );
3941 };
3942
3943 /**
3944 * Get an item by its data.
3945 *
3946 * Data is compared by a hash of its value. Only the first item with matching data will be returned.
3947 *
3948 * @param {Object} data Item data to search for
3949 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
3950 */
3951 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
3952 var i, len, item,
3953 hash = OO.getHash( data );
3954
3955 for ( i = 0, len = this.items.length; i < len; i++ ) {
3956 item = this.items[i];
3957 if ( hash === OO.getHash( item.getData() ) ) {
3958 return item;
3959 }
3960 }
3961
3962 return null;
3963 };
3964
3965 /**
3966 * Get items by their data.
3967 *
3968 * Data is compared by a hash of its value. All items with matching data will be returned.
3969 *
3970 * @param {Object} data Item data to search for
3971 * @return {OO.ui.Element[]} Items with equivalent data
3972 */
3973 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
3974 var i, len, item,
3975 hash = OO.getHash( data ),
3976 items = [];
3977
3978 for ( i = 0, len = this.items.length; i < len; i++ ) {
3979 item = this.items[i];
3980 if ( hash === OO.getHash( item.getData() ) ) {
3981 items.push( item );
3982 }
3983 }
3984
3985 return items;
3986 };
3987
3988 /**
3989 * Add an aggregate item event.
3990 *
3991 * Aggregated events are listened to on each item and then emitted by the group under a new name,
3992 * and with an additional leading parameter containing the item that emitted the original event.
3993 * Other arguments that were emitted from the original event are passed through.
3994 *
3995 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
3996 * event, use null value to remove aggregation
3997 * @throws {Error} If aggregation already exists
3998 */
3999 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4000 var i, len, item, add, remove, itemEvent, groupEvent;
4001
4002 for ( itemEvent in events ) {
4003 groupEvent = events[itemEvent];
4004
4005 // Remove existing aggregated event
4006 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4007 // Don't allow duplicate aggregations
4008 if ( groupEvent ) {
4009 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4010 }
4011 // Remove event aggregation from existing items
4012 for ( i = 0, len = this.items.length; i < len; i++ ) {
4013 item = this.items[i];
4014 if ( item.connect && item.disconnect ) {
4015 remove = {};
4016 remove[itemEvent] = [ 'emit', groupEvent, item ];
4017 item.disconnect( this, remove );
4018 }
4019 }
4020 // Prevent future items from aggregating event
4021 delete this.aggregateItemEvents[itemEvent];
4022 }
4023
4024 // Add new aggregate event
4025 if ( groupEvent ) {
4026 // Make future items aggregate event
4027 this.aggregateItemEvents[itemEvent] = groupEvent;
4028 // Add event aggregation to existing items
4029 for ( i = 0, len = this.items.length; i < len; i++ ) {
4030 item = this.items[i];
4031 if ( item.connect && item.disconnect ) {
4032 add = {};
4033 add[itemEvent] = [ 'emit', groupEvent, item ];
4034 item.connect( this, add );
4035 }
4036 }
4037 }
4038 }
4039 };
4040
4041 /**
4042 * Add items.
4043 *
4044 * Adding an existing item will move it.
4045 *
4046 * @param {OO.ui.Element[]} items Items
4047 * @param {number} [index] Index to insert items at
4048 * @chainable
4049 */
4050 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4051 var i, len, item, event, events, currentIndex,
4052 itemElements = [];
4053
4054 for ( i = 0, len = items.length; i < len; i++ ) {
4055 item = items[i];
4056
4057 // Check if item exists then remove it first, effectively "moving" it
4058 currentIndex = $.inArray( item, this.items );
4059 if ( currentIndex >= 0 ) {
4060 this.removeItems( [ item ] );
4061 // Adjust index to compensate for removal
4062 if ( currentIndex < index ) {
4063 index--;
4064 }
4065 }
4066 // Add the item
4067 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4068 events = {};
4069 for ( event in this.aggregateItemEvents ) {
4070 events[event] = [ 'emit', this.aggregateItemEvents[event], item ];
4071 }
4072 item.connect( this, events );
4073 }
4074 item.setElementGroup( this );
4075 itemElements.push( item.$element.get( 0 ) );
4076 }
4077
4078 if ( index === undefined || index < 0 || index >= this.items.length ) {
4079 this.$group.append( itemElements );
4080 this.items.push.apply( this.items, items );
4081 } else if ( index === 0 ) {
4082 this.$group.prepend( itemElements );
4083 this.items.unshift.apply( this.items, items );
4084 } else {
4085 this.items[index].$element.before( itemElements );
4086 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4087 }
4088
4089 return this;
4090 };
4091
4092 /**
4093 * Remove items.
4094 *
4095 * Items will be detached, not removed, so they can be used later.
4096 *
4097 * @param {OO.ui.Element[]} items Items to remove
4098 * @chainable
4099 */
4100 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4101 var i, len, item, index, remove, itemEvent;
4102
4103 // Remove specific items
4104 for ( i = 0, len = items.length; i < len; i++ ) {
4105 item = items[i];
4106 index = $.inArray( item, this.items );
4107 if ( index !== -1 ) {
4108 if (
4109 item.connect && item.disconnect &&
4110 !$.isEmptyObject( this.aggregateItemEvents )
4111 ) {
4112 remove = {};
4113 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4114 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
4115 }
4116 item.disconnect( this, remove );
4117 }
4118 item.setElementGroup( null );
4119 this.items.splice( index, 1 );
4120 item.$element.detach();
4121 }
4122 }
4123
4124 return this;
4125 };
4126
4127 /**
4128 * Clear all items.
4129 *
4130 * Items will be detached, not removed, so they can be used later.
4131 *
4132 * @chainable
4133 */
4134 OO.ui.GroupElement.prototype.clearItems = function () {
4135 var i, len, item, remove, itemEvent;
4136
4137 // Remove all items
4138 for ( i = 0, len = this.items.length; i < len; i++ ) {
4139 item = this.items[i];
4140 if (
4141 item.connect && item.disconnect &&
4142 !$.isEmptyObject( this.aggregateItemEvents )
4143 ) {
4144 remove = {};
4145 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4146 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
4147 }
4148 item.disconnect( this, remove );
4149 }
4150 item.setElementGroup( null );
4151 item.$element.detach();
4152 }
4153
4154 this.items = [];
4155 return this;
4156 };
4157
4158 /**
4159 * Element containing an icon.
4160 *
4161 * Icons are graphics, about the size of normal text. They can be used to aid the user in locating
4162 * a control or convey information in a more space efficient way. Icons should rarely be used
4163 * without labels; such as in a toolbar where space is at a premium or within a context where the
4164 * meaning is very clear to the user.
4165 *
4166 * @abstract
4167 * @class
4168 *
4169 * @constructor
4170 * @param {Object} [config] Configuration options
4171 * @cfg {jQuery} [$icon] Icon node, assigned to #$icon, omit to use a generated `<span>`
4172 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
4173 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4174 * language
4175 * @cfg {string} [iconTitle] Icon title text or a function that returns text
4176 */
4177 OO.ui.IconElement = function OoUiIconElement( config ) {
4178 // Configuration initialization
4179 config = config || {};
4180
4181 // Properties
4182 this.$icon = null;
4183 this.icon = null;
4184 this.iconTitle = null;
4185
4186 // Initialization
4187 this.setIcon( config.icon || this.constructor.static.icon );
4188 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4189 this.setIconElement( config.$icon || this.$( '<span>' ) );
4190 };
4191
4192 /* Setup */
4193
4194 OO.initClass( OO.ui.IconElement );
4195
4196 /* Static Properties */
4197
4198 /**
4199 * Icon.
4200 *
4201 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
4202 *
4203 * For i18n purposes, this property can be an object containing a `default` icon name property and
4204 * additional icon names keyed by language code.
4205 *
4206 * Example of i18n icon definition:
4207 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4208 *
4209 * @static
4210 * @inheritable
4211 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
4212 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4213 * language
4214 */
4215 OO.ui.IconElement.static.icon = null;
4216
4217 /**
4218 * Icon title.
4219 *
4220 * @static
4221 * @inheritable
4222 * @property {string|Function|null} Icon title text, a function that returns text or null for no
4223 * icon title
4224 */
4225 OO.ui.IconElement.static.iconTitle = null;
4226
4227 /* Methods */
4228
4229 /**
4230 * Set the icon element.
4231 *
4232 * If an element is already set, it will be cleaned up before setting up the new element.
4233 *
4234 * @param {jQuery} $icon Element to use as icon
4235 */
4236 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
4237 if ( this.$icon ) {
4238 this.$icon
4239 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
4240 .removeAttr( 'title' );
4241 }
4242
4243 this.$icon = $icon
4244 .addClass( 'oo-ui-iconElement-icon' )
4245 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
4246 if ( this.iconTitle !== null ) {
4247 this.$icon.attr( 'title', this.iconTitle );
4248 }
4249 };
4250
4251 /**
4252 * Set icon name.
4253 *
4254 * @param {Object|string|null} icon Symbolic icon name, or map of icon names keyed by language ID;
4255 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4256 * language, use null to remove icon
4257 * @chainable
4258 */
4259 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
4260 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
4261 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
4262
4263 if ( this.icon !== icon ) {
4264 if ( this.$icon ) {
4265 if ( this.icon !== null ) {
4266 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
4267 }
4268 if ( icon !== null ) {
4269 this.$icon.addClass( 'oo-ui-icon-' + icon );
4270 }
4271 }
4272 this.icon = icon;
4273 }
4274
4275 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
4276 this.updateThemeClasses();
4277
4278 return this;
4279 };
4280
4281 /**
4282 * Set icon title.
4283 *
4284 * @param {string|Function|null} icon Icon title text, a function that returns text or null
4285 * for no icon title
4286 * @chainable
4287 */
4288 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
4289 iconTitle = typeof iconTitle === 'function' ||
4290 ( typeof iconTitle === 'string' && iconTitle.length ) ?
4291 OO.ui.resolveMsg( iconTitle ) : null;
4292
4293 if ( this.iconTitle !== iconTitle ) {
4294 this.iconTitle = iconTitle;
4295 if ( this.$icon ) {
4296 if ( this.iconTitle !== null ) {
4297 this.$icon.attr( 'title', iconTitle );
4298 } else {
4299 this.$icon.removeAttr( 'title' );
4300 }
4301 }
4302 }
4303
4304 return this;
4305 };
4306
4307 /**
4308 * Get icon name.
4309 *
4310 * @return {string} Icon name
4311 */
4312 OO.ui.IconElement.prototype.getIcon = function () {
4313 return this.icon;
4314 };
4315
4316 /**
4317 * Element containing an indicator.
4318 *
4319 * Indicators are graphics, smaller than normal text. They can be used to describe unique status or
4320 * behavior. Indicators should only be used in exceptional cases; such as a button that opens a menu
4321 * instead of performing an action directly, or an item in a list which has errors that need to be
4322 * resolved.
4323 *
4324 * @abstract
4325 * @class
4326 *
4327 * @constructor
4328 * @param {Object} [config] Configuration options
4329 * @cfg {jQuery} [$indicator] Indicator node, assigned to #$indicator, omit to use a generated
4330 * `<span>`
4331 * @cfg {string} [indicator] Symbolic indicator name
4332 * @cfg {string} [indicatorTitle] Indicator title text or a function that returns text
4333 */
4334 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
4335 // Configuration initialization
4336 config = config || {};
4337
4338 // Properties
4339 this.$indicator = null;
4340 this.indicator = null;
4341 this.indicatorTitle = null;
4342
4343 // Initialization
4344 this.setIndicator( config.indicator || this.constructor.static.indicator );
4345 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4346 this.setIndicatorElement( config.$indicator || this.$( '<span>' ) );
4347 };
4348
4349 /* Setup */
4350
4351 OO.initClass( OO.ui.IndicatorElement );
4352
4353 /* Static Properties */
4354
4355 /**
4356 * indicator.
4357 *
4358 * @static
4359 * @inheritable
4360 * @property {string|null} Symbolic indicator name
4361 */
4362 OO.ui.IndicatorElement.static.indicator = null;
4363
4364 /**
4365 * Indicator title.
4366 *
4367 * @static
4368 * @inheritable
4369 * @property {string|Function|null} Indicator title text, a function that returns text or null for no
4370 * indicator title
4371 */
4372 OO.ui.IndicatorElement.static.indicatorTitle = null;
4373
4374 /* Methods */
4375
4376 /**
4377 * Set the indicator element.
4378 *
4379 * If an element is already set, it will be cleaned up before setting up the new element.
4380 *
4381 * @param {jQuery} $indicator Element to use as indicator
4382 */
4383 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
4384 if ( this.$indicator ) {
4385 this.$indicator
4386 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
4387 .removeAttr( 'title' );
4388 }
4389
4390 this.$indicator = $indicator
4391 .addClass( 'oo-ui-indicatorElement-indicator' )
4392 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
4393 if ( this.indicatorTitle !== null ) {
4394 this.$indicatorTitle.attr( 'title', this.indicatorTitle );
4395 }
4396 };
4397
4398 /**
4399 * Set indicator name.
4400 *
4401 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4402 * @chainable
4403 */
4404 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
4405 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
4406
4407 if ( this.indicator !== indicator ) {
4408 if ( this.$indicator ) {
4409 if ( this.indicator !== null ) {
4410 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4411 }
4412 if ( indicator !== null ) {
4413 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4414 }
4415 }
4416 this.indicator = indicator;
4417 }
4418
4419 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
4420 this.updateThemeClasses();
4421
4422 return this;
4423 };
4424
4425 /**
4426 * Set indicator title.
4427 *
4428 * @param {string|Function|null} indicator Indicator title text, a function that returns text or
4429 * null for no indicator title
4430 * @chainable
4431 */
4432 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4433 indicatorTitle = typeof indicatorTitle === 'function' ||
4434 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
4435 OO.ui.resolveMsg( indicatorTitle ) : null;
4436
4437 if ( this.indicatorTitle !== indicatorTitle ) {
4438 this.indicatorTitle = indicatorTitle;
4439 if ( this.$indicator ) {
4440 if ( this.indicatorTitle !== null ) {
4441 this.$indicator.attr( 'title', indicatorTitle );
4442 } else {
4443 this.$indicator.removeAttr( 'title' );
4444 }
4445 }
4446 }
4447
4448 return this;
4449 };
4450
4451 /**
4452 * Get indicator name.
4453 *
4454 * @return {string} Symbolic name of indicator
4455 */
4456 OO.ui.IndicatorElement.prototype.getIndicator = function () {
4457 return this.indicator;
4458 };
4459
4460 /**
4461 * Get indicator title.
4462 *
4463 * @return {string} Indicator title text
4464 */
4465 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
4466 return this.indicatorTitle;
4467 };
4468
4469 /**
4470 * Element containing a label.
4471 *
4472 * @abstract
4473 * @class
4474 *
4475 * @constructor
4476 * @param {Object} [config] Configuration options
4477 * @cfg {jQuery} [$label] Label node, assigned to #$label, omit to use a generated `<span>`
4478 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
4479 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
4480 */
4481 OO.ui.LabelElement = function OoUiLabelElement( config ) {
4482 // Configuration initialization
4483 config = config || {};
4484
4485 // Properties
4486 this.$label = null;
4487 this.label = null;
4488 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
4489
4490 // Initialization
4491 this.setLabel( config.label || this.constructor.static.label );
4492 this.setLabelElement( config.$label || this.$( '<span>' ) );
4493 };
4494
4495 /* Setup */
4496
4497 OO.initClass( OO.ui.LabelElement );
4498
4499 /* Static Properties */
4500
4501 /**
4502 * Label.
4503 *
4504 * @static
4505 * @inheritable
4506 * @property {string|Function|null} Label text; a function that returns nodes or text; or null for
4507 * no label
4508 */
4509 OO.ui.LabelElement.static.label = null;
4510
4511 /* Methods */
4512
4513 /**
4514 * Set the label element.
4515 *
4516 * If an element is already set, it will be cleaned up before setting up the new element.
4517 *
4518 * @param {jQuery} $label Element to use as label
4519 */
4520 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
4521 if ( this.$label ) {
4522 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
4523 }
4524
4525 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
4526 this.setLabelContent( this.label );
4527 };
4528
4529 /**
4530 * Set the label.
4531 *
4532 * An empty string will result in the label being hidden. A string containing only whitespace will
4533 * be converted to a single `&nbsp;`.
4534 *
4535 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
4536 * text; or null for no label
4537 * @chainable
4538 */
4539 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
4540 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
4541 label = ( typeof label === 'string' && label.length ) || label instanceof jQuery ? label : null;
4542
4543 if ( this.label !== label ) {
4544 if ( this.$label ) {
4545 this.setLabelContent( label );
4546 }
4547 this.label = label;
4548 }
4549
4550 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
4551
4552 return this;
4553 };
4554
4555 /**
4556 * Get the label.
4557 *
4558 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
4559 * text; or null for no label
4560 */
4561 OO.ui.LabelElement.prototype.getLabel = function () {
4562 return this.label;
4563 };
4564
4565 /**
4566 * Fit the label.
4567 *
4568 * @chainable
4569 */
4570 OO.ui.LabelElement.prototype.fitLabel = function () {
4571 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
4572 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
4573 }
4574
4575 return this;
4576 };
4577
4578 /**
4579 * Set the content of the label.
4580 *
4581 * Do not call this method until after the label element has been set by #setLabelElement.
4582 *
4583 * @private
4584 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
4585 * text; or null for no label
4586 */
4587 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
4588 if ( typeof label === 'string' ) {
4589 if ( label.match( /^\s*$/ ) ) {
4590 // Convert whitespace only string to a single non-breaking space
4591 this.$label.html( '&nbsp;' );
4592 } else {
4593 this.$label.text( label );
4594 }
4595 } else if ( label instanceof jQuery ) {
4596 this.$label.empty().append( label );
4597 } else {
4598 this.$label.empty();
4599 }
4600 };
4601
4602 /**
4603 * Element containing an OO.ui.PopupWidget object.
4604 *
4605 * @abstract
4606 * @class
4607 *
4608 * @constructor
4609 * @param {Object} [config] Configuration options
4610 * @cfg {Object} [popup] Configuration to pass to popup
4611 * @cfg {boolean} [autoClose=true] Popup auto-closes when it loses focus
4612 */
4613 OO.ui.PopupElement = function OoUiPopupElement( config ) {
4614 // Configuration initialization
4615 config = config || {};
4616
4617 // Properties
4618 this.popup = new OO.ui.PopupWidget( $.extend(
4619 { autoClose: true },
4620 config.popup,
4621 { $: this.$, $autoCloseIgnore: this.$element }
4622 ) );
4623 };
4624
4625 /* Methods */
4626
4627 /**
4628 * Get popup.
4629 *
4630 * @return {OO.ui.PopupWidget} Popup widget
4631 */
4632 OO.ui.PopupElement.prototype.getPopup = function () {
4633 return this.popup;
4634 };
4635
4636 /**
4637 * Element with named flags that can be added, removed, listed and checked.
4638 *
4639 * A flag, when set, adds a CSS class on the `$element` by combining `oo-ui-flaggedElement-` with
4640 * the flag name. Flags are primarily useful for styling.
4641 *
4642 * @abstract
4643 * @class
4644 *
4645 * @constructor
4646 * @param {Object} [config] Configuration options
4647 * @cfg {string|string[]} [flags] Styling flags, e.g. 'primary', 'destructive' or 'constructive'
4648 * @cfg {jQuery} [$flagged] Flagged node, assigned to #$flagged, omit to use #$element
4649 */
4650 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
4651 // Configuration initialization
4652 config = config || {};
4653
4654 // Properties
4655 this.flags = {};
4656 this.$flagged = null;
4657
4658 // Initialization
4659 this.setFlags( config.flags );
4660 this.setFlaggedElement( config.$flagged || this.$element );
4661 };
4662
4663 /* Events */
4664
4665 /**
4666 * @event flag
4667 * @param {Object.<string,boolean>} changes Object keyed by flag name containing boolean
4668 * added/removed properties
4669 */
4670
4671 /* Methods */
4672
4673 /**
4674 * Set the flagged element.
4675 *
4676 * If an element is already set, it will be cleaned up before setting up the new element.
4677 *
4678 * @param {jQuery} $flagged Element to add flags to
4679 */
4680 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
4681 var classNames = Object.keys( this.flags ).map( function ( flag ) {
4682 return 'oo-ui-flaggedElement-' + flag;
4683 } ).join( ' ' );
4684
4685 if ( this.$flagged ) {
4686 this.$flagged.removeClass( classNames );
4687 }
4688
4689 this.$flagged = $flagged.addClass( classNames );
4690 };
4691
4692 /**
4693 * Check if a flag is set.
4694 *
4695 * @param {string} flag Name of flag
4696 * @return {boolean} Has flag
4697 */
4698 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
4699 return flag in this.flags;
4700 };
4701
4702 /**
4703 * Get the names of all flags set.
4704 *
4705 * @return {string[]} Flag names
4706 */
4707 OO.ui.FlaggedElement.prototype.getFlags = function () {
4708 return Object.keys( this.flags );
4709 };
4710
4711 /**
4712 * Clear all flags.
4713 *
4714 * @chainable
4715 * @fires flag
4716 */
4717 OO.ui.FlaggedElement.prototype.clearFlags = function () {
4718 var flag, className,
4719 changes = {},
4720 remove = [],
4721 classPrefix = 'oo-ui-flaggedElement-';
4722
4723 for ( flag in this.flags ) {
4724 className = classPrefix + flag;
4725 changes[flag] = false;
4726 delete this.flags[flag];
4727 remove.push( className );
4728 }
4729
4730 if ( this.$flagged ) {
4731 this.$flagged.removeClass( remove.join( ' ' ) );
4732 }
4733
4734 this.updateThemeClasses();
4735 this.emit( 'flag', changes );
4736
4737 return this;
4738 };
4739
4740 /**
4741 * Add one or more flags.
4742 *
4743 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
4744 * keyed by flag name containing boolean set/remove instructions.
4745 * @chainable
4746 * @fires flag
4747 */
4748 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
4749 var i, len, flag, className,
4750 changes = {},
4751 add = [],
4752 remove = [],
4753 classPrefix = 'oo-ui-flaggedElement-';
4754
4755 if ( typeof flags === 'string' ) {
4756 className = classPrefix + flags;
4757 // Set
4758 if ( !this.flags[flags] ) {
4759 this.flags[flags] = true;
4760 add.push( className );
4761 }
4762 } else if ( $.isArray( flags ) ) {
4763 for ( i = 0, len = flags.length; i < len; i++ ) {
4764 flag = flags[i];
4765 className = classPrefix + flag;
4766 // Set
4767 if ( !this.flags[flag] ) {
4768 changes[flag] = true;
4769 this.flags[flag] = true;
4770 add.push( className );
4771 }
4772 }
4773 } else if ( OO.isPlainObject( flags ) ) {
4774 for ( flag in flags ) {
4775 className = classPrefix + flag;
4776 if ( flags[flag] ) {
4777 // Set
4778 if ( !this.flags[flag] ) {
4779 changes[flag] = true;
4780 this.flags[flag] = true;
4781 add.push( className );
4782 }
4783 } else {
4784 // Remove
4785 if ( this.flags[flag] ) {
4786 changes[flag] = false;
4787 delete this.flags[flag];
4788 remove.push( className );
4789 }
4790 }
4791 }
4792 }
4793
4794 if ( this.$flagged ) {
4795 this.$flagged
4796 .addClass( add.join( ' ' ) )
4797 .removeClass( remove.join( ' ' ) );
4798 }
4799
4800 this.updateThemeClasses();
4801 this.emit( 'flag', changes );
4802
4803 return this;
4804 };
4805
4806 /**
4807 * Element with a title.
4808 *
4809 * Titles are rendered by the browser and are made visible when hovering the element. Titles are
4810 * not visible on touch devices.
4811 *
4812 * @abstract
4813 * @class
4814 *
4815 * @constructor
4816 * @param {Object} [config] Configuration options
4817 * @cfg {jQuery} [$titled] Titled node, assigned to #$titled, omit to use #$element
4818 * @cfg {string|Function} [title] Title text or a function that returns text. If not provided, the
4819 * static property 'title' is used.
4820 */
4821 OO.ui.TitledElement = function OoUiTitledElement( config ) {
4822 // Configuration initialization
4823 config = config || {};
4824
4825 // Properties
4826 this.$titled = null;
4827 this.title = null;
4828
4829 // Initialization
4830 this.setTitle( config.title || this.constructor.static.title );
4831 this.setTitledElement( config.$titled || this.$element );
4832 };
4833
4834 /* Setup */
4835
4836 OO.initClass( OO.ui.TitledElement );
4837
4838 /* Static Properties */
4839
4840 /**
4841 * Title.
4842 *
4843 * @static
4844 * @inheritable
4845 * @property {string|Function} Title text or a function that returns text
4846 */
4847 OO.ui.TitledElement.static.title = null;
4848
4849 /* Methods */
4850
4851 /**
4852 * Set the titled element.
4853 *
4854 * If an element is already set, it will be cleaned up before setting up the new element.
4855 *
4856 * @param {jQuery} $titled Element to set title on
4857 */
4858 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
4859 if ( this.$titled ) {
4860 this.$titled.removeAttr( 'title' );
4861 }
4862
4863 this.$titled = $titled;
4864 if ( this.title ) {
4865 this.$titled.attr( 'title', this.title );
4866 }
4867 };
4868
4869 /**
4870 * Set title.
4871 *
4872 * @param {string|Function|null} title Title text, a function that returns text or null for no title
4873 * @chainable
4874 */
4875 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
4876 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
4877
4878 if ( this.title !== title ) {
4879 if ( this.$titled ) {
4880 if ( title !== null ) {
4881 this.$titled.attr( 'title', title );
4882 } else {
4883 this.$titled.removeAttr( 'title' );
4884 }
4885 }
4886 this.title = title;
4887 }
4888
4889 return this;
4890 };
4891
4892 /**
4893 * Get title.
4894 *
4895 * @return {string} Title string
4896 */
4897 OO.ui.TitledElement.prototype.getTitle = function () {
4898 return this.title;
4899 };
4900
4901 /**
4902 * Element that can be automatically clipped to visible boundaries.
4903 *
4904 * Whenever the element's natural height changes, you have to call
4905 * #clip to make sure it's still clipping correctly.
4906 *
4907 * @abstract
4908 * @class
4909 *
4910 * @constructor
4911 * @param {Object} [config] Configuration options
4912 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
4913 */
4914 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
4915 // Configuration initialization
4916 config = config || {};
4917
4918 // Properties
4919 this.$clippable = null;
4920 this.clipping = false;
4921 this.clippedHorizontally = false;
4922 this.clippedVertically = false;
4923 this.$clippableContainer = null;
4924 this.$clippableScroller = null;
4925 this.$clippableWindow = null;
4926 this.idealWidth = null;
4927 this.idealHeight = null;
4928 this.onClippableContainerScrollHandler = this.clip.bind( this );
4929 this.onClippableWindowResizeHandler = this.clip.bind( this );
4930
4931 // Initialization
4932 this.setClippableElement( config.$clippable || this.$element );
4933 };
4934
4935 /* Methods */
4936
4937 /**
4938 * Set clippable element.
4939 *
4940 * If an element is already set, it will be cleaned up before setting up the new element.
4941 *
4942 * @param {jQuery} $clippable Element to make clippable
4943 */
4944 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
4945 if ( this.$clippable ) {
4946 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
4947 this.$clippable.css( { width: '', height: '' } );
4948 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
4949 this.$clippable.css( { overflowX: '', overflowY: '' } );
4950 }
4951
4952 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
4953 this.clip();
4954 };
4955
4956 /**
4957 * Toggle clipping.
4958 *
4959 * Do not turn clipping on until after the element is attached to the DOM and visible.
4960 *
4961 * @param {boolean} [clipping] Enable clipping, omit to toggle
4962 * @chainable
4963 */
4964 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
4965 clipping = clipping === undefined ? !this.clipping : !!clipping;
4966
4967 if ( this.clipping !== clipping ) {
4968 this.clipping = clipping;
4969 if ( clipping ) {
4970 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
4971 // If the clippable container is the body, we have to listen to scroll events and check
4972 // jQuery.scrollTop on the window because of browser inconsistencies
4973 this.$clippableScroller = this.$clippableContainer.is( 'body' ) ?
4974 this.$( OO.ui.Element.getWindow( this.$clippableContainer ) ) :
4975 this.$clippableContainer;
4976 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
4977 this.$clippableWindow = this.$( this.getElementWindow() )
4978 .on( 'resize', this.onClippableWindowResizeHandler );
4979 // Initial clip after visible
4980 this.clip();
4981 } else {
4982 this.$clippable.css( { width: '', height: '' } );
4983 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
4984 this.$clippable.css( { overflowX: '', overflowY: '' } );
4985
4986 this.$clippableContainer = null;
4987 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
4988 this.$clippableScroller = null;
4989 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
4990 this.$clippableWindow = null;
4991 }
4992 }
4993
4994 return this;
4995 };
4996
4997 /**
4998 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4999 *
5000 * @return {boolean} Element will be clipped to the visible area
5001 */
5002 OO.ui.ClippableElement.prototype.isClipping = function () {
5003 return this.clipping;
5004 };
5005
5006 /**
5007 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
5008 *
5009 * @return {boolean} Part of the element is being clipped
5010 */
5011 OO.ui.ClippableElement.prototype.isClipped = function () {
5012 return this.clippedHorizontally || this.clippedVertically;
5013 };
5014
5015 /**
5016 * Check if the right of the element is being clipped by the nearest scrollable container.
5017 *
5018 * @return {boolean} Part of the element is being clipped
5019 */
5020 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
5021 return this.clippedHorizontally;
5022 };
5023
5024 /**
5025 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5026 *
5027 * @return {boolean} Part of the element is being clipped
5028 */
5029 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
5030 return this.clippedVertically;
5031 };
5032
5033 /**
5034 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
5035 *
5036 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5037 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5038 */
5039 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
5040 this.idealWidth = width;
5041 this.idealHeight = height;
5042
5043 if ( !this.clipping ) {
5044 // Update dimensions
5045 this.$clippable.css( { width: width, height: height } );
5046 }
5047 // While clipping, idealWidth and idealHeight are not considered
5048 };
5049
5050 /**
5051 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
5052 * the element's natural height changes.
5053 *
5054 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5055 * overlapped by, the visible area of the nearest scrollable container.
5056 *
5057 * @chainable
5058 */
5059 OO.ui.ClippableElement.prototype.clip = function () {
5060 if ( !this.clipping ) {
5061 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
5062 return this;
5063 }
5064
5065 var buffer = 10,
5066 cOffset = this.$clippable.offset(),
5067 $container = this.$clippableContainer.is( 'body' ) ?
5068 this.$clippableWindow : this.$clippableContainer,
5069 ccOffset = $container.offset() || { top: 0, left: 0 },
5070 ccHeight = $container.innerHeight() - buffer,
5071 ccWidth = $container.innerWidth() - buffer,
5072 scrollTop = this.$clippableScroller.scrollTop(),
5073 scrollLeft = this.$clippableScroller.scrollLeft(),
5074 desiredWidth = ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
5075 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
5076 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
5077 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
5078 clipWidth = desiredWidth < naturalWidth,
5079 clipHeight = desiredHeight < naturalHeight;
5080
5081 if ( clipWidth ) {
5082 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
5083 } else {
5084 this.$clippable.css( 'width', this.idealWidth || '' );
5085 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
5086 this.$clippable.css( 'overflowX', '' );
5087 }
5088 if ( clipHeight ) {
5089 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
5090 } else {
5091 this.$clippable.css( 'height', this.idealHeight || '' );
5092 this.$clippable.height(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
5093 this.$clippable.css( 'overflowY', '' );
5094 }
5095
5096 this.clippedHorizontally = clipWidth;
5097 this.clippedVertically = clipHeight;
5098
5099 return this;
5100 };
5101
5102 /**
5103 * Generic toolbar tool.
5104 *
5105 * @abstract
5106 * @class
5107 * @extends OO.ui.Widget
5108 * @mixins OO.ui.IconElement
5109 * @mixins OO.ui.FlaggedElement
5110 *
5111 * @constructor
5112 * @param {OO.ui.ToolGroup} toolGroup
5113 * @param {Object} [config] Configuration options
5114 * @cfg {string|Function} [title] Title text or a function that returns text
5115 */
5116 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
5117 // Configuration initialization
5118 config = config || {};
5119
5120 // Parent constructor
5121 OO.ui.Tool.super.call( this, config );
5122
5123 // Mixin constructors
5124 OO.ui.IconElement.call( this, config );
5125 OO.ui.FlaggedElement.call( this, config );
5126
5127 // Properties
5128 this.toolGroup = toolGroup;
5129 this.toolbar = this.toolGroup.getToolbar();
5130 this.active = false;
5131 this.$title = this.$( '<span>' );
5132 this.$titleText = this.$( '<span>' );
5133 this.$accel = this.$( '<span>' );
5134 this.$link = this.$( '<a>' );
5135 this.title = null;
5136
5137 // Events
5138 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
5139
5140 // Initialization
5141 this.$titleText.addClass( 'oo-ui-tool-title-text' );
5142 this.$accel
5143 .addClass( 'oo-ui-tool-accel' )
5144 .prop( {
5145 // This may need to be changed if the key names are ever localized,
5146 // but for now they are essentially written in English
5147 dir: 'ltr',
5148 lang: 'en'
5149 } );
5150 this.$title
5151 .addClass( 'oo-ui-tool-title' )
5152 .append( this.$titleText, this.$accel );
5153 this.$link
5154 .addClass( 'oo-ui-tool-link' )
5155 .append( this.$icon, this.$title )
5156 .prop( 'tabIndex', 0 )
5157 .attr( 'role', 'button' );
5158 this.$element
5159 .data( 'oo-ui-tool', this )
5160 .addClass(
5161 'oo-ui-tool ' + 'oo-ui-tool-name-' +
5162 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
5163 )
5164 .append( this.$link );
5165 this.setTitle( config.title || this.constructor.static.title );
5166 };
5167
5168 /* Setup */
5169
5170 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
5171 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
5172 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
5173
5174 /* Events */
5175
5176 /**
5177 * @event select
5178 */
5179
5180 /* Static Properties */
5181
5182 /**
5183 * @static
5184 * @inheritdoc
5185 */
5186 OO.ui.Tool.static.tagName = 'span';
5187
5188 /**
5189 * Symbolic name of tool.
5190 *
5191 * @abstract
5192 * @static
5193 * @inheritable
5194 * @property {string}
5195 */
5196 OO.ui.Tool.static.name = '';
5197
5198 /**
5199 * Tool group.
5200 *
5201 * @abstract
5202 * @static
5203 * @inheritable
5204 * @property {string}
5205 */
5206 OO.ui.Tool.static.group = '';
5207
5208 /**
5209 * Tool title.
5210 *
5211 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
5212 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
5213 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
5214 * appended to the title if the tool is part of a bar tool group.
5215 *
5216 * @abstract
5217 * @static
5218 * @inheritable
5219 * @property {string|Function} Title text or a function that returns text
5220 */
5221 OO.ui.Tool.static.title = '';
5222
5223 /**
5224 * Tool can be automatically added to catch-all groups.
5225 *
5226 * @static
5227 * @inheritable
5228 * @property {boolean}
5229 */
5230 OO.ui.Tool.static.autoAddToCatchall = true;
5231
5232 /**
5233 * Tool can be automatically added to named groups.
5234 *
5235 * @static
5236 * @property {boolean}
5237 * @inheritable
5238 */
5239 OO.ui.Tool.static.autoAddToGroup = true;
5240
5241 /**
5242 * Check if this tool is compatible with given data.
5243 *
5244 * @static
5245 * @inheritable
5246 * @param {Mixed} data Data to check
5247 * @return {boolean} Tool can be used with data
5248 */
5249 OO.ui.Tool.static.isCompatibleWith = function () {
5250 return false;
5251 };
5252
5253 /* Methods */
5254
5255 /**
5256 * Handle the toolbar state being updated.
5257 *
5258 * This is an abstract method that must be overridden in a concrete subclass.
5259 *
5260 * @abstract
5261 */
5262 OO.ui.Tool.prototype.onUpdateState = function () {
5263 throw new Error(
5264 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
5265 );
5266 };
5267
5268 /**
5269 * Handle the tool being selected.
5270 *
5271 * This is an abstract method that must be overridden in a concrete subclass.
5272 *
5273 * @abstract
5274 */
5275 OO.ui.Tool.prototype.onSelect = function () {
5276 throw new Error(
5277 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
5278 );
5279 };
5280
5281 /**
5282 * Check if the button is active.
5283 *
5284 * @return {boolean} Button is active
5285 */
5286 OO.ui.Tool.prototype.isActive = function () {
5287 return this.active;
5288 };
5289
5290 /**
5291 * Make the button appear active or inactive.
5292 *
5293 * @param {boolean} state Make button appear active
5294 */
5295 OO.ui.Tool.prototype.setActive = function ( state ) {
5296 this.active = !!state;
5297 if ( this.active ) {
5298 this.$element.addClass( 'oo-ui-tool-active' );
5299 } else {
5300 this.$element.removeClass( 'oo-ui-tool-active' );
5301 }
5302 };
5303
5304 /**
5305 * Get the tool title.
5306 *
5307 * @param {string|Function} title Title text or a function that returns text
5308 * @chainable
5309 */
5310 OO.ui.Tool.prototype.setTitle = function ( title ) {
5311 this.title = OO.ui.resolveMsg( title );
5312 this.updateTitle();
5313 return this;
5314 };
5315
5316 /**
5317 * Get the tool title.
5318 *
5319 * @return {string} Title text
5320 */
5321 OO.ui.Tool.prototype.getTitle = function () {
5322 return this.title;
5323 };
5324
5325 /**
5326 * Get the tool's symbolic name.
5327 *
5328 * @return {string} Symbolic name of tool
5329 */
5330 OO.ui.Tool.prototype.getName = function () {
5331 return this.constructor.static.name;
5332 };
5333
5334 /**
5335 * Update the title.
5336 */
5337 OO.ui.Tool.prototype.updateTitle = function () {
5338 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
5339 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
5340 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
5341 tooltipParts = [];
5342
5343 this.$titleText.text( this.title );
5344 this.$accel.text( accel );
5345
5346 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
5347 tooltipParts.push( this.title );
5348 }
5349 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
5350 tooltipParts.push( accel );
5351 }
5352 if ( tooltipParts.length ) {
5353 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
5354 } else {
5355 this.$link.removeAttr( 'title' );
5356 }
5357 };
5358
5359 /**
5360 * Destroy tool.
5361 */
5362 OO.ui.Tool.prototype.destroy = function () {
5363 this.toolbar.disconnect( this );
5364 this.$element.remove();
5365 };
5366
5367 /**
5368 * Collection of tool groups.
5369 *
5370 * @class
5371 * @extends OO.ui.Element
5372 * @mixins OO.EventEmitter
5373 * @mixins OO.ui.GroupElement
5374 *
5375 * @constructor
5376 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
5377 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
5378 * @param {Object} [config] Configuration options
5379 * @cfg {boolean} [actions] Add an actions section opposite to the tools
5380 * @cfg {boolean} [shadow] Add a shadow below the toolbar
5381 */
5382 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
5383 // Configuration initialization
5384 config = config || {};
5385
5386 // Parent constructor
5387 OO.ui.Toolbar.super.call( this, config );
5388
5389 // Mixin constructors
5390 OO.EventEmitter.call( this );
5391 OO.ui.GroupElement.call( this, config );
5392
5393 // Properties
5394 this.toolFactory = toolFactory;
5395 this.toolGroupFactory = toolGroupFactory;
5396 this.groups = [];
5397 this.tools = {};
5398 this.$bar = this.$( '<div>' );
5399 this.$actions = this.$( '<div>' );
5400 this.initialized = false;
5401
5402 // Events
5403 this.$element
5404 .add( this.$bar ).add( this.$group ).add( this.$actions )
5405 .on( 'mousedown touchstart', this.onPointerDown.bind( this ) );
5406
5407 // Initialization
5408 this.$group.addClass( 'oo-ui-toolbar-tools' );
5409 if ( config.actions ) {
5410 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
5411 }
5412 this.$bar
5413 .addClass( 'oo-ui-toolbar-bar' )
5414 .append( this.$group, '<div style="clear:both"></div>' );
5415 if ( config.shadow ) {
5416 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
5417 }
5418 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
5419 };
5420
5421 /* Setup */
5422
5423 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
5424 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
5425 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
5426
5427 /* Methods */
5428
5429 /**
5430 * Get the tool factory.
5431 *
5432 * @return {OO.ui.ToolFactory} Tool factory
5433 */
5434 OO.ui.Toolbar.prototype.getToolFactory = function () {
5435 return this.toolFactory;
5436 };
5437
5438 /**
5439 * Get the tool group factory.
5440 *
5441 * @return {OO.Factory} Tool group factory
5442 */
5443 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
5444 return this.toolGroupFactory;
5445 };
5446
5447 /**
5448 * Handles mouse down events.
5449 *
5450 * @param {jQuery.Event} e Mouse down event
5451 */
5452 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
5453 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
5454 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
5455 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[0] === $closestWidgetToToolbar[0] ) {
5456 return false;
5457 }
5458 };
5459
5460 /**
5461 * Sets up handles and preloads required information for the toolbar to work.
5462 * This must be called immediately after it is attached to a visible document.
5463 */
5464 OO.ui.Toolbar.prototype.initialize = function () {
5465 this.initialized = true;
5466 };
5467
5468 /**
5469 * Setup toolbar.
5470 *
5471 * Tools can be specified in the following ways:
5472 *
5473 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
5474 * - All tools in a group: `{ group: 'group-name' }`
5475 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
5476 *
5477 * @param {Object.<string,Array>} groups List of tool group configurations
5478 * @param {Array|string} [groups.include] Tools to include
5479 * @param {Array|string} [groups.exclude] Tools to exclude
5480 * @param {Array|string} [groups.promote] Tools to promote to the beginning
5481 * @param {Array|string} [groups.demote] Tools to demote to the end
5482 */
5483 OO.ui.Toolbar.prototype.setup = function ( groups ) {
5484 var i, len, type, group,
5485 items = [],
5486 defaultType = 'bar';
5487
5488 // Cleanup previous groups
5489 this.reset();
5490
5491 // Build out new groups
5492 for ( i = 0, len = groups.length; i < len; i++ ) {
5493 group = groups[i];
5494 if ( group.include === '*' ) {
5495 // Apply defaults to catch-all groups
5496 if ( group.type === undefined ) {
5497 group.type = 'list';
5498 }
5499 if ( group.label === undefined ) {
5500 group.label = OO.ui.msg( 'ooui-toolbar-more' );
5501 }
5502 }
5503 // Check type has been registered
5504 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
5505 items.push(
5506 this.getToolGroupFactory().create( type, this, $.extend( { $: this.$ }, group ) )
5507 );
5508 }
5509 this.addItems( items );
5510 };
5511
5512 /**
5513 * Remove all tools and groups from the toolbar.
5514 */
5515 OO.ui.Toolbar.prototype.reset = function () {
5516 var i, len;
5517
5518 this.groups = [];
5519 this.tools = {};
5520 for ( i = 0, len = this.items.length; i < len; i++ ) {
5521 this.items[i].destroy();
5522 }
5523 this.clearItems();
5524 };
5525
5526 /**
5527 * Destroys toolbar, removing event handlers and DOM elements.
5528 *
5529 * Call this whenever you are done using a toolbar.
5530 */
5531 OO.ui.Toolbar.prototype.destroy = function () {
5532 this.reset();
5533 this.$element.remove();
5534 };
5535
5536 /**
5537 * Check if tool has not been used yet.
5538 *
5539 * @param {string} name Symbolic name of tool
5540 * @return {boolean} Tool is available
5541 */
5542 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
5543 return !this.tools[name];
5544 };
5545
5546 /**
5547 * Prevent tool from being used again.
5548 *
5549 * @param {OO.ui.Tool} tool Tool to reserve
5550 */
5551 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
5552 this.tools[tool.getName()] = tool;
5553 };
5554
5555 /**
5556 * Allow tool to be used again.
5557 *
5558 * @param {OO.ui.Tool} tool Tool to release
5559 */
5560 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
5561 delete this.tools[tool.getName()];
5562 };
5563
5564 /**
5565 * Get accelerator label for tool.
5566 *
5567 * This is a stub that should be overridden to provide access to accelerator information.
5568 *
5569 * @param {string} name Symbolic name of tool
5570 * @return {string|undefined} Tool accelerator label if available
5571 */
5572 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
5573 return undefined;
5574 };
5575
5576 /**
5577 * Collection of tools.
5578 *
5579 * Tools can be specified in the following ways:
5580 *
5581 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
5582 * - All tools in a group: `{ group: 'group-name' }`
5583 * - All tools: `'*'`
5584 *
5585 * @abstract
5586 * @class
5587 * @extends OO.ui.Widget
5588 * @mixins OO.ui.GroupElement
5589 *
5590 * @constructor
5591 * @param {OO.ui.Toolbar} toolbar
5592 * @param {Object} [config] Configuration options
5593 * @cfg {Array|string} [include=[]] List of tools to include
5594 * @cfg {Array|string} [exclude=[]] List of tools to exclude
5595 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
5596 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
5597 */
5598 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
5599 // Configuration initialization
5600 config = config || {};
5601
5602 // Parent constructor
5603 OO.ui.ToolGroup.super.call( this, config );
5604
5605 // Mixin constructors
5606 OO.ui.GroupElement.call( this, config );
5607
5608 // Properties
5609 this.toolbar = toolbar;
5610 this.tools = {};
5611 this.pressed = null;
5612 this.autoDisabled = false;
5613 this.include = config.include || [];
5614 this.exclude = config.exclude || [];
5615 this.promote = config.promote || [];
5616 this.demote = config.demote || [];
5617 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
5618
5619 // Events
5620 this.$element.on( {
5621 'mousedown touchstart': this.onPointerDown.bind( this ),
5622 'mouseup touchend': this.onPointerUp.bind( this ),
5623 mouseover: this.onMouseOver.bind( this ),
5624 mouseout: this.onMouseOut.bind( this )
5625 } );
5626 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
5627 this.aggregate( { disable: 'itemDisable' } );
5628 this.connect( this, { itemDisable: 'updateDisabled' } );
5629
5630 // Initialization
5631 this.$group.addClass( 'oo-ui-toolGroup-tools' );
5632 this.$element
5633 .addClass( 'oo-ui-toolGroup' )
5634 .append( this.$group );
5635 this.populate();
5636 };
5637
5638 /* Setup */
5639
5640 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
5641 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
5642
5643 /* Events */
5644
5645 /**
5646 * @event update
5647 */
5648
5649 /* Static Properties */
5650
5651 /**
5652 * Show labels in tooltips.
5653 *
5654 * @static
5655 * @inheritable
5656 * @property {boolean}
5657 */
5658 OO.ui.ToolGroup.static.titleTooltips = false;
5659
5660 /**
5661 * Show acceleration labels in tooltips.
5662 *
5663 * @static
5664 * @inheritable
5665 * @property {boolean}
5666 */
5667 OO.ui.ToolGroup.static.accelTooltips = false;
5668
5669 /**
5670 * Automatically disable the toolgroup when all tools are disabled
5671 *
5672 * @static
5673 * @inheritable
5674 * @property {boolean}
5675 */
5676 OO.ui.ToolGroup.static.autoDisable = true;
5677
5678 /* Methods */
5679
5680 /**
5681 * @inheritdoc
5682 */
5683 OO.ui.ToolGroup.prototype.isDisabled = function () {
5684 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
5685 };
5686
5687 /**
5688 * @inheritdoc
5689 */
5690 OO.ui.ToolGroup.prototype.updateDisabled = function () {
5691 var i, item, allDisabled = true;
5692
5693 if ( this.constructor.static.autoDisable ) {
5694 for ( i = this.items.length - 1; i >= 0; i-- ) {
5695 item = this.items[i];
5696 if ( !item.isDisabled() ) {
5697 allDisabled = false;
5698 break;
5699 }
5700 }
5701 this.autoDisabled = allDisabled;
5702 }
5703 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
5704 };
5705
5706 /**
5707 * Handle mouse down events.
5708 *
5709 * @param {jQuery.Event} e Mouse down event
5710 */
5711 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
5712 // e.which is 0 for touch events, 1 for left mouse button
5713 if ( !this.isDisabled() && e.which <= 1 ) {
5714 this.pressed = this.getTargetTool( e );
5715 if ( this.pressed ) {
5716 this.pressed.setActive( true );
5717 this.getElementDocument().addEventListener(
5718 'mouseup', this.onCapturedMouseUpHandler, true
5719 );
5720 }
5721 }
5722 return false;
5723 };
5724
5725 /**
5726 * Handle captured mouse up events.
5727 *
5728 * @param {Event} e Mouse up event
5729 */
5730 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
5731 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
5732 // onPointerUp may be called a second time, depending on where the mouse is when the button is
5733 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
5734 this.onPointerUp( e );
5735 };
5736
5737 /**
5738 * Handle mouse up events.
5739 *
5740 * @param {jQuery.Event} e Mouse up event
5741 */
5742 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
5743 var tool = this.getTargetTool( e );
5744
5745 // e.which is 0 for touch events, 1 for left mouse button
5746 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === tool ) {
5747 this.pressed.onSelect();
5748 }
5749
5750 this.pressed = null;
5751 return false;
5752 };
5753
5754 /**
5755 * Handle mouse over events.
5756 *
5757 * @param {jQuery.Event} e Mouse over event
5758 */
5759 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
5760 var tool = this.getTargetTool( e );
5761
5762 if ( this.pressed && this.pressed === tool ) {
5763 this.pressed.setActive( true );
5764 }
5765 };
5766
5767 /**
5768 * Handle mouse out events.
5769 *
5770 * @param {jQuery.Event} e Mouse out event
5771 */
5772 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
5773 var tool = this.getTargetTool( e );
5774
5775 if ( this.pressed && this.pressed === tool ) {
5776 this.pressed.setActive( false );
5777 }
5778 };
5779
5780 /**
5781 * Get the closest tool to a jQuery.Event.
5782 *
5783 * Only tool links are considered, which prevents other elements in the tool such as popups from
5784 * triggering tool group interactions.
5785 *
5786 * @private
5787 * @param {jQuery.Event} e
5788 * @return {OO.ui.Tool|null} Tool, `null` if none was found
5789 */
5790 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
5791 var tool,
5792 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
5793
5794 if ( $item.length ) {
5795 tool = $item.parent().data( 'oo-ui-tool' );
5796 }
5797
5798 return tool && !tool.isDisabled() ? tool : null;
5799 };
5800
5801 /**
5802 * Handle tool registry register events.
5803 *
5804 * If a tool is registered after the group is created, we must repopulate the list to account for:
5805 *
5806 * - a tool being added that may be included
5807 * - a tool already included being overridden
5808 *
5809 * @param {string} name Symbolic name of tool
5810 */
5811 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
5812 this.populate();
5813 };
5814
5815 /**
5816 * Get the toolbar this group is in.
5817 *
5818 * @return {OO.ui.Toolbar} Toolbar of group
5819 */
5820 OO.ui.ToolGroup.prototype.getToolbar = function () {
5821 return this.toolbar;
5822 };
5823
5824 /**
5825 * Add and remove tools based on configuration.
5826 */
5827 OO.ui.ToolGroup.prototype.populate = function () {
5828 var i, len, name, tool,
5829 toolFactory = this.toolbar.getToolFactory(),
5830 names = {},
5831 add = [],
5832 remove = [],
5833 list = this.toolbar.getToolFactory().getTools(
5834 this.include, this.exclude, this.promote, this.demote
5835 );
5836
5837 // Build a list of needed tools
5838 for ( i = 0, len = list.length; i < len; i++ ) {
5839 name = list[i];
5840 if (
5841 // Tool exists
5842 toolFactory.lookup( name ) &&
5843 // Tool is available or is already in this group
5844 ( this.toolbar.isToolAvailable( name ) || this.tools[name] )
5845 ) {
5846 tool = this.tools[name];
5847 if ( !tool ) {
5848 // Auto-initialize tools on first use
5849 this.tools[name] = tool = toolFactory.create( name, this );
5850 tool.updateTitle();
5851 }
5852 this.toolbar.reserveTool( tool );
5853 add.push( tool );
5854 names[name] = true;
5855 }
5856 }
5857 // Remove tools that are no longer needed
5858 for ( name in this.tools ) {
5859 if ( !names[name] ) {
5860 this.tools[name].destroy();
5861 this.toolbar.releaseTool( this.tools[name] );
5862 remove.push( this.tools[name] );
5863 delete this.tools[name];
5864 }
5865 }
5866 if ( remove.length ) {
5867 this.removeItems( remove );
5868 }
5869 // Update emptiness state
5870 if ( add.length ) {
5871 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
5872 } else {
5873 this.$element.addClass( 'oo-ui-toolGroup-empty' );
5874 }
5875 // Re-add tools (moving existing ones to new locations)
5876 this.addItems( add );
5877 // Disabled state may depend on items
5878 this.updateDisabled();
5879 };
5880
5881 /**
5882 * Destroy tool group.
5883 */
5884 OO.ui.ToolGroup.prototype.destroy = function () {
5885 var name;
5886
5887 this.clearItems();
5888 this.toolbar.getToolFactory().disconnect( this );
5889 for ( name in this.tools ) {
5890 this.toolbar.releaseTool( this.tools[name] );
5891 this.tools[name].disconnect( this ).destroy();
5892 delete this.tools[name];
5893 }
5894 this.$element.remove();
5895 };
5896
5897 /**
5898 * Dialog for showing a message.
5899 *
5900 * User interface:
5901 * - Registers two actions by default (safe and primary).
5902 * - Renders action widgets in the footer.
5903 *
5904 * @class
5905 * @extends OO.ui.Dialog
5906 *
5907 * @constructor
5908 * @param {Object} [config] Configuration options
5909 */
5910 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
5911 // Parent constructor
5912 OO.ui.MessageDialog.super.call( this, config );
5913
5914 // Properties
5915 this.verticalActionLayout = null;
5916
5917 // Initialization
5918 this.$element.addClass( 'oo-ui-messageDialog' );
5919 };
5920
5921 /* Inheritance */
5922
5923 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
5924
5925 /* Static Properties */
5926
5927 OO.ui.MessageDialog.static.name = 'message';
5928
5929 OO.ui.MessageDialog.static.size = 'small';
5930
5931 OO.ui.MessageDialog.static.verbose = false;
5932
5933 /**
5934 * Dialog title.
5935 *
5936 * A confirmation dialog's title should describe what the progressive action will do. An alert
5937 * dialog's title should describe what event occurred.
5938 *
5939 * @static
5940 * inheritable
5941 * @property {jQuery|string|Function|null}
5942 */
5943 OO.ui.MessageDialog.static.title = null;
5944
5945 /**
5946 * A confirmation dialog's message should describe the consequences of the progressive action. An
5947 * alert dialog's message should describe why the event occurred.
5948 *
5949 * @static
5950 * inheritable
5951 * @property {jQuery|string|Function|null}
5952 */
5953 OO.ui.MessageDialog.static.message = null;
5954
5955 OO.ui.MessageDialog.static.actions = [
5956 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
5957 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
5958 ];
5959
5960 /* Methods */
5961
5962 /**
5963 * @inheritdoc
5964 */
5965 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
5966 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
5967
5968 // Events
5969 this.manager.connect( this, {
5970 resize: 'onResize'
5971 } );
5972
5973 return this;
5974 };
5975
5976 /**
5977 * @inheritdoc
5978 */
5979 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
5980 this.fitActions();
5981 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
5982 };
5983
5984 /**
5985 * Handle window resized events.
5986 */
5987 OO.ui.MessageDialog.prototype.onResize = function () {
5988 var dialog = this;
5989 dialog.fitActions();
5990 // Wait for CSS transition to finish and do it again :(
5991 setTimeout( function () {
5992 dialog.fitActions();
5993 }, 300 );
5994 };
5995
5996 /**
5997 * Toggle action layout between vertical and horizontal.
5998 *
5999 * @param {boolean} [value] Layout actions vertically, omit to toggle
6000 * @chainable
6001 */
6002 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
6003 value = value === undefined ? !this.verticalActionLayout : !!value;
6004
6005 if ( value !== this.verticalActionLayout ) {
6006 this.verticalActionLayout = value;
6007 this.$actions
6008 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
6009 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
6010 }
6011
6012 return this;
6013 };
6014
6015 /**
6016 * @inheritdoc
6017 */
6018 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
6019 if ( action ) {
6020 return new OO.ui.Process( function () {
6021 this.close( { action: action } );
6022 }, this );
6023 }
6024 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
6025 };
6026
6027 /**
6028 * @inheritdoc
6029 *
6030 * @param {Object} [data] Dialog opening data
6031 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
6032 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
6033 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
6034 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
6035 * action item
6036 */
6037 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
6038 data = data || {};
6039
6040 // Parent method
6041 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
6042 .next( function () {
6043 this.title.setLabel(
6044 data.title !== undefined ? data.title : this.constructor.static.title
6045 );
6046 this.message.setLabel(
6047 data.message !== undefined ? data.message : this.constructor.static.message
6048 );
6049 this.message.$element.toggleClass(
6050 'oo-ui-messageDialog-message-verbose',
6051 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
6052 );
6053 }, this );
6054 };
6055
6056 /**
6057 * @inheritdoc
6058 */
6059 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
6060 var bodyHeight, oldOverflow,
6061 $scrollable = this.container.$element;
6062
6063 oldOverflow = $scrollable[0].style.overflow;
6064 $scrollable[0].style.overflow = 'hidden';
6065
6066 // Force… ugh… something to happen
6067 $scrollable.contents().hide();
6068 $scrollable.height();
6069 $scrollable.contents().show();
6070
6071 bodyHeight = Math.round( this.text.$element.outerHeight( true ) );
6072 $scrollable[0].style.overflow = oldOverflow;
6073
6074 return bodyHeight;
6075 };
6076
6077 /**
6078 * @inheritdoc
6079 */
6080 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
6081 var $scrollable = this.container.$element;
6082 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
6083
6084 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
6085 // Need to do it after transition completes (250ms), add 50ms just in case.
6086 setTimeout( function () {
6087 var oldOverflow = $scrollable[0].style.overflow;
6088 $scrollable[0].style.overflow = 'hidden';
6089
6090 // Force… ugh… something to happen
6091 $scrollable.contents().hide();
6092 $scrollable.height();
6093 $scrollable.contents().show();
6094
6095 $scrollable[0].style.overflow = oldOverflow;
6096 }, 300 );
6097
6098 return this;
6099 };
6100
6101 /**
6102 * @inheritdoc
6103 */
6104 OO.ui.MessageDialog.prototype.initialize = function () {
6105 // Parent method
6106 OO.ui.MessageDialog.super.prototype.initialize.call( this );
6107
6108 // Properties
6109 this.$actions = this.$( '<div>' );
6110 this.container = new OO.ui.PanelLayout( {
6111 $: this.$, scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
6112 } );
6113 this.text = new OO.ui.PanelLayout( {
6114 $: this.$, padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
6115 } );
6116 this.message = new OO.ui.LabelWidget( {
6117 $: this.$, classes: [ 'oo-ui-messageDialog-message' ]
6118 } );
6119
6120 // Initialization
6121 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
6122 this.$content.addClass( 'oo-ui-messageDialog-content' );
6123 this.container.$element.append( this.text.$element );
6124 this.text.$element.append( this.title.$element, this.message.$element );
6125 this.$body.append( this.container.$element );
6126 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
6127 this.$foot.append( this.$actions );
6128 };
6129
6130 /**
6131 * @inheritdoc
6132 */
6133 OO.ui.MessageDialog.prototype.attachActions = function () {
6134 var i, len, other, special, others;
6135
6136 // Parent method
6137 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
6138
6139 special = this.actions.getSpecial();
6140 others = this.actions.getOthers();
6141 if ( special.safe ) {
6142 this.$actions.append( special.safe.$element );
6143 special.safe.toggleFramed( false );
6144 }
6145 if ( others.length ) {
6146 for ( i = 0, len = others.length; i < len; i++ ) {
6147 other = others[i];
6148 this.$actions.append( other.$element );
6149 other.toggleFramed( false );
6150 }
6151 }
6152 if ( special.primary ) {
6153 this.$actions.append( special.primary.$element );
6154 special.primary.toggleFramed( false );
6155 }
6156
6157 if ( !this.isOpening() ) {
6158 // If the dialog is currently opening, this will be called automatically soon.
6159 // This also calls #fitActions.
6160 this.manager.updateWindowSize( this );
6161 }
6162 };
6163
6164 /**
6165 * Fit action actions into columns or rows.
6166 *
6167 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
6168 */
6169 OO.ui.MessageDialog.prototype.fitActions = function () {
6170 var i, len, action,
6171 previous = this.verticalActionLayout,
6172 actions = this.actions.get();
6173
6174 // Detect clipping
6175 this.toggleVerticalActionLayout( false );
6176 for ( i = 0, len = actions.length; i < len; i++ ) {
6177 action = actions[i];
6178 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
6179 this.toggleVerticalActionLayout( true );
6180 break;
6181 }
6182 }
6183
6184 if ( this.verticalActionLayout !== previous ) {
6185 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
6186 // We changed the layout, window height might need to be updated.
6187 this.manager.updateWindowSize( this );
6188 }
6189 };
6190
6191 /**
6192 * Navigation dialog window.
6193 *
6194 * Logic:
6195 * - Show and hide errors.
6196 * - Retry an action.
6197 *
6198 * User interface:
6199 * - Renders header with dialog title and one action widget on either side
6200 * (a 'safe' button on the left, and a 'primary' button on the right, both of
6201 * which close the dialog).
6202 * - Displays any action widgets in the footer (none by default).
6203 * - Ability to dismiss errors.
6204 *
6205 * Subclass responsibilities:
6206 * - Register a 'safe' action.
6207 * - Register a 'primary' action.
6208 * - Add content to the dialog.
6209 *
6210 * @abstract
6211 * @class
6212 * @extends OO.ui.Dialog
6213 *
6214 * @constructor
6215 * @param {Object} [config] Configuration options
6216 */
6217 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
6218 // Parent constructor
6219 OO.ui.ProcessDialog.super.call( this, config );
6220
6221 // Initialization
6222 this.$element.addClass( 'oo-ui-processDialog' );
6223 };
6224
6225 /* Setup */
6226
6227 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
6228
6229 /* Methods */
6230
6231 /**
6232 * Handle dismiss button click events.
6233 *
6234 * Hides errors.
6235 */
6236 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
6237 this.hideErrors();
6238 };
6239
6240 /**
6241 * Handle retry button click events.
6242 *
6243 * Hides errors and then tries again.
6244 */
6245 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
6246 this.hideErrors();
6247 this.executeAction( this.currentAction.getAction() );
6248 };
6249
6250 /**
6251 * @inheritdoc
6252 */
6253 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
6254 if ( this.actions.isSpecial( action ) ) {
6255 this.fitLabel();
6256 }
6257 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
6258 };
6259
6260 /**
6261 * @inheritdoc
6262 */
6263 OO.ui.ProcessDialog.prototype.initialize = function () {
6264 // Parent method
6265 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
6266
6267 // Properties
6268 this.$navigation = this.$( '<div>' );
6269 this.$location = this.$( '<div>' );
6270 this.$safeActions = this.$( '<div>' );
6271 this.$primaryActions = this.$( '<div>' );
6272 this.$otherActions = this.$( '<div>' );
6273 this.dismissButton = new OO.ui.ButtonWidget( {
6274 $: this.$,
6275 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
6276 } );
6277 this.retryButton = new OO.ui.ButtonWidget( { $: this.$ } );
6278 this.$errors = this.$( '<div>' );
6279 this.$errorsTitle = this.$( '<div>' );
6280
6281 // Events
6282 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
6283 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
6284
6285 // Initialization
6286 this.title.$element.addClass( 'oo-ui-processDialog-title' );
6287 this.$location
6288 .append( this.title.$element )
6289 .addClass( 'oo-ui-processDialog-location' );
6290 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
6291 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
6292 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
6293 this.$errorsTitle
6294 .addClass( 'oo-ui-processDialog-errors-title' )
6295 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
6296 this.$errors
6297 .addClass( 'oo-ui-processDialog-errors' )
6298 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
6299 this.$content
6300 .addClass( 'oo-ui-processDialog-content' )
6301 .append( this.$errors );
6302 this.$navigation
6303 .addClass( 'oo-ui-processDialog-navigation' )
6304 .append( this.$safeActions, this.$location, this.$primaryActions );
6305 this.$head.append( this.$navigation );
6306 this.$foot.append( this.$otherActions );
6307 };
6308
6309 /**
6310 * @inheritdoc
6311 */
6312 OO.ui.ProcessDialog.prototype.attachActions = function () {
6313 var i, len, other, special, others;
6314
6315 // Parent method
6316 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
6317
6318 special = this.actions.getSpecial();
6319 others = this.actions.getOthers();
6320 if ( special.primary ) {
6321 this.$primaryActions.append( special.primary.$element );
6322 special.primary.toggleFramed( true );
6323 }
6324 if ( others.length ) {
6325 for ( i = 0, len = others.length; i < len; i++ ) {
6326 other = others[i];
6327 this.$otherActions.append( other.$element );
6328 other.toggleFramed( true );
6329 }
6330 }
6331 if ( special.safe ) {
6332 this.$safeActions.append( special.safe.$element );
6333 special.safe.toggleFramed( true );
6334 }
6335
6336 this.fitLabel();
6337 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
6338 };
6339
6340 /**
6341 * @inheritdoc
6342 */
6343 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
6344 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
6345 .fail( this.showErrors.bind( this ) );
6346 };
6347
6348 /**
6349 * Fit label between actions.
6350 *
6351 * @chainable
6352 */
6353 OO.ui.ProcessDialog.prototype.fitLabel = function () {
6354 var width = Math.max(
6355 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
6356 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
6357 );
6358 this.$location.css( { paddingLeft: width, paddingRight: width } );
6359
6360 return this;
6361 };
6362
6363 /**
6364 * Handle errors that occurred during accept or reject processes.
6365 *
6366 * @param {OO.ui.Error[]} errors Errors to be handled
6367 */
6368 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
6369 var i, len, $item,
6370 items = [],
6371 recoverable = true,
6372 warning = false;
6373
6374 for ( i = 0, len = errors.length; i < len; i++ ) {
6375 if ( !errors[i].isRecoverable() ) {
6376 recoverable = false;
6377 }
6378 if ( errors[i].isWarning() ) {
6379 warning = true;
6380 }
6381 $item = this.$( '<div>' )
6382 .addClass( 'oo-ui-processDialog-error' )
6383 .append( errors[i].getMessage() );
6384 items.push( $item[0] );
6385 }
6386 this.$errorItems = this.$( items );
6387 if ( recoverable ) {
6388 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
6389 } else {
6390 this.currentAction.setDisabled( true );
6391 }
6392 if ( warning ) {
6393 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
6394 } else {
6395 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
6396 }
6397 this.retryButton.toggle( recoverable );
6398 this.$errorsTitle.after( this.$errorItems );
6399 this.$errors.show().scrollTop( 0 );
6400 };
6401
6402 /**
6403 * Hide errors.
6404 */
6405 OO.ui.ProcessDialog.prototype.hideErrors = function () {
6406 this.$errors.hide();
6407 this.$errorItems.remove();
6408 this.$errorItems = null;
6409 };
6410
6411 /**
6412 * Layout containing a series of pages.
6413 *
6414 * @class
6415 * @extends OO.ui.Layout
6416 *
6417 * @constructor
6418 * @param {Object} [config] Configuration options
6419 * @cfg {boolean} [continuous=false] Show all pages, one after another
6420 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
6421 * @cfg {boolean} [outlined=false] Show an outline
6422 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
6423 */
6424 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
6425 // Configuration initialization
6426 config = config || {};
6427
6428 // Parent constructor
6429 OO.ui.BookletLayout.super.call( this, config );
6430
6431 // Properties
6432 this.currentPageName = null;
6433 this.pages = {};
6434 this.ignoreFocus = false;
6435 this.stackLayout = new OO.ui.StackLayout( { $: this.$, continuous: !!config.continuous } );
6436 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
6437 this.outlineVisible = false;
6438 this.outlined = !!config.outlined;
6439 if ( this.outlined ) {
6440 this.editable = !!config.editable;
6441 this.outlineControlsWidget = null;
6442 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget( { $: this.$ } );
6443 this.outlinePanel = new OO.ui.PanelLayout( { $: this.$, scrollable: true } );
6444 this.gridLayout = new OO.ui.GridLayout(
6445 [ this.outlinePanel, this.stackLayout ],
6446 { $: this.$, widths: [ 1, 2 ] }
6447 );
6448 this.outlineVisible = true;
6449 if ( this.editable ) {
6450 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
6451 this.outlineSelectWidget, { $: this.$ }
6452 );
6453 }
6454 }
6455
6456 // Events
6457 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
6458 if ( this.outlined ) {
6459 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
6460 }
6461 if ( this.autoFocus ) {
6462 // Event 'focus' does not bubble, but 'focusin' does
6463 this.stackLayout.onDOMEvent( 'focusin', this.onStackLayoutFocus.bind( this ) );
6464 }
6465
6466 // Initialization
6467 this.$element.addClass( 'oo-ui-bookletLayout' );
6468 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
6469 if ( this.outlined ) {
6470 this.outlinePanel.$element
6471 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
6472 .append( this.outlineSelectWidget.$element );
6473 if ( this.editable ) {
6474 this.outlinePanel.$element
6475 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
6476 .append( this.outlineControlsWidget.$element );
6477 }
6478 this.$element.append( this.gridLayout.$element );
6479 } else {
6480 this.$element.append( this.stackLayout.$element );
6481 }
6482 };
6483
6484 /* Setup */
6485
6486 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
6487
6488 /* Events */
6489
6490 /**
6491 * @event set
6492 * @param {OO.ui.PageLayout} page Current page
6493 */
6494
6495 /**
6496 * @event add
6497 * @param {OO.ui.PageLayout[]} page Added pages
6498 * @param {number} index Index pages were added at
6499 */
6500
6501 /**
6502 * @event remove
6503 * @param {OO.ui.PageLayout[]} pages Removed pages
6504 */
6505
6506 /* Methods */
6507
6508 /**
6509 * Handle stack layout focus.
6510 *
6511 * @param {jQuery.Event} e Focusin event
6512 */
6513 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
6514 var name, $target;
6515
6516 // Find the page that an element was focused within
6517 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
6518 for ( name in this.pages ) {
6519 // Check for page match, exclude current page to find only page changes
6520 if ( this.pages[name].$element[0] === $target[0] && name !== this.currentPageName ) {
6521 this.setPage( name );
6522 break;
6523 }
6524 }
6525 };
6526
6527 /**
6528 * Handle stack layout set events.
6529 *
6530 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
6531 */
6532 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
6533 var layout = this;
6534 if ( page ) {
6535 page.scrollElementIntoView( { complete: function () {
6536 if ( layout.autoFocus ) {
6537 layout.focus();
6538 }
6539 } } );
6540 }
6541 };
6542
6543 /**
6544 * Focus the first input in the current page.
6545 *
6546 * If no page is selected, the first selectable page will be selected.
6547 * If the focus is already in an element on the current page, nothing will happen.
6548 */
6549 OO.ui.BookletLayout.prototype.focus = function () {
6550 var $input, page = this.stackLayout.getCurrentItem();
6551 if ( !page && this.outlined ) {
6552 this.selectFirstSelectablePage();
6553 page = this.stackLayout.getCurrentItem();
6554 if ( !page ) {
6555 return;
6556 }
6557 }
6558 // Only change the focus if is not already in the current page
6559 if ( !page.$element.find( ':focus' ).length ) {
6560 $input = page.$element.find( ':input:first' );
6561 if ( $input.length ) {
6562 $input[0].focus();
6563 }
6564 }
6565 };
6566
6567 /**
6568 * Handle outline widget select events.
6569 *
6570 * @param {OO.ui.OptionWidget|null} item Selected item
6571 */
6572 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
6573 if ( item ) {
6574 this.setPage( item.getData() );
6575 }
6576 };
6577
6578 /**
6579 * Check if booklet has an outline.
6580 *
6581 * @return {boolean}
6582 */
6583 OO.ui.BookletLayout.prototype.isOutlined = function () {
6584 return this.outlined;
6585 };
6586
6587 /**
6588 * Check if booklet has editing controls.
6589 *
6590 * @return {boolean}
6591 */
6592 OO.ui.BookletLayout.prototype.isEditable = function () {
6593 return this.editable;
6594 };
6595
6596 /**
6597 * Check if booklet has a visible outline.
6598 *
6599 * @return {boolean}
6600 */
6601 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
6602 return this.outlined && this.outlineVisible;
6603 };
6604
6605 /**
6606 * Hide or show the outline.
6607 *
6608 * @param {boolean} [show] Show outline, omit to invert current state
6609 * @chainable
6610 */
6611 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
6612 if ( this.outlined ) {
6613 show = show === undefined ? !this.outlineVisible : !!show;
6614 this.outlineVisible = show;
6615 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
6616 }
6617
6618 return this;
6619 };
6620
6621 /**
6622 * Get the outline widget.
6623 *
6624 * @param {OO.ui.PageLayout} page Page to be selected
6625 * @return {OO.ui.PageLayout|null} Closest page to another
6626 */
6627 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
6628 var next, prev, level,
6629 pages = this.stackLayout.getItems(),
6630 index = $.inArray( page, pages );
6631
6632 if ( index !== -1 ) {
6633 next = pages[index + 1];
6634 prev = pages[index - 1];
6635 // Prefer adjacent pages at the same level
6636 if ( this.outlined ) {
6637 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
6638 if (
6639 prev &&
6640 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
6641 ) {
6642 return prev;
6643 }
6644 if (
6645 next &&
6646 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
6647 ) {
6648 return next;
6649 }
6650 }
6651 }
6652 return prev || next || null;
6653 };
6654
6655 /**
6656 * Get the outline widget.
6657 *
6658 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
6659 */
6660 OO.ui.BookletLayout.prototype.getOutline = function () {
6661 return this.outlineSelectWidget;
6662 };
6663
6664 /**
6665 * Get the outline controls widget. If the outline is not editable, null is returned.
6666 *
6667 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
6668 */
6669 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
6670 return this.outlineControlsWidget;
6671 };
6672
6673 /**
6674 * Get a page by name.
6675 *
6676 * @param {string} name Symbolic name of page
6677 * @return {OO.ui.PageLayout|undefined} Page, if found
6678 */
6679 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
6680 return this.pages[name];
6681 };
6682
6683 /**
6684 * Get the current page name.
6685 *
6686 * @return {string|null} Current page name
6687 */
6688 OO.ui.BookletLayout.prototype.getPageName = function () {
6689 return this.currentPageName;
6690 };
6691
6692 /**
6693 * Add a page to the layout.
6694 *
6695 * When pages are added with the same names as existing pages, the existing pages will be
6696 * automatically removed before the new pages are added.
6697 *
6698 * @param {OO.ui.PageLayout[]} pages Pages to add
6699 * @param {number} index Index to insert pages after
6700 * @fires add
6701 * @chainable
6702 */
6703 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
6704 var i, len, name, page, item, currentIndex,
6705 stackLayoutPages = this.stackLayout.getItems(),
6706 remove = [],
6707 items = [];
6708
6709 // Remove pages with same names
6710 for ( i = 0, len = pages.length; i < len; i++ ) {
6711 page = pages[i];
6712 name = page.getName();
6713
6714 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
6715 // Correct the insertion index
6716 currentIndex = $.inArray( this.pages[name], stackLayoutPages );
6717 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
6718 index--;
6719 }
6720 remove.push( this.pages[name] );
6721 }
6722 }
6723 if ( remove.length ) {
6724 this.removePages( remove );
6725 }
6726
6727 // Add new pages
6728 for ( i = 0, len = pages.length; i < len; i++ ) {
6729 page = pages[i];
6730 name = page.getName();
6731 this.pages[page.getName()] = page;
6732 if ( this.outlined ) {
6733 item = new OO.ui.OutlineOptionWidget( { $: this.$, data: name } );
6734 page.setOutlineItem( item );
6735 items.push( item );
6736 }
6737 }
6738
6739 if ( this.outlined && items.length ) {
6740 this.outlineSelectWidget.addItems( items, index );
6741 this.selectFirstSelectablePage();
6742 }
6743 this.stackLayout.addItems( pages, index );
6744 this.emit( 'add', pages, index );
6745
6746 return this;
6747 };
6748
6749 /**
6750 * Remove a page from the layout.
6751 *
6752 * @fires remove
6753 * @chainable
6754 */
6755 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
6756 var i, len, name, page,
6757 items = [];
6758
6759 for ( i = 0, len = pages.length; i < len; i++ ) {
6760 page = pages[i];
6761 name = page.getName();
6762 delete this.pages[name];
6763 if ( this.outlined ) {
6764 items.push( this.outlineSelectWidget.getItemFromData( name ) );
6765 page.setOutlineItem( null );
6766 }
6767 }
6768 if ( this.outlined && items.length ) {
6769 this.outlineSelectWidget.removeItems( items );
6770 this.selectFirstSelectablePage();
6771 }
6772 this.stackLayout.removeItems( pages );
6773 this.emit( 'remove', pages );
6774
6775 return this;
6776 };
6777
6778 /**
6779 * Clear all pages from the layout.
6780 *
6781 * @fires remove
6782 * @chainable
6783 */
6784 OO.ui.BookletLayout.prototype.clearPages = function () {
6785 var i, len,
6786 pages = this.stackLayout.getItems();
6787
6788 this.pages = {};
6789 this.currentPageName = null;
6790 if ( this.outlined ) {
6791 this.outlineSelectWidget.clearItems();
6792 for ( i = 0, len = pages.length; i < len; i++ ) {
6793 pages[i].setOutlineItem( null );
6794 }
6795 }
6796 this.stackLayout.clearItems();
6797
6798 this.emit( 'remove', pages );
6799
6800 return this;
6801 };
6802
6803 /**
6804 * Set the current page by name.
6805 *
6806 * @fires set
6807 * @param {string} name Symbolic name of page
6808 */
6809 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
6810 var selectedItem,
6811 $focused,
6812 page = this.pages[name];
6813
6814 if ( name !== this.currentPageName ) {
6815 if ( this.outlined ) {
6816 selectedItem = this.outlineSelectWidget.getSelectedItem();
6817 if ( selectedItem && selectedItem.getData() !== name ) {
6818 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
6819 }
6820 }
6821 if ( page ) {
6822 if ( this.currentPageName && this.pages[this.currentPageName] ) {
6823 this.pages[this.currentPageName].setActive( false );
6824 // Blur anything focused if the next page doesn't have anything focusable - this
6825 // is not needed if the next page has something focusable because once it is focused
6826 // this blur happens automatically
6827 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
6828 $focused = this.pages[this.currentPageName].$element.find( ':focus' );
6829 if ( $focused.length ) {
6830 $focused[0].blur();
6831 }
6832 }
6833 }
6834 this.currentPageName = name;
6835 this.stackLayout.setItem( page );
6836 page.setActive( true );
6837 this.emit( 'set', page );
6838 }
6839 }
6840 };
6841
6842 /**
6843 * Select the first selectable page.
6844 *
6845 * @chainable
6846 */
6847 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
6848 if ( !this.outlineSelectWidget.getSelectedItem() ) {
6849 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
6850 }
6851
6852 return this;
6853 };
6854
6855 /**
6856 * Layout made of a field and optional label.
6857 *
6858 * Available label alignment modes include:
6859 * - left: Label is before the field and aligned away from it, best for when the user will be
6860 * scanning for a specific label in a form with many fields
6861 * - right: Label is before the field and aligned toward it, best for forms the user is very
6862 * familiar with and will tab through field checking quickly to verify which field they are in
6863 * - top: Label is before the field and above it, best for when the user will need to fill out all
6864 * fields from top to bottom in a form with few fields
6865 * - inline: Label is after the field and aligned toward it, best for small boolean fields like
6866 * checkboxes or radio buttons
6867 *
6868 * @class
6869 * @extends OO.ui.Layout
6870 * @mixins OO.ui.LabelElement
6871 *
6872 * @constructor
6873 * @param {OO.ui.Widget} fieldWidget Field widget
6874 * @param {Object} [config] Configuration options
6875 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
6876 * @cfg {string} [help] Explanatory text shown as a '?' icon.
6877 */
6878 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
6879 // Configuration initialization
6880 config = $.extend( { align: 'left' }, config );
6881
6882 // Properties (must be set before parent constructor, which calls #getTagName)
6883 this.fieldWidget = fieldWidget;
6884
6885 // Parent constructor
6886 OO.ui.FieldLayout.super.call( this, config );
6887
6888 // Mixin constructors
6889 OO.ui.LabelElement.call( this, config );
6890
6891 // Properties
6892 this.$field = this.$( '<div>' );
6893 this.align = null;
6894 if ( config.help ) {
6895 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
6896 $: this.$,
6897 classes: [ 'oo-ui-fieldLayout-help' ],
6898 framed: false,
6899 icon: 'info'
6900 } );
6901
6902 this.popupButtonWidget.getPopup().$body.append(
6903 this.$( '<div>' )
6904 .text( config.help )
6905 .addClass( 'oo-ui-fieldLayout-help-content' )
6906 );
6907 this.$help = this.popupButtonWidget.$element;
6908 } else {
6909 this.$help = this.$( [] );
6910 }
6911
6912 // Events
6913 if ( this.fieldWidget instanceof OO.ui.InputWidget ) {
6914 this.$label.on( 'click', this.onLabelClick.bind( this ) );
6915 }
6916 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
6917
6918 // Initialization
6919 this.$element.addClass( 'oo-ui-fieldLayout' );
6920 this.$field
6921 .addClass( 'oo-ui-fieldLayout-field' )
6922 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
6923 .append( this.fieldWidget.$element );
6924 this.setAlignment( config.align );
6925 };
6926
6927 /* Setup */
6928
6929 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
6930 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
6931
6932 /* Methods */
6933
6934 /**
6935 * @inheritdoc
6936 */
6937 OO.ui.FieldLayout.prototype.getTagName = function () {
6938 if ( this.fieldWidget instanceof OO.ui.InputWidget ) {
6939 return 'label';
6940 } else {
6941 return 'div';
6942 }
6943 };
6944
6945 /**
6946 * Handle field disable events.
6947 *
6948 * @param {boolean} value Field is disabled
6949 */
6950 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
6951 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
6952 };
6953
6954 /**
6955 * Handle label mouse click events.
6956 *
6957 * @param {jQuery.Event} e Mouse click event
6958 */
6959 OO.ui.FieldLayout.prototype.onLabelClick = function () {
6960 this.fieldWidget.simulateLabelClick();
6961 return false;
6962 };
6963
6964 /**
6965 * Get the field.
6966 *
6967 * @return {OO.ui.Widget} Field widget
6968 */
6969 OO.ui.FieldLayout.prototype.getField = function () {
6970 return this.fieldWidget;
6971 };
6972
6973 /**
6974 * Set the field alignment mode.
6975 *
6976 * @private
6977 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
6978 * @chainable
6979 */
6980 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
6981 if ( value !== this.align ) {
6982 // Default to 'left'
6983 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
6984 value = 'left';
6985 }
6986 // Reorder elements
6987 if ( value === 'inline' ) {
6988 this.$element.append( this.$field, this.$label, this.$help );
6989 } else {
6990 this.$element.append( this.$help, this.$label, this.$field );
6991 }
6992 // Set classes. The following classes can be used here:
6993 // * oo-ui-fieldLayout-align-left
6994 // * oo-ui-fieldLayout-align-right
6995 // * oo-ui-fieldLayout-align-top
6996 // * oo-ui-fieldLayout-align-inline
6997 if ( this.align ) {
6998 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
6999 }
7000 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7001 this.align = value;
7002 }
7003
7004 return this;
7005 };
7006
7007 /**
7008 * Layout made of a fieldset and optional legend.
7009 *
7010 * Just add OO.ui.FieldLayout items.
7011 *
7012 * @class
7013 * @extends OO.ui.Layout
7014 * @mixins OO.ui.IconElement
7015 * @mixins OO.ui.LabelElement
7016 * @mixins OO.ui.GroupElement
7017 *
7018 * @constructor
7019 * @param {Object} [config] Configuration options
7020 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7021 */
7022 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
7023 // Configuration initialization
7024 config = config || {};
7025
7026 // Parent constructor
7027 OO.ui.FieldsetLayout.super.call( this, config );
7028
7029 // Mixin constructors
7030 OO.ui.IconElement.call( this, config );
7031 OO.ui.LabelElement.call( this, config );
7032 OO.ui.GroupElement.call( this, config );
7033
7034 // Initialization
7035 this.$element
7036 .addClass( 'oo-ui-fieldsetLayout' )
7037 .prepend( this.$icon, this.$label, this.$group );
7038 if ( $.isArray( config.items ) ) {
7039 this.addItems( config.items );
7040 }
7041 };
7042
7043 /* Setup */
7044
7045 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
7046 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
7047 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
7048 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
7049
7050 /**
7051 * Layout with an HTML form.
7052 *
7053 * @class
7054 * @extends OO.ui.Layout
7055 *
7056 * @constructor
7057 * @param {Object} [config] Configuration options
7058 * @cfg {string} [method] HTML form `method` attribute
7059 * @cfg {string} [action] HTML form `action` attribute
7060 * @cfg {string} [enctype] HTML form `enctype` attribute
7061 */
7062 OO.ui.FormLayout = function OoUiFormLayout( config ) {
7063 // Configuration initialization
7064 config = config || {};
7065
7066 // Parent constructor
7067 OO.ui.FormLayout.super.call( this, config );
7068
7069 // Events
7070 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
7071
7072 // Initialization
7073 this.$element
7074 .addClass( 'oo-ui-formLayout' )
7075 .attr( {
7076 method: config.method,
7077 action: config.action,
7078 enctype: config.enctype
7079 } );
7080 };
7081
7082 /* Setup */
7083
7084 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
7085
7086 /* Events */
7087
7088 /**
7089 * @event submit
7090 */
7091
7092 /* Static Properties */
7093
7094 OO.ui.FormLayout.static.tagName = 'form';
7095
7096 /* Methods */
7097
7098 /**
7099 * Handle form submit events.
7100 *
7101 * @param {jQuery.Event} e Submit event
7102 * @fires submit
7103 */
7104 OO.ui.FormLayout.prototype.onFormSubmit = function () {
7105 this.emit( 'submit' );
7106 return false;
7107 };
7108
7109 /**
7110 * Layout made of proportionally sized columns and rows.
7111 *
7112 * @class
7113 * @extends OO.ui.Layout
7114 *
7115 * @constructor
7116 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
7117 * @param {Object} [config] Configuration options
7118 * @cfg {number[]} [widths] Widths of columns as ratios
7119 * @cfg {number[]} [heights] Heights of rows as ratios
7120 */
7121 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
7122 var i, len, widths;
7123
7124 // Configuration initialization
7125 config = config || {};
7126
7127 // Parent constructor
7128 OO.ui.GridLayout.super.call( this, config );
7129
7130 // Properties
7131 this.panels = [];
7132 this.widths = [];
7133 this.heights = [];
7134
7135 // Initialization
7136 this.$element.addClass( 'oo-ui-gridLayout' );
7137 for ( i = 0, len = panels.length; i < len; i++ ) {
7138 this.panels.push( panels[i] );
7139 this.$element.append( panels[i].$element );
7140 }
7141 if ( config.widths || config.heights ) {
7142 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
7143 } else {
7144 // Arrange in columns by default
7145 widths = this.panels.map( function () { return 1; } );
7146 this.layout( widths, [ 1 ] );
7147 }
7148 };
7149
7150 /* Setup */
7151
7152 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
7153
7154 /* Events */
7155
7156 /**
7157 * @event layout
7158 */
7159
7160 /**
7161 * @event update
7162 */
7163
7164 /* Methods */
7165
7166 /**
7167 * Set grid dimensions.
7168 *
7169 * @param {number[]} widths Widths of columns as ratios
7170 * @param {number[]} heights Heights of rows as ratios
7171 * @fires layout
7172 * @throws {Error} If grid is not large enough to fit all panels
7173 */
7174 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
7175 var x, y,
7176 xd = 0,
7177 yd = 0,
7178 cols = widths.length,
7179 rows = heights.length;
7180
7181 // Verify grid is big enough to fit panels
7182 if ( cols * rows < this.panels.length ) {
7183 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
7184 }
7185
7186 // Sum up denominators
7187 for ( x = 0; x < cols; x++ ) {
7188 xd += widths[x];
7189 }
7190 for ( y = 0; y < rows; y++ ) {
7191 yd += heights[y];
7192 }
7193 // Store factors
7194 this.widths = [];
7195 this.heights = [];
7196 for ( x = 0; x < cols; x++ ) {
7197 this.widths[x] = widths[x] / xd;
7198 }
7199 for ( y = 0; y < rows; y++ ) {
7200 this.heights[y] = heights[y] / yd;
7201 }
7202 // Synchronize view
7203 this.update();
7204 this.emit( 'layout' );
7205 };
7206
7207 /**
7208 * Update panel positions and sizes.
7209 *
7210 * @fires update
7211 */
7212 OO.ui.GridLayout.prototype.update = function () {
7213 var x, y, panel, width, height, dimensions,
7214 i = 0,
7215 top = 0,
7216 left = 0,
7217 cols = this.widths.length,
7218 rows = this.heights.length;
7219
7220 for ( y = 0; y < rows; y++ ) {
7221 height = this.heights[y];
7222 for ( x = 0; x < cols; x++ ) {
7223 width = this.widths[x];
7224 panel = this.panels[i];
7225 dimensions = {
7226 width: Math.round( width * 100 ) + '%',
7227 height: Math.round( height * 100 ) + '%',
7228 top: Math.round( top * 100 ) + '%'
7229 };
7230 // If RTL, reverse:
7231 if ( OO.ui.Element.getDir( this.$.context ) === 'rtl' ) {
7232 dimensions.right = Math.round( left * 100 ) + '%';
7233 } else {
7234 dimensions.left = Math.round( left * 100 ) + '%';
7235 }
7236 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
7237 if ( width === 0 || height === 0 ) {
7238 dimensions.visibility = 'hidden';
7239 } else {
7240 dimensions.visibility = '';
7241 }
7242 panel.$element.css( dimensions );
7243 i++;
7244 left += width;
7245 }
7246 top += height;
7247 left = 0;
7248 }
7249
7250 this.emit( 'update' );
7251 };
7252
7253 /**
7254 * Get a panel at a given position.
7255 *
7256 * The x and y position is affected by the current grid layout.
7257 *
7258 * @param {number} x Horizontal position
7259 * @param {number} y Vertical position
7260 * @return {OO.ui.PanelLayout} The panel at the given position
7261 */
7262 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
7263 return this.panels[ ( x * this.widths.length ) + y ];
7264 };
7265
7266 /**
7267 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
7268 *
7269 * @class
7270 * @extends OO.ui.Layout
7271 *
7272 * @constructor
7273 * @param {Object} [config] Configuration options
7274 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
7275 * @cfg {boolean} [padded=false] Pad the content from the edges
7276 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
7277 */
7278 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
7279 // Configuration initialization
7280 config = $.extend( {
7281 scrollable: false,
7282 padded: false,
7283 expanded: true
7284 }, config );
7285
7286 // Parent constructor
7287 OO.ui.PanelLayout.super.call( this, config );
7288
7289 // Initialization
7290 this.$element.addClass( 'oo-ui-panelLayout' );
7291 if ( config.scrollable ) {
7292 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
7293 }
7294 if ( config.padded ) {
7295 this.$element.addClass( 'oo-ui-panelLayout-padded' );
7296 }
7297 if ( config.expanded ) {
7298 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
7299 }
7300 };
7301
7302 /* Setup */
7303
7304 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
7305
7306 /**
7307 * Page within an booklet layout.
7308 *
7309 * @class
7310 * @extends OO.ui.PanelLayout
7311 *
7312 * @constructor
7313 * @param {string} name Unique symbolic name of page
7314 * @param {Object} [config] Configuration options
7315 * @param {string} [outlineItem] Outline item widget
7316 */
7317 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
7318 // Configuration initialization
7319 config = $.extend( { scrollable: true }, config );
7320
7321 // Parent constructor
7322 OO.ui.PageLayout.super.call( this, config );
7323
7324 // Properties
7325 this.name = name;
7326 this.outlineItem = config.outlineItem || null;
7327 this.active = false;
7328
7329 // Initialization
7330 this.$element.addClass( 'oo-ui-pageLayout' );
7331 };
7332
7333 /* Setup */
7334
7335 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
7336
7337 /* Events */
7338
7339 /**
7340 * @event active
7341 * @param {boolean} active Page is active
7342 */
7343
7344 /* Methods */
7345
7346 /**
7347 * Get page name.
7348 *
7349 * @return {string} Symbolic name of page
7350 */
7351 OO.ui.PageLayout.prototype.getName = function () {
7352 return this.name;
7353 };
7354
7355 /**
7356 * Check if page is active.
7357 *
7358 * @return {boolean} Page is active
7359 */
7360 OO.ui.PageLayout.prototype.isActive = function () {
7361 return this.active;
7362 };
7363
7364 /**
7365 * Get outline item.
7366 *
7367 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
7368 */
7369 OO.ui.PageLayout.prototype.getOutlineItem = function () {
7370 return this.outlineItem;
7371 };
7372
7373 /**
7374 * Set outline item.
7375 *
7376 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
7377 * outline item as desired; this method is called for setting (with an object) and unsetting
7378 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
7379 * operating on null instead of an OO.ui.OutlineOptionWidget object.
7380 *
7381 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
7382 * @chainable
7383 */
7384 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
7385 this.outlineItem = outlineItem || null;
7386 if ( outlineItem ) {
7387 this.setupOutlineItem();
7388 }
7389 return this;
7390 };
7391
7392 /**
7393 * Setup outline item.
7394 *
7395 * @localdoc Subclasses should override this method to adjust the outline item as desired.
7396 *
7397 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
7398 * @chainable
7399 */
7400 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
7401 return this;
7402 };
7403
7404 /**
7405 * Set page active state.
7406 *
7407 * @param {boolean} Page is active
7408 * @fires active
7409 */
7410 OO.ui.PageLayout.prototype.setActive = function ( active ) {
7411 active = !!active;
7412
7413 if ( active !== this.active ) {
7414 this.active = active;
7415 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
7416 this.emit( 'active', this.active );
7417 }
7418 };
7419
7420 /**
7421 * Layout containing a series of mutually exclusive pages.
7422 *
7423 * @class
7424 * @extends OO.ui.PanelLayout
7425 * @mixins OO.ui.GroupElement
7426 *
7427 * @constructor
7428 * @param {Object} [config] Configuration options
7429 * @cfg {boolean} [continuous=false] Show all pages, one after another
7430 * @cfg {string} [icon=''] Symbolic icon name
7431 * @cfg {OO.ui.Layout[]} [items] Layouts to add
7432 */
7433 OO.ui.StackLayout = function OoUiStackLayout( config ) {
7434 // Configuration initialization
7435 config = $.extend( { scrollable: true }, config );
7436
7437 // Parent constructor
7438 OO.ui.StackLayout.super.call( this, config );
7439
7440 // Mixin constructors
7441 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
7442
7443 // Properties
7444 this.currentItem = null;
7445 this.continuous = !!config.continuous;
7446
7447 // Initialization
7448 this.$element.addClass( 'oo-ui-stackLayout' );
7449 if ( this.continuous ) {
7450 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
7451 }
7452 if ( $.isArray( config.items ) ) {
7453 this.addItems( config.items );
7454 }
7455 };
7456
7457 /* Setup */
7458
7459 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
7460 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
7461
7462 /* Events */
7463
7464 /**
7465 * @event set
7466 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
7467 */
7468
7469 /* Methods */
7470
7471 /**
7472 * Get the current item.
7473 *
7474 * @return {OO.ui.Layout|null}
7475 */
7476 OO.ui.StackLayout.prototype.getCurrentItem = function () {
7477 return this.currentItem;
7478 };
7479
7480 /**
7481 * Unset the current item.
7482 *
7483 * @private
7484 * @param {OO.ui.StackLayout} layout
7485 * @fires set
7486 */
7487 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
7488 var prevItem = this.currentItem;
7489 if ( prevItem === null ) {
7490 return;
7491 }
7492
7493 this.currentItem = null;
7494 this.emit( 'set', null );
7495 };
7496
7497 /**
7498 * Add items.
7499 *
7500 * Adding an existing item (by value) will move it.
7501 *
7502 * @param {OO.ui.Layout[]} items Items to add
7503 * @param {number} [index] Index to insert items after
7504 * @chainable
7505 */
7506 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
7507 // Mixin method
7508 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
7509
7510 if ( !this.currentItem && items.length ) {
7511 this.setItem( items[0] );
7512 }
7513
7514 return this;
7515 };
7516
7517 /**
7518 * Remove items.
7519 *
7520 * Items will be detached, not removed, so they can be used later.
7521 *
7522 * @param {OO.ui.Layout[]} items Items to remove
7523 * @chainable
7524 * @fires set
7525 */
7526 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
7527 // Mixin method
7528 OO.ui.GroupElement.prototype.removeItems.call( this, items );
7529
7530 if ( $.inArray( this.currentItem, items ) !== -1 ) {
7531 if ( this.items.length ) {
7532 this.setItem( this.items[0] );
7533 } else {
7534 this.unsetCurrentItem();
7535 }
7536 }
7537
7538 return this;
7539 };
7540
7541 /**
7542 * Clear all items.
7543 *
7544 * Items will be detached, not removed, so they can be used later.
7545 *
7546 * @chainable
7547 * @fires set
7548 */
7549 OO.ui.StackLayout.prototype.clearItems = function () {
7550 this.unsetCurrentItem();
7551 OO.ui.GroupElement.prototype.clearItems.call( this );
7552
7553 return this;
7554 };
7555
7556 /**
7557 * Show item.
7558 *
7559 * Any currently shown item will be hidden.
7560 *
7561 * FIXME: If the passed item to show has not been added in the items list, then
7562 * this method drops it and unsets the current item.
7563 *
7564 * @param {OO.ui.Layout} item Item to show
7565 * @chainable
7566 * @fires set
7567 */
7568 OO.ui.StackLayout.prototype.setItem = function ( item ) {
7569 var i, len;
7570
7571 if ( item !== this.currentItem ) {
7572 if ( !this.continuous ) {
7573 for ( i = 0, len = this.items.length; i < len; i++ ) {
7574 this.items[i].$element.css( 'display', '' );
7575 }
7576 }
7577 if ( $.inArray( item, this.items ) !== -1 ) {
7578 if ( !this.continuous ) {
7579 item.$element.css( 'display', 'block' );
7580 }
7581 this.currentItem = item;
7582 this.emit( 'set', item );
7583 } else {
7584 this.unsetCurrentItem();
7585 }
7586 }
7587
7588 return this;
7589 };
7590
7591 /**
7592 * Horizontal bar layout of tools as icon buttons.
7593 *
7594 * @class
7595 * @extends OO.ui.ToolGroup
7596 *
7597 * @constructor
7598 * @param {OO.ui.Toolbar} toolbar
7599 * @param {Object} [config] Configuration options
7600 */
7601 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
7602 // Parent constructor
7603 OO.ui.BarToolGroup.super.call( this, toolbar, config );
7604
7605 // Initialization
7606 this.$element.addClass( 'oo-ui-barToolGroup' );
7607 };
7608
7609 /* Setup */
7610
7611 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
7612
7613 /* Static Properties */
7614
7615 OO.ui.BarToolGroup.static.titleTooltips = true;
7616
7617 OO.ui.BarToolGroup.static.accelTooltips = true;
7618
7619 OO.ui.BarToolGroup.static.name = 'bar';
7620
7621 /**
7622 * Popup list of tools with an icon and optional label.
7623 *
7624 * @abstract
7625 * @class
7626 * @extends OO.ui.ToolGroup
7627 * @mixins OO.ui.IconElement
7628 * @mixins OO.ui.IndicatorElement
7629 * @mixins OO.ui.LabelElement
7630 * @mixins OO.ui.TitledElement
7631 * @mixins OO.ui.ClippableElement
7632 *
7633 * @constructor
7634 * @param {OO.ui.Toolbar} toolbar
7635 * @param {Object} [config] Configuration options
7636 * @cfg {string} [header] Text to display at the top of the pop-up
7637 */
7638 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
7639 // Configuration initialization
7640 config = config || {};
7641
7642 // Parent constructor
7643 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
7644
7645 // Mixin constructors
7646 OO.ui.IconElement.call( this, config );
7647 OO.ui.IndicatorElement.call( this, config );
7648 OO.ui.LabelElement.call( this, config );
7649 OO.ui.TitledElement.call( this, config );
7650 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7651
7652 // Properties
7653 this.active = false;
7654 this.dragging = false;
7655 this.onBlurHandler = this.onBlur.bind( this );
7656 this.$handle = this.$( '<span>' );
7657
7658 // Events
7659 this.$handle.on( {
7660 'mousedown touchstart': this.onHandlePointerDown.bind( this ),
7661 'mouseup touchend': this.onHandlePointerUp.bind( this )
7662 } );
7663
7664 // Initialization
7665 this.$handle
7666 .addClass( 'oo-ui-popupToolGroup-handle' )
7667 .append( this.$icon, this.$label, this.$indicator );
7668 // If the pop-up should have a header, add it to the top of the toolGroup.
7669 // Note: If this feature is useful for other widgets, we could abstract it into an
7670 // OO.ui.HeaderedElement mixin constructor.
7671 if ( config.header !== undefined ) {
7672 this.$group
7673 .prepend( this.$( '<span>' )
7674 .addClass( 'oo-ui-popupToolGroup-header' )
7675 .text( config.header )
7676 );
7677 }
7678 this.$element
7679 .addClass( 'oo-ui-popupToolGroup' )
7680 .prepend( this.$handle );
7681 };
7682
7683 /* Setup */
7684
7685 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
7686 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
7687 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
7688 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
7689 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
7690 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
7691
7692 /* Static Properties */
7693
7694 /* Methods */
7695
7696 /**
7697 * @inheritdoc
7698 */
7699 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
7700 // Parent method
7701 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
7702
7703 if ( this.isDisabled() && this.isElementAttached() ) {
7704 this.setActive( false );
7705 }
7706 };
7707
7708 /**
7709 * Handle focus being lost.
7710 *
7711 * The event is actually generated from a mouseup, so it is not a normal blur event object.
7712 *
7713 * @param {jQuery.Event} e Mouse up event
7714 */
7715 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
7716 // Only deactivate when clicking outside the dropdown element
7717 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
7718 this.setActive( false );
7719 }
7720 };
7721
7722 /**
7723 * @inheritdoc
7724 */
7725 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
7726 // e.which is 0 for touch events, 1 for left mouse button
7727 // Only close toolgroup when a tool was actually selected
7728 // FIXME: this duplicates logic from the parent class
7729 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
7730 this.setActive( false );
7731 }
7732 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
7733 };
7734
7735 /**
7736 * Handle mouse up events.
7737 *
7738 * @param {jQuery.Event} e Mouse up event
7739 */
7740 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
7741 return false;
7742 };
7743
7744 /**
7745 * Handle mouse down events.
7746 *
7747 * @param {jQuery.Event} e Mouse down event
7748 */
7749 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
7750 // e.which is 0 for touch events, 1 for left mouse button
7751 if ( !this.isDisabled() && e.which <= 1 ) {
7752 this.setActive( !this.active );
7753 }
7754 return false;
7755 };
7756
7757 /**
7758 * Switch into active mode.
7759 *
7760 * When active, mouseup events anywhere in the document will trigger deactivation.
7761 */
7762 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
7763 value = !!value;
7764 if ( this.active !== value ) {
7765 this.active = value;
7766 if ( value ) {
7767 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
7768
7769 // Try anchoring the popup to the left first
7770 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
7771 this.toggleClipping( true );
7772 if ( this.isClippedHorizontally() ) {
7773 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
7774 this.toggleClipping( false );
7775 this.$element
7776 .removeClass( 'oo-ui-popupToolGroup-left' )
7777 .addClass( 'oo-ui-popupToolGroup-right' );
7778 this.toggleClipping( true );
7779 }
7780 } else {
7781 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
7782 this.$element.removeClass(
7783 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
7784 );
7785 this.toggleClipping( false );
7786 }
7787 }
7788 };
7789
7790 /**
7791 * Drop down list layout of tools as labeled icon buttons.
7792 *
7793 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
7794 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
7795 * may want to use the 'promote' and 'demote' configuration options to achieve this.
7796 *
7797 * @class
7798 * @extends OO.ui.PopupToolGroup
7799 *
7800 * @constructor
7801 * @param {OO.ui.Toolbar} toolbar
7802 * @param {Object} [config] Configuration options
7803 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
7804 * shown.
7805 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
7806 * allowed to be collapsed.
7807 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
7808 */
7809 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
7810 // Configuration initialization
7811 config = config || {};
7812
7813 // Properties (must be set before parent constructor, which calls #populate)
7814 this.allowCollapse = config.allowCollapse;
7815 this.forceExpand = config.forceExpand;
7816 this.expanded = config.expanded !== undefined ? config.expanded : false;
7817 this.collapsibleTools = [];
7818
7819 // Parent constructor
7820 OO.ui.ListToolGroup.super.call( this, toolbar, config );
7821
7822 // Initialization
7823 this.$element.addClass( 'oo-ui-listToolGroup' );
7824 };
7825
7826 /* Setup */
7827
7828 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
7829
7830 /* Static Properties */
7831
7832 OO.ui.ListToolGroup.static.accelTooltips = true;
7833
7834 OO.ui.ListToolGroup.static.name = 'list';
7835
7836 /* Methods */
7837
7838 /**
7839 * @inheritdoc
7840 */
7841 OO.ui.ListToolGroup.prototype.populate = function () {
7842 var i, len, allowCollapse = [];
7843
7844 OO.ui.ListToolGroup.super.prototype.populate.call( this );
7845
7846 // Update the list of collapsible tools
7847 if ( this.allowCollapse !== undefined ) {
7848 allowCollapse = this.allowCollapse;
7849 } else if ( this.forceExpand !== undefined ) {
7850 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
7851 }
7852
7853 this.collapsibleTools = [];
7854 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
7855 if ( this.tools[ allowCollapse[i] ] !== undefined ) {
7856 this.collapsibleTools.push( this.tools[ allowCollapse[i] ] );
7857 }
7858 }
7859
7860 // Keep at the end, even when tools are added
7861 this.$group.append( this.getExpandCollapseTool().$element );
7862
7863 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
7864
7865 // Calling jQuery's .hide() and then .show() on a detached element caches the default value of its
7866 // 'display' attribute and restores it, and the tool uses a <span> and can be hidden and re-shown.
7867 // Is this a jQuery bug? http://jsfiddle.net/gtj4hu3h/
7868 if ( this.getExpandCollapseTool().$element.css( 'display' ) === 'inline' ) {
7869 this.getExpandCollapseTool().$element.css( 'display', 'inline-block' );
7870 }
7871
7872 this.updateCollapsibleState();
7873 };
7874
7875 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
7876 if ( this.expandCollapseTool === undefined ) {
7877 var ExpandCollapseTool = function () {
7878 ExpandCollapseTool.super.apply( this, arguments );
7879 };
7880
7881 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
7882
7883 ExpandCollapseTool.prototype.onSelect = function () {
7884 this.toolGroup.expanded = !this.toolGroup.expanded;
7885 this.toolGroup.updateCollapsibleState();
7886 this.setActive( false );
7887 };
7888 ExpandCollapseTool.prototype.onUpdateState = function () {
7889 // Do nothing. Tool interface requires an implementation of this function.
7890 };
7891
7892 ExpandCollapseTool.static.name = 'more-fewer';
7893
7894 this.expandCollapseTool = new ExpandCollapseTool( this );
7895 }
7896 return this.expandCollapseTool;
7897 };
7898
7899 /**
7900 * @inheritdoc
7901 */
7902 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
7903 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
7904
7905 // Do not close the popup when the user wants to show more/fewer tools
7906 if ( this.$( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
7907 // Prevent the popup list from being hidden
7908 this.setActive( true );
7909 }
7910
7911 return ret;
7912 };
7913
7914 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
7915 var i, len;
7916
7917 this.getExpandCollapseTool()
7918 .setIcon( this.expanded ? 'collapse' : 'expand' )
7919 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
7920
7921 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
7922 this.collapsibleTools[i].toggle( this.expanded );
7923 }
7924 };
7925
7926 /**
7927 * Drop down menu layout of tools as selectable menu items.
7928 *
7929 * @class
7930 * @extends OO.ui.PopupToolGroup
7931 *
7932 * @constructor
7933 * @param {OO.ui.Toolbar} toolbar
7934 * @param {Object} [config] Configuration options
7935 */
7936 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
7937 // Configuration initialization
7938 config = config || {};
7939
7940 // Parent constructor
7941 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
7942
7943 // Events
7944 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7945
7946 // Initialization
7947 this.$element.addClass( 'oo-ui-menuToolGroup' );
7948 };
7949
7950 /* Setup */
7951
7952 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
7953
7954 /* Static Properties */
7955
7956 OO.ui.MenuToolGroup.static.accelTooltips = true;
7957
7958 OO.ui.MenuToolGroup.static.name = 'menu';
7959
7960 /* Methods */
7961
7962 /**
7963 * Handle the toolbar state being updated.
7964 *
7965 * When the state changes, the title of each active item in the menu will be joined together and
7966 * used as a label for the group. The label will be empty if none of the items are active.
7967 */
7968 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
7969 var name,
7970 labelTexts = [];
7971
7972 for ( name in this.tools ) {
7973 if ( this.tools[name].isActive() ) {
7974 labelTexts.push( this.tools[name].getTitle() );
7975 }
7976 }
7977
7978 this.setLabel( labelTexts.join( ', ' ) || ' ' );
7979 };
7980
7981 /**
7982 * Tool that shows a popup when selected.
7983 *
7984 * @abstract
7985 * @class
7986 * @extends OO.ui.Tool
7987 * @mixins OO.ui.PopupElement
7988 *
7989 * @constructor
7990 * @param {OO.ui.Toolbar} toolbar
7991 * @param {Object} [config] Configuration options
7992 */
7993 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
7994 // Parent constructor
7995 OO.ui.PopupTool.super.call( this, toolbar, config );
7996
7997 // Mixin constructors
7998 OO.ui.PopupElement.call( this, config );
7999
8000 // Initialization
8001 this.$element
8002 .addClass( 'oo-ui-popupTool' )
8003 .append( this.popup.$element );
8004 };
8005
8006 /* Setup */
8007
8008 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
8009 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
8010
8011 /* Methods */
8012
8013 /**
8014 * Handle the tool being selected.
8015 *
8016 * @inheritdoc
8017 */
8018 OO.ui.PopupTool.prototype.onSelect = function () {
8019 if ( !this.isDisabled() ) {
8020 this.popup.toggle();
8021 }
8022 this.setActive( false );
8023 return false;
8024 };
8025
8026 /**
8027 * Handle the toolbar state being updated.
8028 *
8029 * @inheritdoc
8030 */
8031 OO.ui.PopupTool.prototype.onUpdateState = function () {
8032 this.setActive( false );
8033 };
8034
8035 /**
8036 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
8037 *
8038 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
8039 *
8040 * @abstract
8041 * @class
8042 * @extends OO.ui.GroupElement
8043 *
8044 * @constructor
8045 * @param {Object} [config] Configuration options
8046 */
8047 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
8048 // Parent constructor
8049 OO.ui.GroupWidget.super.call( this, config );
8050 };
8051
8052 /* Setup */
8053
8054 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
8055
8056 /* Methods */
8057
8058 /**
8059 * Set the disabled state of the widget.
8060 *
8061 * This will also update the disabled state of child widgets.
8062 *
8063 * @param {boolean} disabled Disable widget
8064 * @chainable
8065 */
8066 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
8067 var i, len;
8068
8069 // Parent method
8070 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
8071 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
8072
8073 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
8074 if ( this.items ) {
8075 for ( i = 0, len = this.items.length; i < len; i++ ) {
8076 this.items[i].updateDisabled();
8077 }
8078 }
8079
8080 return this;
8081 };
8082
8083 /**
8084 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
8085 *
8086 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
8087 * allows bidirectional communication.
8088 *
8089 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
8090 *
8091 * @abstract
8092 * @class
8093 *
8094 * @constructor
8095 */
8096 OO.ui.ItemWidget = function OoUiItemWidget() {
8097 //
8098 };
8099
8100 /* Methods */
8101
8102 /**
8103 * Check if widget is disabled.
8104 *
8105 * Checks parent if present, making disabled state inheritable.
8106 *
8107 * @return {boolean} Widget is disabled
8108 */
8109 OO.ui.ItemWidget.prototype.isDisabled = function () {
8110 return this.disabled ||
8111 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
8112 };
8113
8114 /**
8115 * Set group element is in.
8116 *
8117 * @param {OO.ui.GroupElement|null} group Group element, null if none
8118 * @chainable
8119 */
8120 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
8121 // Parent method
8122 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
8123 OO.ui.Element.prototype.setElementGroup.call( this, group );
8124
8125 // Initialize item disabled states
8126 this.updateDisabled();
8127
8128 return this;
8129 };
8130
8131 /**
8132 * Mixin that adds a menu showing suggested values for a text input.
8133 *
8134 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
8135 *
8136 * Subclasses that set the value of #lookupInput from their `choose` or `select` handler should
8137 * be aware that this will cause new suggestions to be looked up for the new value. If this is
8138 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
8139 *
8140 * @class
8141 * @abstract
8142 *
8143 * @constructor
8144 * @param {OO.ui.TextInputWidget} input Input widget
8145 * @param {Object} [config] Configuration options
8146 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
8147 * @cfg {jQuery} [$container=input.$element] Element to render menu under
8148 */
8149 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
8150 // Configuration initialization
8151 config = config || {};
8152
8153 // Properties
8154 this.lookupInput = input;
8155 this.$overlay = config.$overlay || this.$element;
8156 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
8157 $: OO.ui.Element.getJQuery( this.$overlay ),
8158 input: this.lookupInput,
8159 $container: config.$container
8160 } );
8161 this.lookupCache = {};
8162 this.lookupQuery = null;
8163 this.lookupRequest = null;
8164 this.lookupsDisabled = false;
8165 this.lookupInputFocused = false;
8166
8167 // Events
8168 this.lookupInput.$input.on( {
8169 focus: this.onLookupInputFocus.bind( this ),
8170 blur: this.onLookupInputBlur.bind( this ),
8171 mousedown: this.onLookupInputMouseDown.bind( this )
8172 } );
8173 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
8174 this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle' } );
8175
8176 // Initialization
8177 this.$element.addClass( 'oo-ui-lookupWidget' );
8178 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
8179 this.$overlay.append( this.lookupMenu.$element );
8180 };
8181
8182 /* Methods */
8183
8184 /**
8185 * Handle input focus event.
8186 *
8187 * @param {jQuery.Event} e Input focus event
8188 */
8189 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
8190 this.lookupInputFocused = true;
8191 this.populateLookupMenu();
8192 };
8193
8194 /**
8195 * Handle input blur event.
8196 *
8197 * @param {jQuery.Event} e Input blur event
8198 */
8199 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
8200 this.closeLookupMenu();
8201 this.lookupInputFocused = false;
8202 };
8203
8204 /**
8205 * Handle input mouse down event.
8206 *
8207 * @param {jQuery.Event} e Input mouse down event
8208 */
8209 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
8210 // Only open the menu if the input was already focused.
8211 // This way we allow the user to open the menu again after closing it with Esc
8212 // by clicking in the input. Opening (and populating) the menu when initially
8213 // clicking into the input is handled by the focus handler.
8214 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
8215 this.populateLookupMenu();
8216 }
8217 };
8218
8219 /**
8220 * Handle input change event.
8221 *
8222 * @param {string} value New input value
8223 */
8224 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
8225 if ( this.lookupInputFocused ) {
8226 this.populateLookupMenu();
8227 }
8228 };
8229
8230 /**
8231 * Handle the lookup menu being shown/hidden.
8232 * @param {boolean} visible Whether the lookup menu is now visible.
8233 */
8234 OO.ui.LookupInputWidget.prototype.onLookupMenuToggle = function ( visible ) {
8235 if ( !visible ) {
8236 // When the menu is hidden, abort any active request and clear the menu.
8237 // This has to be done here in addition to closeLookupMenu(), because
8238 // MenuSelectWidget will close itself when the user presses Esc.
8239 this.abortLookupRequest();
8240 this.lookupMenu.clearItems();
8241 }
8242 };
8243
8244 /**
8245 * Get lookup menu.
8246 *
8247 * @return {OO.ui.TextInputMenuSelectWidget}
8248 */
8249 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
8250 return this.lookupMenu;
8251 };
8252
8253 /**
8254 * Disable or re-enable lookups.
8255 *
8256 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
8257 *
8258 * @param {boolean} disabled Disable lookups
8259 */
8260 OO.ui.LookupInputWidget.prototype.setLookupsDisabled = function ( disabled ) {
8261 this.lookupsDisabled = !!disabled;
8262 };
8263
8264 /**
8265 * Open the menu. If there are no entries in the menu, this does nothing.
8266 *
8267 * @chainable
8268 */
8269 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
8270 if ( !this.lookupMenu.isEmpty() ) {
8271 this.lookupMenu.toggle( true );
8272 }
8273 return this;
8274 };
8275
8276 /**
8277 * Close the menu, empty it, and abort any pending request.
8278 *
8279 * @chainable
8280 */
8281 OO.ui.LookupInputWidget.prototype.closeLookupMenu = function () {
8282 this.lookupMenu.toggle( false );
8283 this.abortLookupRequest();
8284 this.lookupMenu.clearItems();
8285 return this;
8286 };
8287
8288 /**
8289 * Request menu items based on the input's current value, and when they arrive,
8290 * populate the menu with these items and show the menu.
8291 *
8292 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
8293 *
8294 * @chainable
8295 */
8296 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
8297 var widget = this,
8298 value = this.lookupInput.getValue();
8299
8300 if ( this.lookupsDisabled ) {
8301 return;
8302 }
8303
8304 // If the input is empty, clear the menu
8305 if ( value === '' ) {
8306 this.closeLookupMenu();
8307 // Skip population if there is already a request pending for the current value
8308 } else if ( value !== this.lookupQuery ) {
8309 this.getLookupMenuItems()
8310 .done( function ( items ) {
8311 widget.lookupMenu.clearItems();
8312 if ( items.length ) {
8313 widget.lookupMenu
8314 .addItems( items )
8315 .toggle( true );
8316 widget.initializeLookupMenuSelection();
8317 } else {
8318 widget.lookupMenu.toggle( false );
8319 }
8320 } )
8321 .fail( function () {
8322 widget.lookupMenu.clearItems();
8323 } );
8324 }
8325
8326 return this;
8327 };
8328
8329 /**
8330 * Select and highlight the first selectable item in the menu.
8331 *
8332 * @chainable
8333 */
8334 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
8335 if ( !this.lookupMenu.getSelectedItem() ) {
8336 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
8337 }
8338 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
8339 };
8340
8341 /**
8342 * Get lookup menu items for the current query.
8343 *
8344 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
8345 * of the done event. If the request was aborted to make way for a subsequent request,
8346 * this promise will not be rejected: it will remain pending forever.
8347 */
8348 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
8349 var widget = this,
8350 value = this.lookupInput.getValue(),
8351 deferred = $.Deferred(),
8352 ourRequest;
8353
8354 this.abortLookupRequest();
8355 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
8356 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
8357 } else {
8358 this.lookupInput.pushPending();
8359 this.lookupQuery = value;
8360 ourRequest = this.lookupRequest = this.getLookupRequest();
8361 ourRequest
8362 .always( function () {
8363 // We need to pop pending even if this is an old request, otherwise
8364 // the widget will remain pending forever.
8365 // TODO: this assumes that an aborted request will fail or succeed soon after
8366 // being aborted, or at least eventually. It would be nice if we could popPending()
8367 // at abort time, but only if we knew that we hadn't already called popPending()
8368 // for that request.
8369 widget.lookupInput.popPending();
8370 } )
8371 .done( function ( data ) {
8372 // If this is an old request (and aborting it somehow caused it to still succeed),
8373 // ignore its success completely
8374 if ( ourRequest === widget.lookupRequest ) {
8375 widget.lookupQuery = null;
8376 widget.lookupRequest = null;
8377 widget.lookupCache[value] = widget.getLookupCacheItemFromData( data );
8378 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[value] ) );
8379 }
8380 } )
8381 .fail( function () {
8382 // If this is an old request (or a request failing because it's being aborted),
8383 // ignore its failure completely
8384 if ( ourRequest === widget.lookupRequest ) {
8385 widget.lookupQuery = null;
8386 widget.lookupRequest = null;
8387 deferred.reject();
8388 }
8389 } );
8390 }
8391 return deferred.promise();
8392 };
8393
8394 /**
8395 * Abort the currently pending lookup request, if any.
8396 */
8397 OO.ui.LookupInputWidget.prototype.abortLookupRequest = function () {
8398 var oldRequest = this.lookupRequest;
8399 if ( oldRequest ) {
8400 // First unset this.lookupRequest to the fail handler will notice
8401 // that the request is no longer current
8402 this.lookupRequest = null;
8403 this.lookupQuery = null;
8404 oldRequest.abort();
8405 }
8406 };
8407
8408 /**
8409 * Get a new request object of the current lookup query value.
8410 *
8411 * @abstract
8412 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
8413 */
8414 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
8415 // Stub, implemented in subclass
8416 return null;
8417 };
8418
8419 /**
8420 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
8421 *
8422 * @abstract
8423 * @param {Mixed} data Cached result data, usually an array
8424 * @return {OO.ui.MenuOptionWidget[]} Menu items
8425 */
8426 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
8427 // Stub, implemented in subclass
8428 return [];
8429 };
8430
8431 /**
8432 * Get lookup cache item from server response data.
8433 *
8434 * @abstract
8435 * @param {Mixed} data Response from server
8436 * @return {Mixed} Cached result data
8437 */
8438 OO.ui.LookupInputWidget.prototype.getLookupCacheItemFromData = function () {
8439 // Stub, implemented in subclass
8440 return [];
8441 };
8442
8443 /**
8444 * Set of controls for an OO.ui.OutlineSelectWidget.
8445 *
8446 * Controls include moving items up and down, removing items, and adding different kinds of items.
8447 *
8448 * @class
8449 * @extends OO.ui.Widget
8450 * @mixins OO.ui.GroupElement
8451 * @mixins OO.ui.IconElement
8452 *
8453 * @constructor
8454 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
8455 * @param {Object} [config] Configuration options
8456 */
8457 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
8458 // Configuration initialization
8459 config = $.extend( { icon: 'add' }, config );
8460
8461 // Parent constructor
8462 OO.ui.OutlineControlsWidget.super.call( this, config );
8463
8464 // Mixin constructors
8465 OO.ui.GroupElement.call( this, config );
8466 OO.ui.IconElement.call( this, config );
8467
8468 // Properties
8469 this.outline = outline;
8470 this.$movers = this.$( '<div>' );
8471 this.upButton = new OO.ui.ButtonWidget( {
8472 $: this.$,
8473 framed: false,
8474 icon: 'collapse',
8475 title: OO.ui.msg( 'ooui-outline-control-move-up' )
8476 } );
8477 this.downButton = new OO.ui.ButtonWidget( {
8478 $: this.$,
8479 framed: false,
8480 icon: 'expand',
8481 title: OO.ui.msg( 'ooui-outline-control-move-down' )
8482 } );
8483 this.removeButton = new OO.ui.ButtonWidget( {
8484 $: this.$,
8485 framed: false,
8486 icon: 'remove',
8487 title: OO.ui.msg( 'ooui-outline-control-remove' )
8488 } );
8489
8490 // Events
8491 outline.connect( this, {
8492 select: 'onOutlineChange',
8493 add: 'onOutlineChange',
8494 remove: 'onOutlineChange'
8495 } );
8496 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
8497 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
8498 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
8499
8500 // Initialization
8501 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
8502 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
8503 this.$movers
8504 .addClass( 'oo-ui-outlineControlsWidget-movers' )
8505 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
8506 this.$element.append( this.$icon, this.$group, this.$movers );
8507 };
8508
8509 /* Setup */
8510
8511 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
8512 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
8513 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
8514
8515 /* Events */
8516
8517 /**
8518 * @event move
8519 * @param {number} places Number of places to move
8520 */
8521
8522 /**
8523 * @event remove
8524 */
8525
8526 /* Methods */
8527
8528 /**
8529 * Handle outline change events.
8530 */
8531 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
8532 var i, len, firstMovable, lastMovable,
8533 items = this.outline.getItems(),
8534 selectedItem = this.outline.getSelectedItem(),
8535 movable = selectedItem && selectedItem.isMovable(),
8536 removable = selectedItem && selectedItem.isRemovable();
8537
8538 if ( movable ) {
8539 i = -1;
8540 len = items.length;
8541 while ( ++i < len ) {
8542 if ( items[i].isMovable() ) {
8543 firstMovable = items[i];
8544 break;
8545 }
8546 }
8547 i = len;
8548 while ( i-- ) {
8549 if ( items[i].isMovable() ) {
8550 lastMovable = items[i];
8551 break;
8552 }
8553 }
8554 }
8555 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
8556 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
8557 this.removeButton.setDisabled( !removable );
8558 };
8559
8560 /**
8561 * Mixin for widgets with a boolean on/off state.
8562 *
8563 * @abstract
8564 * @class
8565 *
8566 * @constructor
8567 * @param {Object} [config] Configuration options
8568 * @cfg {boolean} [value=false] Initial value
8569 */
8570 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
8571 // Configuration initialization
8572 config = config || {};
8573
8574 // Properties
8575 this.value = null;
8576
8577 // Initialization
8578 this.$element.addClass( 'oo-ui-toggleWidget' );
8579 this.setValue( !!config.value );
8580 };
8581
8582 /* Events */
8583
8584 /**
8585 * @event change
8586 * @param {boolean} value Changed value
8587 */
8588
8589 /* Methods */
8590
8591 /**
8592 * Get the value of the toggle.
8593 *
8594 * @return {boolean}
8595 */
8596 OO.ui.ToggleWidget.prototype.getValue = function () {
8597 return this.value;
8598 };
8599
8600 /**
8601 * Set the value of the toggle.
8602 *
8603 * @param {boolean} value New value
8604 * @fires change
8605 * @chainable
8606 */
8607 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
8608 value = !!value;
8609 if ( this.value !== value ) {
8610 this.value = value;
8611 this.emit( 'change', value );
8612 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
8613 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
8614 }
8615 return this;
8616 };
8617
8618 /**
8619 * Group widget for multiple related buttons.
8620 *
8621 * Use together with OO.ui.ButtonWidget.
8622 *
8623 * @class
8624 * @extends OO.ui.Widget
8625 * @mixins OO.ui.GroupElement
8626 *
8627 * @constructor
8628 * @param {Object} [config] Configuration options
8629 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
8630 */
8631 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
8632 // Configuration initialization
8633 config = config || {};
8634
8635 // Parent constructor
8636 OO.ui.ButtonGroupWidget.super.call( this, config );
8637
8638 // Mixin constructors
8639 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8640
8641 // Initialization
8642 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
8643 if ( $.isArray( config.items ) ) {
8644 this.addItems( config.items );
8645 }
8646 };
8647
8648 /* Setup */
8649
8650 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
8651 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
8652
8653 /**
8654 * Generic widget for buttons.
8655 *
8656 * @class
8657 * @extends OO.ui.Widget
8658 * @mixins OO.ui.ButtonElement
8659 * @mixins OO.ui.IconElement
8660 * @mixins OO.ui.IndicatorElement
8661 * @mixins OO.ui.LabelElement
8662 * @mixins OO.ui.TitledElement
8663 * @mixins OO.ui.FlaggedElement
8664 *
8665 * @constructor
8666 * @param {Object} [config] Configuration options
8667 * @cfg {string} [href] Hyperlink to visit when clicked
8668 * @cfg {string} [target] Target to open hyperlink in
8669 */
8670 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
8671 // Configuration initialization
8672 config = $.extend( { target: '_blank' }, config );
8673
8674 // Parent constructor
8675 OO.ui.ButtonWidget.super.call( this, config );
8676
8677 // Mixin constructors
8678 OO.ui.ButtonElement.call( this, config );
8679 OO.ui.IconElement.call( this, config );
8680 OO.ui.IndicatorElement.call( this, config );
8681 OO.ui.LabelElement.call( this, config );
8682 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
8683 OO.ui.FlaggedElement.call( this, config );
8684
8685 // Properties
8686 this.href = null;
8687 this.target = null;
8688 this.isHyperlink = false;
8689
8690 // Events
8691 this.$button.on( {
8692 click: this.onClick.bind( this ),
8693 keypress: this.onKeyPress.bind( this )
8694 } );
8695
8696 // Initialization
8697 this.$button.append( this.$icon, this.$label, this.$indicator );
8698 this.$element
8699 .addClass( 'oo-ui-buttonWidget' )
8700 .append( this.$button );
8701 this.setHref( config.href );
8702 this.setTarget( config.target );
8703 };
8704
8705 /* Setup */
8706
8707 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
8708 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
8709 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
8710 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
8711 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
8712 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
8713 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
8714
8715 /* Events */
8716
8717 /**
8718 * @event click
8719 */
8720
8721 /* Methods */
8722
8723 /**
8724 * Handles mouse click events.
8725 *
8726 * @param {jQuery.Event} e Mouse click event
8727 * @fires click
8728 */
8729 OO.ui.ButtonWidget.prototype.onClick = function () {
8730 if ( !this.isDisabled() ) {
8731 this.emit( 'click' );
8732 if ( this.isHyperlink ) {
8733 return true;
8734 }
8735 }
8736 return false;
8737 };
8738
8739 /**
8740 * Handles keypress events.
8741 *
8742 * @param {jQuery.Event} e Keypress event
8743 * @fires click
8744 */
8745 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
8746 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
8747 this.emit( 'click' );
8748 if ( this.isHyperlink ) {
8749 return true;
8750 }
8751 }
8752 return false;
8753 };
8754
8755 /**
8756 * Get hyperlink location.
8757 *
8758 * @return {string} Hyperlink location
8759 */
8760 OO.ui.ButtonWidget.prototype.getHref = function () {
8761 return this.href;
8762 };
8763
8764 /**
8765 * Get hyperlink target.
8766 *
8767 * @return {string} Hyperlink target
8768 */
8769 OO.ui.ButtonWidget.prototype.getTarget = function () {
8770 return this.target;
8771 };
8772
8773 /**
8774 * Set hyperlink location.
8775 *
8776 * @param {string|null} href Hyperlink location, null to remove
8777 */
8778 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
8779 href = typeof href === 'string' ? href : null;
8780
8781 if ( href !== this.href ) {
8782 this.href = href;
8783 if ( href !== null ) {
8784 this.$button.attr( 'href', href );
8785 this.isHyperlink = true;
8786 } else {
8787 this.$button.removeAttr( 'href' );
8788 this.isHyperlink = false;
8789 }
8790 }
8791
8792 return this;
8793 };
8794
8795 /**
8796 * Set hyperlink target.
8797 *
8798 * @param {string|null} target Hyperlink target, null to remove
8799 */
8800 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
8801 target = typeof target === 'string' ? target : null;
8802
8803 if ( target !== this.target ) {
8804 this.target = target;
8805 if ( target !== null ) {
8806 this.$button.attr( 'target', target );
8807 } else {
8808 this.$button.removeAttr( 'target' );
8809 }
8810 }
8811
8812 return this;
8813 };
8814
8815 /**
8816 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
8817 *
8818 * @class
8819 * @extends OO.ui.ButtonWidget
8820 * @mixins OO.ui.PendingElement
8821 *
8822 * @constructor
8823 * @param {Object} [config] Configuration options
8824 * @cfg {string} [action] Symbolic action name
8825 * @cfg {string[]} [modes] Symbolic mode names
8826 * @cfg {boolean} [framed=false] Render button with a frame
8827 */
8828 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
8829 // Configuration initialization
8830 config = $.extend( { framed: false }, config );
8831
8832 // Parent constructor
8833 OO.ui.ActionWidget.super.call( this, config );
8834
8835 // Mixin constructors
8836 OO.ui.PendingElement.call( this, config );
8837
8838 // Properties
8839 this.action = config.action || '';
8840 this.modes = config.modes || [];
8841 this.width = 0;
8842 this.height = 0;
8843
8844 // Initialization
8845 this.$element.addClass( 'oo-ui-actionWidget' );
8846 };
8847
8848 /* Setup */
8849
8850 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
8851 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
8852
8853 /* Events */
8854
8855 /**
8856 * @event resize
8857 */
8858
8859 /* Methods */
8860
8861 /**
8862 * Check if action is available in a certain mode.
8863 *
8864 * @param {string} mode Name of mode
8865 * @return {boolean} Has mode
8866 */
8867 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
8868 return this.modes.indexOf( mode ) !== -1;
8869 };
8870
8871 /**
8872 * Get symbolic action name.
8873 *
8874 * @return {string}
8875 */
8876 OO.ui.ActionWidget.prototype.getAction = function () {
8877 return this.action;
8878 };
8879
8880 /**
8881 * Get symbolic action name.
8882 *
8883 * @return {string}
8884 */
8885 OO.ui.ActionWidget.prototype.getModes = function () {
8886 return this.modes.slice();
8887 };
8888
8889 /**
8890 * Emit a resize event if the size has changed.
8891 *
8892 * @chainable
8893 */
8894 OO.ui.ActionWidget.prototype.propagateResize = function () {
8895 var width, height;
8896
8897 if ( this.isElementAttached() ) {
8898 width = this.$element.width();
8899 height = this.$element.height();
8900
8901 if ( width !== this.width || height !== this.height ) {
8902 this.width = width;
8903 this.height = height;
8904 this.emit( 'resize' );
8905 }
8906 }
8907
8908 return this;
8909 };
8910
8911 /**
8912 * @inheritdoc
8913 */
8914 OO.ui.ActionWidget.prototype.setIcon = function () {
8915 // Mixin method
8916 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
8917 this.propagateResize();
8918
8919 return this;
8920 };
8921
8922 /**
8923 * @inheritdoc
8924 */
8925 OO.ui.ActionWidget.prototype.setLabel = function () {
8926 // Mixin method
8927 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
8928 this.propagateResize();
8929
8930 return this;
8931 };
8932
8933 /**
8934 * @inheritdoc
8935 */
8936 OO.ui.ActionWidget.prototype.setFlags = function () {
8937 // Mixin method
8938 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
8939 this.propagateResize();
8940
8941 return this;
8942 };
8943
8944 /**
8945 * @inheritdoc
8946 */
8947 OO.ui.ActionWidget.prototype.clearFlags = function () {
8948 // Mixin method
8949 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
8950 this.propagateResize();
8951
8952 return this;
8953 };
8954
8955 /**
8956 * Toggle visibility of button.
8957 *
8958 * @param {boolean} [show] Show button, omit to toggle visibility
8959 * @chainable
8960 */
8961 OO.ui.ActionWidget.prototype.toggle = function () {
8962 // Parent method
8963 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
8964 this.propagateResize();
8965
8966 return this;
8967 };
8968
8969 /**
8970 * Button that shows and hides a popup.
8971 *
8972 * @class
8973 * @extends OO.ui.ButtonWidget
8974 * @mixins OO.ui.PopupElement
8975 *
8976 * @constructor
8977 * @param {Object} [config] Configuration options
8978 */
8979 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
8980 // Parent constructor
8981 OO.ui.PopupButtonWidget.super.call( this, config );
8982
8983 // Mixin constructors
8984 OO.ui.PopupElement.call( this, config );
8985
8986 // Initialization
8987 this.$element
8988 .addClass( 'oo-ui-popupButtonWidget' )
8989 .append( this.popup.$element );
8990 };
8991
8992 /* Setup */
8993
8994 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
8995 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
8996
8997 /* Methods */
8998
8999 /**
9000 * Handles mouse click events.
9001 *
9002 * @param {jQuery.Event} e Mouse click event
9003 */
9004 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
9005 // Skip clicks within the popup
9006 if ( $.contains( this.popup.$element[0], e.target ) ) {
9007 return;
9008 }
9009
9010 if ( !this.isDisabled() ) {
9011 this.popup.toggle();
9012 // Parent method
9013 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
9014 }
9015 return false;
9016 };
9017
9018 /**
9019 * Button that toggles on and off.
9020 *
9021 * @class
9022 * @extends OO.ui.ButtonWidget
9023 * @mixins OO.ui.ToggleWidget
9024 *
9025 * @constructor
9026 * @param {Object} [config] Configuration options
9027 * @cfg {boolean} [value=false] Initial value
9028 */
9029 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
9030 // Configuration initialization
9031 config = config || {};
9032
9033 // Parent constructor
9034 OO.ui.ToggleButtonWidget.super.call( this, config );
9035
9036 // Mixin constructors
9037 OO.ui.ToggleWidget.call( this, config );
9038
9039 // Initialization
9040 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
9041 };
9042
9043 /* Setup */
9044
9045 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
9046 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
9047
9048 /* Methods */
9049
9050 /**
9051 * @inheritdoc
9052 */
9053 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
9054 if ( !this.isDisabled() ) {
9055 this.setValue( !this.value );
9056 }
9057
9058 // Parent method
9059 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
9060 };
9061
9062 /**
9063 * @inheritdoc
9064 */
9065 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
9066 value = !!value;
9067 if ( value !== this.value ) {
9068 this.setActive( value );
9069 }
9070
9071 // Parent method (from mixin)
9072 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
9073
9074 return this;
9075 };
9076
9077 /**
9078 * Dropdown menu of options.
9079 *
9080 * Dropdown menus provide a control for accessing a menu and compose a menu within the widget, which
9081 * can be accessed using the #getMenu method.
9082 *
9083 * Use with OO.ui.MenuOptionWidget.
9084 *
9085 * @class
9086 * @extends OO.ui.Widget
9087 * @mixins OO.ui.IconElement
9088 * @mixins OO.ui.IndicatorElement
9089 * @mixins OO.ui.LabelElement
9090 * @mixins OO.ui.TitledElement
9091 *
9092 * @constructor
9093 * @param {Object} [config] Configuration options
9094 * @cfg {Object} [menu] Configuration options to pass to menu widget
9095 */
9096 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
9097 // Configuration initialization
9098 config = $.extend( { indicator: 'down' }, config );
9099
9100 // Parent constructor
9101 OO.ui.DropdownWidget.super.call( this, config );
9102
9103 // Mixin constructors
9104 OO.ui.IconElement.call( this, config );
9105 OO.ui.IndicatorElement.call( this, config );
9106 OO.ui.LabelElement.call( this, config );
9107 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9108
9109 // Properties
9110 this.menu = new OO.ui.MenuSelectWidget( $.extend( { $: this.$, widget: this }, config.menu ) );
9111 this.$handle = this.$( '<span>' );
9112
9113 // Events
9114 this.$element.on( { click: this.onClick.bind( this ) } );
9115 this.menu.connect( this, { select: 'onMenuSelect' } );
9116
9117 // Initialization
9118 this.$handle
9119 .addClass( 'oo-ui-dropdownWidget-handle' )
9120 .append( this.$icon, this.$label, this.$indicator );
9121 this.$element
9122 .addClass( 'oo-ui-dropdownWidget' )
9123 .append( this.$handle, this.menu.$element );
9124 };
9125
9126 /* Setup */
9127
9128 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
9129 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
9130 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
9131 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
9132 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
9133
9134 /* Methods */
9135
9136 /**
9137 * Get the menu.
9138 *
9139 * @return {OO.ui.MenuSelectWidget} Menu of widget
9140 */
9141 OO.ui.DropdownWidget.prototype.getMenu = function () {
9142 return this.menu;
9143 };
9144
9145 /**
9146 * Handles menu select events.
9147 *
9148 * @param {OO.ui.MenuOptionWidget} item Selected menu item
9149 */
9150 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
9151 var selectedLabel;
9152
9153 if ( !item ) {
9154 return;
9155 }
9156
9157 selectedLabel = item.getLabel();
9158
9159 // If the label is a DOM element, clone it, because setLabel will append() it
9160 if ( selectedLabel instanceof jQuery ) {
9161 selectedLabel = selectedLabel.clone();
9162 }
9163
9164 this.setLabel( selectedLabel );
9165 };
9166
9167 /**
9168 * Handles mouse click events.
9169 *
9170 * @param {jQuery.Event} e Mouse click event
9171 */
9172 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
9173 // Skip clicks within the menu
9174 if ( $.contains( this.menu.$element[0], e.target ) ) {
9175 return;
9176 }
9177
9178 if ( !this.isDisabled() ) {
9179 if ( this.menu.isVisible() ) {
9180 this.menu.toggle( false );
9181 } else {
9182 this.menu.toggle( true );
9183 }
9184 }
9185 return false;
9186 };
9187
9188 /**
9189 * Icon widget.
9190 *
9191 * See OO.ui.IconElement for more information.
9192 *
9193 * @class
9194 * @extends OO.ui.Widget
9195 * @mixins OO.ui.IconElement
9196 * @mixins OO.ui.TitledElement
9197 *
9198 * @constructor
9199 * @param {Object} [config] Configuration options
9200 */
9201 OO.ui.IconWidget = function OoUiIconWidget( config ) {
9202 // Configuration initialization
9203 config = config || {};
9204
9205 // Parent constructor
9206 OO.ui.IconWidget.super.call( this, config );
9207
9208 // Mixin constructors
9209 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
9210 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
9211
9212 // Initialization
9213 this.$element.addClass( 'oo-ui-iconWidget' );
9214 };
9215
9216 /* Setup */
9217
9218 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
9219 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
9220 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
9221
9222 /* Static Properties */
9223
9224 OO.ui.IconWidget.static.tagName = 'span';
9225
9226 /**
9227 * Indicator widget.
9228 *
9229 * See OO.ui.IndicatorElement for more information.
9230 *
9231 * @class
9232 * @extends OO.ui.Widget
9233 * @mixins OO.ui.IndicatorElement
9234 * @mixins OO.ui.TitledElement
9235 *
9236 * @constructor
9237 * @param {Object} [config] Configuration options
9238 */
9239 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
9240 // Configuration initialization
9241 config = config || {};
9242
9243 // Parent constructor
9244 OO.ui.IndicatorWidget.super.call( this, config );
9245
9246 // Mixin constructors
9247 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
9248 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
9249
9250 // Initialization
9251 this.$element.addClass( 'oo-ui-indicatorWidget' );
9252 };
9253
9254 /* Setup */
9255
9256 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
9257 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
9258 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
9259
9260 /* Static Properties */
9261
9262 OO.ui.IndicatorWidget.static.tagName = 'span';
9263
9264 /**
9265 * Base class for input widgets.
9266 *
9267 * @abstract
9268 * @class
9269 * @extends OO.ui.Widget
9270 * @mixins OO.ui.FlaggedElement
9271 *
9272 * @constructor
9273 * @param {Object} [config] Configuration options
9274 * @cfg {string} [name=''] HTML input name
9275 * @cfg {string} [value=''] Input value
9276 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
9277 */
9278 OO.ui.InputWidget = function OoUiInputWidget( config ) {
9279 // Configuration initialization
9280 config = config || {};
9281
9282 // Parent constructor
9283 OO.ui.InputWidget.super.call( this, config );
9284
9285 // Mixin constructors
9286 OO.ui.FlaggedElement.call( this, config );
9287
9288 // Properties
9289 this.$input = this.getInputElement( config );
9290 this.value = '';
9291 this.inputFilter = config.inputFilter;
9292
9293 // Events
9294 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
9295
9296 // Initialization
9297 this.$input
9298 .attr( 'name', config.name )
9299 .prop( 'disabled', this.isDisabled() );
9300 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
9301 this.setValue( config.value );
9302 };
9303
9304 /* Setup */
9305
9306 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
9307 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
9308
9309 /* Events */
9310
9311 /**
9312 * @event change
9313 * @param {string} value
9314 */
9315
9316 /* Methods */
9317
9318 /**
9319 * Get input element.
9320 *
9321 * @private
9322 * @param {Object} [config] Configuration options
9323 * @return {jQuery} Input element
9324 */
9325 OO.ui.InputWidget.prototype.getInputElement = function () {
9326 return this.$( '<input>' );
9327 };
9328
9329 /**
9330 * Handle potentially value-changing events.
9331 *
9332 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
9333 */
9334 OO.ui.InputWidget.prototype.onEdit = function () {
9335 var widget = this;
9336 if ( !this.isDisabled() ) {
9337 // Allow the stack to clear so the value will be updated
9338 setTimeout( function () {
9339 widget.setValue( widget.$input.val() );
9340 } );
9341 }
9342 };
9343
9344 /**
9345 * Get the value of the input.
9346 *
9347 * @return {string} Input value
9348 */
9349 OO.ui.InputWidget.prototype.getValue = function () {
9350 return this.value;
9351 };
9352
9353 /**
9354 * Sets the direction of the current input, either RTL or LTR
9355 *
9356 * @param {boolean} isRTL
9357 */
9358 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
9359 if ( isRTL ) {
9360 this.$input.removeClass( 'oo-ui-ltr' );
9361 this.$input.addClass( 'oo-ui-rtl' );
9362 } else {
9363 this.$input.removeClass( 'oo-ui-rtl' );
9364 this.$input.addClass( 'oo-ui-ltr' );
9365 }
9366 };
9367
9368 /**
9369 * Set the value of the input.
9370 *
9371 * @param {string} value New value
9372 * @fires change
9373 * @chainable
9374 */
9375 OO.ui.InputWidget.prototype.setValue = function ( value ) {
9376 value = this.cleanUpValue( value );
9377 if ( this.value !== value ) {
9378 this.value = value;
9379 this.emit( 'change', this.value );
9380 }
9381 // Update the DOM if it has changed. Note that with cleanUpValue, it
9382 // is possible for the DOM value to change without this.value changing.
9383 if ( this.$input.val() !== this.value ) {
9384 this.$input.val( this.value );
9385 }
9386 return this;
9387 };
9388
9389 /**
9390 * Clean up incoming value.
9391 *
9392 * Ensures value is a string, and converts undefined and null to empty string.
9393 *
9394 * @private
9395 * @param {string} value Original value
9396 * @return {string} Cleaned up value
9397 */
9398 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
9399 if ( value === undefined || value === null ) {
9400 return '';
9401 } else if ( this.inputFilter ) {
9402 return this.inputFilter( String( value ) );
9403 } else {
9404 return String( value );
9405 }
9406 };
9407
9408 /**
9409 * Simulate the behavior of clicking on a label bound to this input.
9410 */
9411 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
9412 if ( !this.isDisabled() ) {
9413 if ( this.$input.is( ':checkbox,:radio' ) ) {
9414 this.$input.click();
9415 } else if ( this.$input.is( ':input' ) ) {
9416 this.$input[0].focus();
9417 }
9418 }
9419 };
9420
9421 /**
9422 * @inheritdoc
9423 */
9424 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
9425 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
9426 if ( this.$input ) {
9427 this.$input.prop( 'disabled', this.isDisabled() );
9428 }
9429 return this;
9430 };
9431
9432 /**
9433 * Focus the input.
9434 *
9435 * @chainable
9436 */
9437 OO.ui.InputWidget.prototype.focus = function () {
9438 this.$input[0].focus();
9439 return this;
9440 };
9441
9442 /**
9443 * Blur the input.
9444 *
9445 * @chainable
9446 */
9447 OO.ui.InputWidget.prototype.blur = function () {
9448 this.$input[0].blur();
9449 return this;
9450 };
9451
9452 /**
9453 * A button that is an input widget. Intended to be used within a OO.ui.FormLayout.
9454 *
9455 * @class
9456 * @extends OO.ui.InputWidget
9457 * @mixins OO.ui.ButtonElement
9458 * @mixins OO.ui.IconElement
9459 * @mixins OO.ui.IndicatorElement
9460 * @mixins OO.ui.LabelElement
9461 * @mixins OO.ui.TitledElement
9462 * @mixins OO.ui.FlaggedElement
9463 *
9464 * @constructor
9465 * @param {Object} [config] Configuration options
9466 * @cfg {string} [type='button'] HTML tag `type` attribute, may be 'button', 'submit' or 'reset'
9467 * @cfg {boolean} [useInputTag=false] Whether to use `<input/>` rather than `<button/>`. Only useful
9468 * if you need IE 6 support in a form with multiple buttons. If you use this option, icons and
9469 * indicators will not be displayed, it won't be possible to have a non-plaintext label, and it
9470 * won't be possible to set a value (which will internally become identical to the label).
9471 */
9472 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
9473 // Configuration initialization
9474 config = $.extend( { type: 'button', useInputTag: false }, config );
9475
9476 // Properties (must be set before parent constructor, which calls #setValue)
9477 this.useInputTag = config.useInputTag;
9478
9479 // Parent constructor
9480 OO.ui.ButtonInputWidget.super.call( this, config );
9481
9482 // Mixin constructors
9483 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
9484 OO.ui.IconElement.call( this, config );
9485 OO.ui.IndicatorElement.call( this, config );
9486 OO.ui.LabelElement.call( this, config );
9487 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
9488 OO.ui.FlaggedElement.call( this, config );
9489
9490 // Events
9491 this.$input.on( {
9492 click: this.onClick.bind( this ),
9493 keypress: this.onKeyPress.bind( this )
9494 } );
9495
9496 // Initialization
9497 if ( !config.useInputTag ) {
9498 this.$input.append( this.$icon, this.$label, this.$indicator );
9499 }
9500 this.$element.addClass( 'oo-ui-buttonInputWidget' );
9501 };
9502
9503 /* Setup */
9504
9505 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
9506 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
9507 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
9508 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
9509 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
9510 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
9511 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
9512
9513 /* Events */
9514
9515 /**
9516 * @event click
9517 */
9518
9519 /* Methods */
9520
9521 /**
9522 * Get input element.
9523 *
9524 * @private
9525 * @param {Object} [config] Configuration options
9526 * @return {jQuery} Input element
9527 */
9528 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
9529 // Configuration initialization
9530 config = config || {};
9531
9532 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
9533
9534 return this.$( html );
9535 };
9536
9537 /**
9538 * Set label value.
9539 *
9540 * Overridden to support setting the 'value' of `<input/>` elements.
9541 *
9542 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
9543 * text; or null for no label
9544 * @chainable
9545 */
9546 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
9547 OO.ui.LabelElement.prototype.setLabel.call( this, label );
9548
9549 if ( this.useInputTag ) {
9550 if ( typeof label === 'function' ) {
9551 label = OO.ui.resolveMsg( label );
9552 }
9553 if ( label instanceof jQuery ) {
9554 label = label.text();
9555 }
9556 if ( !label ) {
9557 label = '';
9558 }
9559 this.$input.val( label );
9560 }
9561
9562 return this;
9563 };
9564
9565 /**
9566 * Set the value of the input.
9567 *
9568 * Overridden to disable for `<input/>` elements, which have value identical to the label.
9569 *
9570 * @param {string} value New value
9571 * @chainable
9572 */
9573 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
9574 if ( !this.useInputTag ) {
9575 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
9576 }
9577 return this;
9578 };
9579
9580 /**
9581 * Handles mouse click events.
9582 *
9583 * @param {jQuery.Event} e Mouse click event
9584 * @fires click
9585 */
9586 OO.ui.ButtonInputWidget.prototype.onClick = function () {
9587 if ( !this.isDisabled() ) {
9588 this.emit( 'click' );
9589 }
9590 return false;
9591 };
9592
9593 /**
9594 * Handles keypress events.
9595 *
9596 * @param {jQuery.Event} e Keypress event
9597 * @fires click
9598 */
9599 OO.ui.ButtonInputWidget.prototype.onKeyPress = function ( e ) {
9600 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
9601 this.emit( 'click' );
9602 }
9603 return false;
9604 };
9605
9606 /**
9607 * Checkbox input widget.
9608 *
9609 * @class
9610 * @extends OO.ui.InputWidget
9611 *
9612 * @constructor
9613 * @param {Object} [config] Configuration options
9614 */
9615 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
9616 // Parent constructor
9617 OO.ui.CheckboxInputWidget.super.call( this, config );
9618
9619 // Initialization
9620 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
9621 };
9622
9623 /* Setup */
9624
9625 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
9626
9627 /* Methods */
9628
9629 /**
9630 * Get input element.
9631 *
9632 * @private
9633 * @return {jQuery} Input element
9634 */
9635 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
9636 return this.$( '<input type="checkbox" />' );
9637 };
9638
9639 /**
9640 * Get checked state of the checkbox
9641 *
9642 * @return {boolean} If the checkbox is checked
9643 */
9644 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
9645 return this.value;
9646 };
9647
9648 /**
9649 * Set checked state of the checkbox
9650 *
9651 * @param {boolean} value New value
9652 */
9653 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
9654 value = !!value;
9655 if ( this.value !== value ) {
9656 this.value = value;
9657 this.$input.prop( 'checked', this.value );
9658 this.emit( 'change', this.value );
9659 }
9660 };
9661
9662 /**
9663 * @inheritdoc
9664 */
9665 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
9666 var widget = this;
9667 if ( !this.isDisabled() ) {
9668 // Allow the stack to clear so the value will be updated
9669 setTimeout( function () {
9670 widget.setValue( widget.$input.prop( 'checked' ) );
9671 } );
9672 }
9673 };
9674
9675 /**
9676 * Radio input widget.
9677 *
9678 * Radio buttons only make sense as a set, and you probably want to use the OO.ui.RadioSelectWidget
9679 * class instead of using this class directly.
9680 *
9681 * This class doesn't make it possible to learn whether the radio button is selected ("pressed").
9682 *
9683 * @class
9684 * @extends OO.ui.InputWidget
9685 *
9686 * @constructor
9687 * @param {Object} [config] Configuration options
9688 * @param {boolean} [config.selected=false] Whether the radio button is initially selected
9689 */
9690 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
9691 // Parent constructor
9692 OO.ui.RadioInputWidget.super.call( this, config );
9693
9694 // Initialization
9695 this.$element.addClass( 'oo-ui-radioInputWidget' );
9696 this.setSelected( config.selected !== undefined ? config.selected : false );
9697 };
9698
9699 /* Setup */
9700
9701 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
9702
9703 /* Methods */
9704
9705 /**
9706 * Get input element.
9707 *
9708 * @private
9709 * @return {jQuery} Input element
9710 */
9711 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
9712 return this.$( '<input type="radio" />' );
9713 };
9714
9715 /**
9716 * @inheritdoc
9717 */
9718 OO.ui.RadioInputWidget.prototype.onEdit = function () {
9719 // RadioInputWidget doesn't track its state.
9720 };
9721
9722 /**
9723 * Set selection state of this radio button.
9724 *
9725 * @param {boolean} state Whether the button is selected
9726 * @chainable
9727 */
9728 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
9729 // RadioInputWidget doesn't track its state.
9730 this.$input.prop( 'checked', state );
9731 return this;
9732 };
9733
9734 /**
9735 * Check if this radio button is selected.
9736 *
9737 * @return {boolean} Radio is selected
9738 */
9739 OO.ui.RadioInputWidget.prototype.isSelected = function () {
9740 return this.$input.prop( 'checked' );
9741 };
9742
9743 /**
9744 * Input widget with a text field.
9745 *
9746 * @class
9747 * @extends OO.ui.InputWidget
9748 * @mixins OO.ui.IconElement
9749 * @mixins OO.ui.IndicatorElement
9750 * @mixins OO.ui.PendingElement
9751 *
9752 * @constructor
9753 * @param {Object} [config] Configuration options
9754 * @cfg {string} [type='text'] HTML tag `type` attribute
9755 * @cfg {string} [placeholder] Placeholder text
9756 * @cfg {boolean} [readOnly=false] Prevent changes
9757 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9758 * @cfg {boolean} [autosize=false] Automatically resize to fit content
9759 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
9760 * @cfg {RegExp|string} [validate] Regular expression (or symbolic name referencing
9761 * one, see #static-validationPatterns)
9762 */
9763 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
9764 // Configuration initialization
9765 config = $.extend( { readOnly: false }, config );
9766
9767 // Parent constructor
9768 OO.ui.TextInputWidget.super.call( this, config );
9769
9770 // Mixin constructors
9771 OO.ui.IconElement.call( this, config );
9772 OO.ui.IndicatorElement.call( this, config );
9773 OO.ui.PendingElement.call( this, config );
9774
9775 // Properties
9776 this.readOnly = false;
9777 this.multiline = !!config.multiline;
9778 this.autosize = !!config.autosize;
9779 this.maxRows = config.maxRows !== undefined ? config.maxRows : 10;
9780 this.validate = null;
9781
9782 this.setValidation( config.validate );
9783
9784 // Events
9785 this.$input.on( {
9786 keypress: this.onKeyPress.bind( this ),
9787 blur: this.setValidityFlag.bind( this )
9788 } );
9789 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
9790 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
9791 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
9792
9793 // Initialization
9794 this.$element
9795 .addClass( 'oo-ui-textInputWidget' )
9796 .append( this.$icon, this.$indicator );
9797 this.setReadOnly( config.readOnly );
9798 if ( config.placeholder ) {
9799 this.$input.attr( 'placeholder', config.placeholder );
9800 }
9801 this.$element.attr( 'role', 'textbox' );
9802 };
9803
9804 /* Setup */
9805
9806 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
9807 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
9808 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
9809 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
9810
9811 /* Static properties */
9812
9813 OO.ui.TextInputWidget.static.validationPatterns = {
9814 'non-empty': /.+/,
9815 integer: /^\d+$/
9816 };
9817
9818 /* Events */
9819
9820 /**
9821 * User presses enter inside the text box.
9822 *
9823 * Not called if input is multiline.
9824 *
9825 * @event enter
9826 */
9827
9828 /**
9829 * User clicks the icon.
9830 *
9831 * @event icon
9832 */
9833
9834 /**
9835 * User clicks the indicator.
9836 *
9837 * @event indicator
9838 */
9839
9840 /* Methods */
9841
9842 /**
9843 * Handle icon mouse down events.
9844 *
9845 * @param {jQuery.Event} e Mouse down event
9846 * @fires icon
9847 */
9848 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
9849 if ( e.which === 1 ) {
9850 this.$input[0].focus();
9851 this.emit( 'icon' );
9852 return false;
9853 }
9854 };
9855
9856 /**
9857 * Handle indicator mouse down events.
9858 *
9859 * @param {jQuery.Event} e Mouse down event
9860 * @fires indicator
9861 */
9862 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
9863 if ( e.which === 1 ) {
9864 this.$input[0].focus();
9865 this.emit( 'indicator' );
9866 return false;
9867 }
9868 };
9869
9870 /**
9871 * Handle key press events.
9872 *
9873 * @param {jQuery.Event} e Key press event
9874 * @fires enter If enter key is pressed and input is not multiline
9875 */
9876 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
9877 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
9878 this.emit( 'enter', e );
9879 }
9880 };
9881
9882 /**
9883 * Handle element attach events.
9884 *
9885 * @param {jQuery.Event} e Element attach event
9886 */
9887 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
9888 this.adjustSize();
9889 };
9890
9891 /**
9892 * @inheritdoc
9893 */
9894 OO.ui.TextInputWidget.prototype.onEdit = function () {
9895 this.adjustSize();
9896
9897 // Parent method
9898 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
9899 };
9900
9901 /**
9902 * @inheritdoc
9903 */
9904 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
9905 // Parent method
9906 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
9907
9908 this.setValidityFlag();
9909 this.adjustSize();
9910 return this;
9911 };
9912
9913 /**
9914 * Check if the widget is read-only.
9915 *
9916 * @return {boolean}
9917 */
9918 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
9919 return this.readOnly;
9920 };
9921
9922 /**
9923 * Set the read-only state of the widget.
9924 *
9925 * This should probably change the widget's appearance and prevent it from being used.
9926 *
9927 * @param {boolean} state Make input read-only
9928 * @chainable
9929 */
9930 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
9931 this.readOnly = !!state;
9932 this.$input.prop( 'readOnly', this.readOnly );
9933 return this;
9934 };
9935
9936 /**
9937 * Automatically adjust the size of the text input.
9938 *
9939 * This only affects multi-line inputs that are auto-sized.
9940 *
9941 * @chainable
9942 */
9943 OO.ui.TextInputWidget.prototype.adjustSize = function () {
9944 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
9945
9946 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
9947 $clone = this.$input.clone()
9948 .val( this.$input.val() )
9949 // Set inline height property to 0 to measure scroll height
9950 .css( 'height', 0 )
9951 .insertAfter( this.$input );
9952 this.valCache = this.$input.val();
9953 scrollHeight = $clone[0].scrollHeight;
9954 // Remove inline height property to measure natural heights
9955 $clone.css( 'height', '' );
9956 innerHeight = $clone.innerHeight();
9957 outerHeight = $clone.outerHeight();
9958 // Measure max rows height
9959 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' ).val( '' );
9960 maxInnerHeight = $clone.innerHeight();
9961 // Difference between reported innerHeight and scrollHeight with no scrollbars present
9962 // Equals 1 on Blink-based browsers and 0 everywhere else
9963 measurementError = maxInnerHeight - $clone[0].scrollHeight;
9964 $clone.remove();
9965 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
9966 // Only apply inline height when expansion beyond natural height is needed
9967 if ( idealHeight > innerHeight ) {
9968 // Use the difference between the inner and outer height as a buffer
9969 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
9970 } else {
9971 this.$input.css( 'height', '' );
9972 }
9973 }
9974 return this;
9975 };
9976
9977 /**
9978 * Get input element.
9979 *
9980 * @private
9981 * @param {Object} [config] Configuration options
9982 * @return {jQuery} Input element
9983 */
9984 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
9985 // Configuration initialization
9986 config = config || {};
9987
9988 var type = config.type || 'text';
9989
9990 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="' + type + '" />' );
9991 };
9992
9993 /**
9994 * Check if input supports multiple lines.
9995 *
9996 * @return {boolean}
9997 */
9998 OO.ui.TextInputWidget.prototype.isMultiline = function () {
9999 return !!this.multiline;
10000 };
10001
10002 /**
10003 * Check if input automatically adjusts its size.
10004 *
10005 * @return {boolean}
10006 */
10007 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
10008 return !!this.autosize;
10009 };
10010
10011 /**
10012 * Select the contents of the input.
10013 *
10014 * @chainable
10015 */
10016 OO.ui.TextInputWidget.prototype.select = function () {
10017 this.$input.select();
10018 return this;
10019 };
10020
10021 /**
10022 * Sets the validation pattern to use.
10023 * @param {RegExp|string|null} validate Regular expression (or symbolic name referencing
10024 * one, see #static-validationPatterns)
10025 */
10026 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10027 if ( validate instanceof RegExp ) {
10028 this.validate = validate;
10029 } else {
10030 this.validate = this.constructor.static.validationPatterns[validate] || /.*/;
10031 }
10032 };
10033
10034 /**
10035 * Sets the 'invalid' flag appropriately.
10036 */
10037 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
10038 var widget = this;
10039 this.isValid().done( function ( valid ) {
10040 widget.setFlags( { invalid: !valid } );
10041 } );
10042 };
10043
10044 /**
10045 * Returns whether or not the current value is considered valid, according to the
10046 * supplied validation pattern.
10047 *
10048 * @return {jQuery.Deferred}
10049 */
10050 OO.ui.TextInputWidget.prototype.isValid = function () {
10051 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
10052 };
10053
10054 /**
10055 * Text input with a menu of optional values.
10056 *
10057 * @class
10058 * @extends OO.ui.Widget
10059 *
10060 * @constructor
10061 * @param {Object} [config] Configuration options
10062 * @cfg {Object} [menu] Configuration options to pass to menu widget
10063 * @cfg {Object} [input] Configuration options to pass to input widget
10064 * @cfg {jQuery} [$overlay] Overlay layer; defaults to relative positioning
10065 */
10066 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
10067 // Configuration initialization
10068 config = config || {};
10069
10070 // Parent constructor
10071 OO.ui.ComboBoxWidget.super.call( this, config );
10072
10073 // Properties
10074 this.$overlay = config.$overlay || this.$element;
10075 this.input = new OO.ui.TextInputWidget( $.extend(
10076 { $: this.$, indicator: 'down', disabled: this.isDisabled() },
10077 config.input
10078 ) );
10079 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
10080 {
10081 $: OO.ui.Element.getJQuery( this.$overlay ),
10082 widget: this,
10083 input: this.input,
10084 disabled: this.isDisabled()
10085 },
10086 config.menu
10087 ) );
10088
10089 // Events
10090 this.input.connect( this, {
10091 change: 'onInputChange',
10092 indicator: 'onInputIndicator',
10093 enter: 'onInputEnter'
10094 } );
10095 this.menu.connect( this, {
10096 choose: 'onMenuChoose',
10097 add: 'onMenuItemsChange',
10098 remove: 'onMenuItemsChange'
10099 } );
10100
10101 // Initialization
10102 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
10103 this.$overlay.append( this.menu.$element );
10104 this.onMenuItemsChange();
10105 };
10106
10107 /* Setup */
10108
10109 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
10110
10111 /* Methods */
10112
10113 /**
10114 * Get the combobox's menu.
10115 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
10116 */
10117 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
10118 return this.menu;
10119 };
10120
10121 /**
10122 * Handle input change events.
10123 *
10124 * @param {string} value New value
10125 */
10126 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
10127 var match = this.menu.getItemFromData( value );
10128
10129 this.menu.selectItem( match );
10130
10131 if ( !this.isDisabled() ) {
10132 this.menu.toggle( true );
10133 }
10134 };
10135
10136 /**
10137 * Handle input indicator events.
10138 */
10139 OO.ui.ComboBoxWidget.prototype.onInputIndicator = function () {
10140 if ( !this.isDisabled() ) {
10141 this.menu.toggle();
10142 }
10143 };
10144
10145 /**
10146 * Handle input enter events.
10147 */
10148 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
10149 if ( !this.isDisabled() ) {
10150 this.menu.toggle( false );
10151 }
10152 };
10153
10154 /**
10155 * Handle menu choose events.
10156 *
10157 * @param {OO.ui.OptionWidget} item Chosen item
10158 */
10159 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
10160 if ( item ) {
10161 this.input.setValue( item.getData() );
10162 }
10163 };
10164
10165 /**
10166 * Handle menu item change events.
10167 */
10168 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
10169 var match = this.menu.getItemFromData( this.input.getValue() );
10170 this.menu.selectItem( match );
10171 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
10172 };
10173
10174 /**
10175 * @inheritdoc
10176 */
10177 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
10178 // Parent method
10179 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
10180
10181 if ( this.input ) {
10182 this.input.setDisabled( this.isDisabled() );
10183 }
10184 if ( this.menu ) {
10185 this.menu.setDisabled( this.isDisabled() );
10186 }
10187
10188 return this;
10189 };
10190
10191 /**
10192 * Label widget.
10193 *
10194 * @class
10195 * @extends OO.ui.Widget
10196 * @mixins OO.ui.LabelElement
10197 *
10198 * @constructor
10199 * @param {Object} [config] Configuration options
10200 * @cfg {OO.ui.InputWidget} [input] Input widget this label is for
10201 */
10202 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
10203 // Configuration initialization
10204 config = config || {};
10205
10206 // Parent constructor
10207 OO.ui.LabelWidget.super.call( this, config );
10208
10209 // Mixin constructors
10210 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
10211 OO.ui.TitledElement.call( this, config );
10212
10213 // Properties
10214 this.input = config.input;
10215
10216 // Events
10217 if ( this.input instanceof OO.ui.InputWidget ) {
10218 this.$element.on( 'click', this.onClick.bind( this ) );
10219 }
10220
10221 // Initialization
10222 this.$element.addClass( 'oo-ui-labelWidget' );
10223 };
10224
10225 /* Setup */
10226
10227 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
10228 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
10229 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
10230
10231 /* Static Properties */
10232
10233 OO.ui.LabelWidget.static.tagName = 'span';
10234
10235 /* Methods */
10236
10237 /**
10238 * Handles label mouse click events.
10239 *
10240 * @param {jQuery.Event} e Mouse click event
10241 */
10242 OO.ui.LabelWidget.prototype.onClick = function () {
10243 this.input.simulateLabelClick();
10244 return false;
10245 };
10246
10247 /**
10248 * Generic option widget for use with OO.ui.SelectWidget.
10249 *
10250 * @class
10251 * @extends OO.ui.Widget
10252 * @mixins OO.ui.LabelElement
10253 * @mixins OO.ui.FlaggedElement
10254 *
10255 * @constructor
10256 * @param {Object} [config] Configuration options
10257 */
10258 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
10259 // Configuration initialization
10260 config = config || {};
10261
10262 // Parent constructor
10263 OO.ui.OptionWidget.super.call( this, config );
10264
10265 // Mixin constructors
10266 OO.ui.ItemWidget.call( this );
10267 OO.ui.LabelElement.call( this, config );
10268 OO.ui.FlaggedElement.call( this, config );
10269
10270 // Properties
10271 this.selected = false;
10272 this.highlighted = false;
10273 this.pressed = false;
10274
10275 // Initialization
10276 this.$element
10277 .data( 'oo-ui-optionWidget', this )
10278 .attr( 'role', 'option' )
10279 .addClass( 'oo-ui-optionWidget' )
10280 .append( this.$label );
10281 };
10282
10283 /* Setup */
10284
10285 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
10286 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
10287 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
10288 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
10289
10290 /* Static Properties */
10291
10292 OO.ui.OptionWidget.static.selectable = true;
10293
10294 OO.ui.OptionWidget.static.highlightable = true;
10295
10296 OO.ui.OptionWidget.static.pressable = true;
10297
10298 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
10299
10300 /* Methods */
10301
10302 /**
10303 * Check if option can be selected.
10304 *
10305 * @return {boolean} Item is selectable
10306 */
10307 OO.ui.OptionWidget.prototype.isSelectable = function () {
10308 return this.constructor.static.selectable && !this.isDisabled();
10309 };
10310
10311 /**
10312 * Check if option can be highlighted.
10313 *
10314 * @return {boolean} Item is highlightable
10315 */
10316 OO.ui.OptionWidget.prototype.isHighlightable = function () {
10317 return this.constructor.static.highlightable && !this.isDisabled();
10318 };
10319
10320 /**
10321 * Check if option can be pressed.
10322 *
10323 * @return {boolean} Item is pressable
10324 */
10325 OO.ui.OptionWidget.prototype.isPressable = function () {
10326 return this.constructor.static.pressable && !this.isDisabled();
10327 };
10328
10329 /**
10330 * Check if option is selected.
10331 *
10332 * @return {boolean} Item is selected
10333 */
10334 OO.ui.OptionWidget.prototype.isSelected = function () {
10335 return this.selected;
10336 };
10337
10338 /**
10339 * Check if option is highlighted.
10340 *
10341 * @return {boolean} Item is highlighted
10342 */
10343 OO.ui.OptionWidget.prototype.isHighlighted = function () {
10344 return this.highlighted;
10345 };
10346
10347 /**
10348 * Check if option is pressed.
10349 *
10350 * @return {boolean} Item is pressed
10351 */
10352 OO.ui.OptionWidget.prototype.isPressed = function () {
10353 return this.pressed;
10354 };
10355
10356 /**
10357 * Set selected state.
10358 *
10359 * @param {boolean} [state=false] Select option
10360 * @chainable
10361 */
10362 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
10363 if ( this.constructor.static.selectable ) {
10364 this.selected = !!state;
10365 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
10366 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
10367 this.scrollElementIntoView();
10368 }
10369 this.updateThemeClasses();
10370 }
10371 return this;
10372 };
10373
10374 /**
10375 * Set highlighted state.
10376 *
10377 * @param {boolean} [state=false] Highlight option
10378 * @chainable
10379 */
10380 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
10381 if ( this.constructor.static.highlightable ) {
10382 this.highlighted = !!state;
10383 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
10384 this.updateThemeClasses();
10385 }
10386 return this;
10387 };
10388
10389 /**
10390 * Set pressed state.
10391 *
10392 * @param {boolean} [state=false] Press option
10393 * @chainable
10394 */
10395 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
10396 if ( this.constructor.static.pressable ) {
10397 this.pressed = !!state;
10398 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
10399 this.updateThemeClasses();
10400 }
10401 return this;
10402 };
10403
10404 /**
10405 * Make the option's highlight flash.
10406 *
10407 * While flashing, the visual style of the pressed state is removed if present.
10408 *
10409 * @return {jQuery.Promise} Promise resolved when flashing is done
10410 */
10411 OO.ui.OptionWidget.prototype.flash = function () {
10412 var widget = this,
10413 $element = this.$element,
10414 deferred = $.Deferred();
10415
10416 if ( !this.isDisabled() && this.constructor.static.pressable ) {
10417 $element.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
10418 setTimeout( function () {
10419 // Restore original classes
10420 $element
10421 .toggleClass( 'oo-ui-optionWidget-highlighted', widget.highlighted )
10422 .toggleClass( 'oo-ui-optionWidget-pressed', widget.pressed );
10423
10424 setTimeout( function () {
10425 deferred.resolve();
10426 }, 100 );
10427
10428 }, 100 );
10429 }
10430
10431 return deferred.promise();
10432 };
10433
10434 /**
10435 * Option widget with an option icon and indicator.
10436 *
10437 * Use together with OO.ui.SelectWidget.
10438 *
10439 * @class
10440 * @extends OO.ui.OptionWidget
10441 * @mixins OO.ui.IconElement
10442 * @mixins OO.ui.IndicatorElement
10443 *
10444 * @constructor
10445 * @param {Object} [config] Configuration options
10446 */
10447 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
10448 // Parent constructor
10449 OO.ui.DecoratedOptionWidget.super.call( this, config );
10450
10451 // Mixin constructors
10452 OO.ui.IconElement.call( this, config );
10453 OO.ui.IndicatorElement.call( this, config );
10454
10455 // Initialization
10456 this.$element
10457 .addClass( 'oo-ui-decoratedOptionWidget' )
10458 .prepend( this.$icon )
10459 .append( this.$indicator );
10460 };
10461
10462 /* Setup */
10463
10464 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
10465 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
10466 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
10467
10468 /**
10469 * Option widget that looks like a button.
10470 *
10471 * Use together with OO.ui.ButtonSelectWidget.
10472 *
10473 * @class
10474 * @extends OO.ui.DecoratedOptionWidget
10475 * @mixins OO.ui.ButtonElement
10476 *
10477 * @constructor
10478 * @param {Object} [config] Configuration options
10479 */
10480 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
10481 // Parent constructor
10482 OO.ui.ButtonOptionWidget.super.call( this, config );
10483
10484 // Mixin constructors
10485 OO.ui.ButtonElement.call( this, config );
10486
10487 // Initialization
10488 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
10489 this.$button.append( this.$element.contents() );
10490 this.$element.append( this.$button );
10491 };
10492
10493 /* Setup */
10494
10495 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
10496 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
10497
10498 /* Static Properties */
10499
10500 // Allow button mouse down events to pass through so they can be handled by the parent select widget
10501 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
10502
10503 /* Methods */
10504
10505 /**
10506 * @inheritdoc
10507 */
10508 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
10509 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
10510
10511 if ( this.constructor.static.selectable ) {
10512 this.setActive( state );
10513 }
10514
10515 return this;
10516 };
10517
10518 /**
10519 * Option widget that looks like a radio button.
10520 *
10521 * Use together with OO.ui.RadioSelectWidget.
10522 *
10523 * @class
10524 * @extends OO.ui.OptionWidget
10525 *
10526 * @constructor
10527 * @param {Object} [config] Configuration options
10528 */
10529 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
10530 // Parent constructor
10531 OO.ui.RadioOptionWidget.super.call( this, config );
10532
10533 // Properties
10534 this.radio = new OO.ui.RadioInputWidget( { value: config.data } );
10535
10536 // Initialization
10537 this.$element
10538 .addClass( 'oo-ui-radioOptionWidget' )
10539 .prepend( this.radio.$element );
10540 };
10541
10542 /* Setup */
10543
10544 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
10545
10546 /* Static Properties */
10547
10548 OO.ui.RadioOptionWidget.static.highlightable = false;
10549
10550 OO.ui.RadioOptionWidget.static.pressable = false;
10551
10552 /* Methods */
10553
10554 /**
10555 * @inheritdoc
10556 */
10557 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
10558 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
10559
10560 this.radio.setSelected( state );
10561
10562 return this;
10563 };
10564
10565 /**
10566 * Item of an OO.ui.MenuSelectWidget.
10567 *
10568 * @class
10569 * @extends OO.ui.DecoratedOptionWidget
10570 *
10571 * @constructor
10572 * @param {Object} [config] Configuration options
10573 */
10574 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
10575 // Configuration initialization
10576 config = $.extend( { icon: 'check' }, config );
10577
10578 // Parent constructor
10579 OO.ui.MenuOptionWidget.super.call( this, config );
10580
10581 // Initialization
10582 this.$element
10583 .attr( 'role', 'menuitem' )
10584 .addClass( 'oo-ui-menuOptionWidget' );
10585 };
10586
10587 /* Setup */
10588
10589 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
10590
10591 /**
10592 * Section to group one or more items in a OO.ui.MenuSelectWidget.
10593 *
10594 * @class
10595 * @extends OO.ui.DecoratedOptionWidget
10596 *
10597 * @constructor
10598 * @param {Object} [config] Configuration options
10599 */
10600 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
10601 // Parent constructor
10602 OO.ui.MenuSectionOptionWidget.super.call( this, config );
10603
10604 // Initialization
10605 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
10606 };
10607
10608 /* Setup */
10609
10610 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
10611
10612 /* Static Properties */
10613
10614 OO.ui.MenuSectionOptionWidget.static.selectable = false;
10615
10616 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
10617
10618 /**
10619 * Items for an OO.ui.OutlineSelectWidget.
10620 *
10621 * @class
10622 * @extends OO.ui.DecoratedOptionWidget
10623 *
10624 * @constructor
10625 * @param {Object} [config] Configuration options
10626 * @cfg {number} [level] Indentation level
10627 * @cfg {boolean} [movable] Allow modification from outline controls
10628 */
10629 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
10630 // Configuration initialization
10631 config = config || {};
10632
10633 // Parent constructor
10634 OO.ui.OutlineOptionWidget.super.call( this, config );
10635
10636 // Properties
10637 this.level = 0;
10638 this.movable = !!config.movable;
10639 this.removable = !!config.removable;
10640
10641 // Initialization
10642 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
10643 this.setLevel( config.level );
10644 };
10645
10646 /* Setup */
10647
10648 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
10649
10650 /* Static Properties */
10651
10652 OO.ui.OutlineOptionWidget.static.highlightable = false;
10653
10654 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
10655
10656 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
10657
10658 OO.ui.OutlineOptionWidget.static.levels = 3;
10659
10660 /* Methods */
10661
10662 /**
10663 * Check if item is movable.
10664 *
10665 * Movability is used by outline controls.
10666 *
10667 * @return {boolean} Item is movable
10668 */
10669 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
10670 return this.movable;
10671 };
10672
10673 /**
10674 * Check if item is removable.
10675 *
10676 * Removability is used by outline controls.
10677 *
10678 * @return {boolean} Item is removable
10679 */
10680 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
10681 return this.removable;
10682 };
10683
10684 /**
10685 * Get indentation level.
10686 *
10687 * @return {number} Indentation level
10688 */
10689 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
10690 return this.level;
10691 };
10692
10693 /**
10694 * Set movability.
10695 *
10696 * Movability is used by outline controls.
10697 *
10698 * @param {boolean} movable Item is movable
10699 * @chainable
10700 */
10701 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
10702 this.movable = !!movable;
10703 this.updateThemeClasses();
10704 return this;
10705 };
10706
10707 /**
10708 * Set removability.
10709 *
10710 * Removability is used by outline controls.
10711 *
10712 * @param {boolean} movable Item is removable
10713 * @chainable
10714 */
10715 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
10716 this.removable = !!removable;
10717 this.updateThemeClasses();
10718 return this;
10719 };
10720
10721 /**
10722 * Set indentation level.
10723 *
10724 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
10725 * @chainable
10726 */
10727 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
10728 var levels = this.constructor.static.levels,
10729 levelClass = this.constructor.static.levelClass,
10730 i = levels;
10731
10732 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
10733 while ( i-- ) {
10734 if ( this.level === i ) {
10735 this.$element.addClass( levelClass + i );
10736 } else {
10737 this.$element.removeClass( levelClass + i );
10738 }
10739 }
10740 this.updateThemeClasses();
10741
10742 return this;
10743 };
10744
10745 /**
10746 * Container for content that is overlaid and positioned absolutely.
10747 *
10748 * @class
10749 * @extends OO.ui.Widget
10750 * @mixins OO.ui.LabelElement
10751 *
10752 * @constructor
10753 * @param {Object} [config] Configuration options
10754 * @cfg {number} [width=320] Width of popup in pixels
10755 * @cfg {number} [height] Height of popup, omit to use automatic height
10756 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
10757 * @cfg {string} [align='center'] Alignment of popup to origin
10758 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
10759 * @cfg {number} [containerPadding=10] How much padding to keep between popup and container
10760 * @cfg {jQuery} [$content] Content to append to the popup's body
10761 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
10762 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
10763 * @cfg {boolean} [head] Show label and close button at the top
10764 * @cfg {boolean} [padded] Add padding to the body
10765 */
10766 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
10767 // Configuration initialization
10768 config = config || {};
10769
10770 // Parent constructor
10771 OO.ui.PopupWidget.super.call( this, config );
10772
10773 // Mixin constructors
10774 OO.ui.LabelElement.call( this, config );
10775 OO.ui.ClippableElement.call( this, config );
10776
10777 // Properties
10778 this.visible = false;
10779 this.$popup = this.$( '<div>' );
10780 this.$head = this.$( '<div>' );
10781 this.$body = this.$( '<div>' );
10782 this.$anchor = this.$( '<div>' );
10783 // If undefined, will be computed lazily in updateDimensions()
10784 this.$container = config.$container;
10785 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
10786 this.autoClose = !!config.autoClose;
10787 this.$autoCloseIgnore = config.$autoCloseIgnore;
10788 this.transitionTimeout = null;
10789 this.anchor = null;
10790 this.width = config.width !== undefined ? config.width : 320;
10791 this.height = config.height !== undefined ? config.height : null;
10792 this.align = config.align || 'center';
10793 this.closeButton = new OO.ui.ButtonWidget( { $: this.$, framed: false, icon: 'close' } );
10794 this.onMouseDownHandler = this.onMouseDown.bind( this );
10795
10796 // Events
10797 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
10798
10799 // Initialization
10800 this.toggleAnchor( config.anchor === undefined || config.anchor );
10801 this.$body.addClass( 'oo-ui-popupWidget-body' );
10802 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
10803 this.$head
10804 .addClass( 'oo-ui-popupWidget-head' )
10805 .append( this.$label, this.closeButton.$element );
10806 if ( !config.head ) {
10807 this.$head.hide();
10808 }
10809 this.$popup
10810 .addClass( 'oo-ui-popupWidget-popup' )
10811 .append( this.$head, this.$body );
10812 this.$element
10813 .hide()
10814 .addClass( 'oo-ui-popupWidget' )
10815 .append( this.$popup, this.$anchor );
10816 // Move content, which was added to #$element by OO.ui.Widget, to the body
10817 if ( config.$content instanceof jQuery ) {
10818 this.$body.append( config.$content );
10819 }
10820 if ( config.padded ) {
10821 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
10822 }
10823 this.setClippableElement( this.$body );
10824 };
10825
10826 /* Setup */
10827
10828 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
10829 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
10830 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
10831
10832 /* Methods */
10833
10834 /**
10835 * Handles mouse down events.
10836 *
10837 * @param {jQuery.Event} e Mouse down event
10838 */
10839 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
10840 if (
10841 this.isVisible() &&
10842 !$.contains( this.$element[0], e.target ) &&
10843 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
10844 ) {
10845 this.toggle( false );
10846 }
10847 };
10848
10849 /**
10850 * Bind mouse down listener.
10851 */
10852 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
10853 // Capture clicks outside popup
10854 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
10855 };
10856
10857 /**
10858 * Handles close button click events.
10859 */
10860 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
10861 if ( this.isVisible() ) {
10862 this.toggle( false );
10863 }
10864 };
10865
10866 /**
10867 * Unbind mouse down listener.
10868 */
10869 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
10870 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
10871 };
10872
10873 /**
10874 * Set whether to show a anchor.
10875 *
10876 * @param {boolean} [show] Show anchor, omit to toggle
10877 */
10878 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
10879 show = show === undefined ? !this.anchored : !!show;
10880
10881 if ( this.anchored !== show ) {
10882 if ( show ) {
10883 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
10884 } else {
10885 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
10886 }
10887 this.anchored = show;
10888 }
10889 };
10890
10891 /**
10892 * Check if showing a anchor.
10893 *
10894 * @return {boolean} anchor is visible
10895 */
10896 OO.ui.PopupWidget.prototype.hasAnchor = function () {
10897 return this.anchor;
10898 };
10899
10900 /**
10901 * @inheritdoc
10902 */
10903 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
10904 show = show === undefined ? !this.isVisible() : !!show;
10905
10906 var change = show !== this.isVisible();
10907
10908 // Parent method
10909 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
10910
10911 if ( change ) {
10912 if ( show ) {
10913 if ( this.autoClose ) {
10914 this.bindMouseDownListener();
10915 }
10916 this.updateDimensions();
10917 this.toggleClipping( true );
10918 } else {
10919 this.toggleClipping( false );
10920 if ( this.autoClose ) {
10921 this.unbindMouseDownListener();
10922 }
10923 }
10924 }
10925
10926 return this;
10927 };
10928
10929 /**
10930 * Set the size of the popup.
10931 *
10932 * Changing the size may also change the popup's position depending on the alignment.
10933 *
10934 * @param {number} width Width
10935 * @param {number} height Height
10936 * @param {boolean} [transition=false] Use a smooth transition
10937 * @chainable
10938 */
10939 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
10940 this.width = width;
10941 this.height = height !== undefined ? height : null;
10942 if ( this.isVisible() ) {
10943 this.updateDimensions( transition );
10944 }
10945 };
10946
10947 /**
10948 * Update the size and position.
10949 *
10950 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
10951 * be called automatically.
10952 *
10953 * @param {boolean} [transition=false] Use a smooth transition
10954 * @chainable
10955 */
10956 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
10957 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
10958 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
10959 widget = this;
10960
10961 if ( !this.$container ) {
10962 // Lazy-initialize $container if not specified in constructor
10963 this.$container = this.$( this.getClosestScrollableElementContainer() );
10964 }
10965
10966 // Set height and width before measuring things, since it might cause our measurements
10967 // to change (e.g. due to scrollbars appearing or disappearing)
10968 this.$popup.css( {
10969 width: this.width,
10970 height: this.height !== null ? this.height : 'auto'
10971 } );
10972
10973 // Compute initial popupOffset based on alignment
10974 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[this.align];
10975
10976 // Figure out if this will cause the popup to go beyond the edge of the container
10977 originOffset = Math.round( this.$element.offset().left );
10978 containerLeft = Math.round( this.$container.offset().left );
10979 containerWidth = this.$container.innerWidth();
10980 containerRight = containerLeft + containerWidth;
10981 popupLeft = popupOffset - this.containerPadding;
10982 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
10983 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
10984 overlapRight = containerRight - ( originOffset + popupRight );
10985
10986 // Adjust offset to make the popup not go beyond the edge, if needed
10987 if ( overlapRight < 0 ) {
10988 popupOffset += overlapRight;
10989 } else if ( overlapLeft < 0 ) {
10990 popupOffset -= overlapLeft;
10991 }
10992
10993 // Adjust offset to avoid anchor being rendered too close to the edge
10994 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
10995 // TODO: Find a measurement that works for CSS anchors and image anchors
10996 anchorWidth = this.$anchor[0].scrollWidth * 2;
10997 if ( popupOffset + this.width < anchorWidth ) {
10998 popupOffset = anchorWidth - this.width;
10999 } else if ( -popupOffset < anchorWidth ) {
11000 popupOffset = -anchorWidth;
11001 }
11002
11003 // Prevent transition from being interrupted
11004 clearTimeout( this.transitionTimeout );
11005 if ( transition ) {
11006 // Enable transition
11007 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
11008 }
11009
11010 // Position body relative to anchor
11011 this.$popup.css( 'margin-left', popupOffset );
11012
11013 if ( transition ) {
11014 // Prevent transitioning after transition is complete
11015 this.transitionTimeout = setTimeout( function () {
11016 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
11017 }, 200 );
11018 } else {
11019 // Prevent transitioning immediately
11020 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
11021 }
11022
11023 // Reevaluate clipping state since we've relocated and resized the popup
11024 this.clip();
11025
11026 return this;
11027 };
11028
11029 /**
11030 * Progress bar widget.
11031 *
11032 * @class
11033 * @extends OO.ui.Widget
11034 *
11035 * @constructor
11036 * @param {Object} [config] Configuration options
11037 * @cfg {number|boolean} [progress=false] Initial progress percent or false for indeterminate
11038 */
11039 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
11040 // Configuration initialization
11041 config = config || {};
11042
11043 // Parent constructor
11044 OO.ui.ProgressBarWidget.super.call( this, config );
11045
11046 // Properties
11047 this.$bar = this.$( '<div>' );
11048 this.progress = null;
11049
11050 // Initialization
11051 this.setProgress( config.progress !== undefined ? config.progress : false );
11052 this.$bar.addClass( 'oo-ui-progressBarWidget-bar');
11053 this.$element
11054 .attr( {
11055 role: 'progressbar',
11056 'aria-valuemin': 0,
11057 'aria-valuemax': 100
11058 } )
11059 .addClass( 'oo-ui-progressBarWidget' )
11060 .append( this.$bar );
11061 };
11062
11063 /* Setup */
11064
11065 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
11066
11067 /* Static Properties */
11068
11069 OO.ui.ProgressBarWidget.static.tagName = 'div';
11070
11071 /* Methods */
11072
11073 /**
11074 * Get progress percent
11075 *
11076 * @return {number} Progress percent
11077 */
11078 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
11079 return this.progress;
11080 };
11081
11082 /**
11083 * Set progress percent
11084 *
11085 * @param {number|boolean} progress Progress percent or false for indeterminate
11086 */
11087 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
11088 this.progress = progress;
11089
11090 if ( progress !== false ) {
11091 this.$bar.css( 'width', this.progress + '%' );
11092 this.$element.attr( 'aria-valuenow', this.progress );
11093 } else {
11094 this.$bar.css( 'width', '' );
11095 this.$element.removeAttr( 'aria-valuenow' );
11096 }
11097 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
11098 };
11099
11100 /**
11101 * Search widget.
11102 *
11103 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
11104 * Results are cleared and populated each time the query is changed.
11105 *
11106 * @class
11107 * @extends OO.ui.Widget
11108 *
11109 * @constructor
11110 * @param {Object} [config] Configuration options
11111 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
11112 * @cfg {string} [value] Initial query value
11113 */
11114 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
11115 // Configuration initialization
11116 config = config || {};
11117
11118 // Parent constructor
11119 OO.ui.SearchWidget.super.call( this, config );
11120
11121 // Properties
11122 this.query = new OO.ui.TextInputWidget( {
11123 $: this.$,
11124 icon: 'search',
11125 placeholder: config.placeholder,
11126 value: config.value
11127 } );
11128 this.results = new OO.ui.SelectWidget( { $: this.$ } );
11129 this.$query = this.$( '<div>' );
11130 this.$results = this.$( '<div>' );
11131
11132 // Events
11133 this.query.connect( this, {
11134 change: 'onQueryChange',
11135 enter: 'onQueryEnter'
11136 } );
11137 this.results.connect( this, {
11138 highlight: 'onResultsHighlight',
11139 select: 'onResultsSelect'
11140 } );
11141 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
11142
11143 // Initialization
11144 this.$query
11145 .addClass( 'oo-ui-searchWidget-query' )
11146 .append( this.query.$element );
11147 this.$results
11148 .addClass( 'oo-ui-searchWidget-results' )
11149 .append( this.results.$element );
11150 this.$element
11151 .addClass( 'oo-ui-searchWidget' )
11152 .append( this.$results, this.$query );
11153 };
11154
11155 /* Setup */
11156
11157 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
11158
11159 /* Events */
11160
11161 /**
11162 * @event highlight
11163 * @param {Object|null} item Item data or null if no item is highlighted
11164 */
11165
11166 /**
11167 * @event select
11168 * @param {Object|null} item Item data or null if no item is selected
11169 */
11170
11171 /* Methods */
11172
11173 /**
11174 * Handle query key down events.
11175 *
11176 * @param {jQuery.Event} e Key down event
11177 */
11178 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
11179 var highlightedItem, nextItem,
11180 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
11181
11182 if ( dir ) {
11183 highlightedItem = this.results.getHighlightedItem();
11184 if ( !highlightedItem ) {
11185 highlightedItem = this.results.getSelectedItem();
11186 }
11187 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
11188 this.results.highlightItem( nextItem );
11189 nextItem.scrollElementIntoView();
11190 }
11191 };
11192
11193 /**
11194 * Handle select widget select events.
11195 *
11196 * Clears existing results. Subclasses should repopulate items according to new query.
11197 *
11198 * @param {string} value New value
11199 */
11200 OO.ui.SearchWidget.prototype.onQueryChange = function () {
11201 // Reset
11202 this.results.clearItems();
11203 };
11204
11205 /**
11206 * Handle select widget enter key events.
11207 *
11208 * Selects highlighted item.
11209 *
11210 * @param {string} value New value
11211 */
11212 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
11213 // Reset
11214 this.results.selectItem( this.results.getHighlightedItem() );
11215 };
11216
11217 /**
11218 * Handle select widget highlight events.
11219 *
11220 * @param {OO.ui.OptionWidget} item Highlighted item
11221 * @fires highlight
11222 */
11223 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
11224 this.emit( 'highlight', item ? item.getData() : null );
11225 };
11226
11227 /**
11228 * Handle select widget select events.
11229 *
11230 * @param {OO.ui.OptionWidget} item Selected item
11231 * @fires select
11232 */
11233 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
11234 this.emit( 'select', item ? item.getData() : null );
11235 };
11236
11237 /**
11238 * Get the query input.
11239 *
11240 * @return {OO.ui.TextInputWidget} Query input
11241 */
11242 OO.ui.SearchWidget.prototype.getQuery = function () {
11243 return this.query;
11244 };
11245
11246 /**
11247 * Get the results list.
11248 *
11249 * @return {OO.ui.SelectWidget} Select list
11250 */
11251 OO.ui.SearchWidget.prototype.getResults = function () {
11252 return this.results;
11253 };
11254
11255 /**
11256 * Generic selection of options.
11257 *
11258 * Items can contain any rendering. Any widget that provides options, from which the user must
11259 * choose one, should be built on this class.
11260 *
11261 * Use together with OO.ui.OptionWidget.
11262 *
11263 * @class
11264 * @extends OO.ui.Widget
11265 * @mixins OO.ui.GroupElement
11266 *
11267 * @constructor
11268 * @param {Object} [config] Configuration options
11269 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
11270 */
11271 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
11272 // Configuration initialization
11273 config = config || {};
11274
11275 // Parent constructor
11276 OO.ui.SelectWidget.super.call( this, config );
11277
11278 // Mixin constructors
11279 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
11280
11281 // Properties
11282 this.pressed = false;
11283 this.selecting = null;
11284 this.onMouseUpHandler = this.onMouseUp.bind( this );
11285 this.onMouseMoveHandler = this.onMouseMove.bind( this );
11286
11287 // Events
11288 this.$element.on( {
11289 mousedown: this.onMouseDown.bind( this ),
11290 mouseover: this.onMouseOver.bind( this ),
11291 mouseleave: this.onMouseLeave.bind( this )
11292 } );
11293
11294 // Initialization
11295 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
11296 if ( $.isArray( config.items ) ) {
11297 this.addItems( config.items );
11298 }
11299 };
11300
11301 /* Setup */
11302
11303 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
11304
11305 // Need to mixin base class as well
11306 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
11307 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
11308
11309 /* Events */
11310
11311 /**
11312 * @event highlight
11313 * @param {OO.ui.OptionWidget|null} item Highlighted item
11314 */
11315
11316 /**
11317 * @event press
11318 * @param {OO.ui.OptionWidget|null} item Pressed item
11319 */
11320
11321 /**
11322 * @event select
11323 * @param {OO.ui.OptionWidget|null} item Selected item
11324 */
11325
11326 /**
11327 * @event choose
11328 * @param {OO.ui.OptionWidget|null} item Chosen item
11329 */
11330
11331 /**
11332 * @event add
11333 * @param {OO.ui.OptionWidget[]} items Added items
11334 * @param {number} index Index items were added at
11335 */
11336
11337 /**
11338 * @event remove
11339 * @param {OO.ui.OptionWidget[]} items Removed items
11340 */
11341
11342 /* Methods */
11343
11344 /**
11345 * Handle mouse down events.
11346 *
11347 * @private
11348 * @param {jQuery.Event} e Mouse down event
11349 */
11350 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
11351 var item;
11352
11353 if ( !this.isDisabled() && e.which === 1 ) {
11354 this.togglePressed( true );
11355 item = this.getTargetItem( e );
11356 if ( item && item.isSelectable() ) {
11357 this.pressItem( item );
11358 this.selecting = item;
11359 this.getElementDocument().addEventListener(
11360 'mouseup',
11361 this.onMouseUpHandler,
11362 true
11363 );
11364 this.getElementDocument().addEventListener(
11365 'mousemove',
11366 this.onMouseMoveHandler,
11367 true
11368 );
11369 }
11370 }
11371 return false;
11372 };
11373
11374 /**
11375 * Handle mouse up events.
11376 *
11377 * @private
11378 * @param {jQuery.Event} e Mouse up event
11379 */
11380 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
11381 var item;
11382
11383 this.togglePressed( false );
11384 if ( !this.selecting ) {
11385 item = this.getTargetItem( e );
11386 if ( item && item.isSelectable() ) {
11387 this.selecting = item;
11388 }
11389 }
11390 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
11391 this.pressItem( null );
11392 this.chooseItem( this.selecting );
11393 this.selecting = null;
11394 }
11395
11396 this.getElementDocument().removeEventListener(
11397 'mouseup',
11398 this.onMouseUpHandler,
11399 true
11400 );
11401 this.getElementDocument().removeEventListener(
11402 'mousemove',
11403 this.onMouseMoveHandler,
11404 true
11405 );
11406
11407 return false;
11408 };
11409
11410 /**
11411 * Handle mouse move events.
11412 *
11413 * @private
11414 * @param {jQuery.Event} e Mouse move event
11415 */
11416 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
11417 var item;
11418
11419 if ( !this.isDisabled() && this.pressed ) {
11420 item = this.getTargetItem( e );
11421 if ( item && item !== this.selecting && item.isSelectable() ) {
11422 this.pressItem( item );
11423 this.selecting = item;
11424 }
11425 }
11426 return false;
11427 };
11428
11429 /**
11430 * Handle mouse over events.
11431 *
11432 * @private
11433 * @param {jQuery.Event} e Mouse over event
11434 */
11435 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
11436 var item;
11437
11438 if ( !this.isDisabled() ) {
11439 item = this.getTargetItem( e );
11440 this.highlightItem( item && item.isHighlightable() ? item : null );
11441 }
11442 return false;
11443 };
11444
11445 /**
11446 * Handle mouse leave events.
11447 *
11448 * @private
11449 * @param {jQuery.Event} e Mouse over event
11450 */
11451 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
11452 if ( !this.isDisabled() ) {
11453 this.highlightItem( null );
11454 }
11455 return false;
11456 };
11457
11458 /**
11459 * Get the closest item to a jQuery.Event.
11460 *
11461 * @private
11462 * @param {jQuery.Event} e
11463 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
11464 */
11465 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
11466 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
11467 if ( $item.length ) {
11468 return $item.data( 'oo-ui-optionWidget' );
11469 }
11470 return null;
11471 };
11472
11473 /**
11474 * Get selected item.
11475 *
11476 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
11477 */
11478 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
11479 var i, len;
11480
11481 for ( i = 0, len = this.items.length; i < len; i++ ) {
11482 if ( this.items[i].isSelected() ) {
11483 return this.items[i];
11484 }
11485 }
11486 return null;
11487 };
11488
11489 /**
11490 * Get highlighted item.
11491 *
11492 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
11493 */
11494 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
11495 var i, len;
11496
11497 for ( i = 0, len = this.items.length; i < len; i++ ) {
11498 if ( this.items[i].isHighlighted() ) {
11499 return this.items[i];
11500 }
11501 }
11502 return null;
11503 };
11504
11505 /**
11506 * Toggle pressed state.
11507 *
11508 * @param {boolean} pressed An option is being pressed
11509 */
11510 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
11511 if ( pressed === undefined ) {
11512 pressed = !this.pressed;
11513 }
11514 if ( pressed !== this.pressed ) {
11515 this.$element
11516 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
11517 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
11518 this.pressed = pressed;
11519 }
11520 };
11521
11522 /**
11523 * Highlight an item.
11524 *
11525 * Highlighting is mutually exclusive.
11526 *
11527 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
11528 * @fires highlight
11529 * @chainable
11530 */
11531 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
11532 var i, len, highlighted,
11533 changed = false;
11534
11535 for ( i = 0, len = this.items.length; i < len; i++ ) {
11536 highlighted = this.items[i] === item;
11537 if ( this.items[i].isHighlighted() !== highlighted ) {
11538 this.items[i].setHighlighted( highlighted );
11539 changed = true;
11540 }
11541 }
11542 if ( changed ) {
11543 this.emit( 'highlight', item );
11544 }
11545
11546 return this;
11547 };
11548
11549 /**
11550 * Select an item.
11551 *
11552 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
11553 * @fires select
11554 * @chainable
11555 */
11556 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
11557 var i, len, selected,
11558 changed = false;
11559
11560 for ( i = 0, len = this.items.length; i < len; i++ ) {
11561 selected = this.items[i] === item;
11562 if ( this.items[i].isSelected() !== selected ) {
11563 this.items[i].setSelected( selected );
11564 changed = true;
11565 }
11566 }
11567 if ( changed ) {
11568 this.emit( 'select', item );
11569 }
11570
11571 return this;
11572 };
11573
11574 /**
11575 * Press an item.
11576 *
11577 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
11578 * @fires press
11579 * @chainable
11580 */
11581 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
11582 var i, len, pressed,
11583 changed = false;
11584
11585 for ( i = 0, len = this.items.length; i < len; i++ ) {
11586 pressed = this.items[i] === item;
11587 if ( this.items[i].isPressed() !== pressed ) {
11588 this.items[i].setPressed( pressed );
11589 changed = true;
11590 }
11591 }
11592 if ( changed ) {
11593 this.emit( 'press', item );
11594 }
11595
11596 return this;
11597 };
11598
11599 /**
11600 * Choose an item.
11601 *
11602 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
11603 * an item is selected using the keyboard or mouse.
11604 *
11605 * @param {OO.ui.OptionWidget} item Item to choose
11606 * @fires choose
11607 * @chainable
11608 */
11609 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
11610 this.selectItem( item );
11611 this.emit( 'choose', item );
11612
11613 return this;
11614 };
11615
11616 /**
11617 * Get an item relative to another one.
11618 *
11619 * @param {OO.ui.OptionWidget} item Item to start at
11620 * @param {number} direction Direction to move in, -1 to look backward, 1 to move forward
11621 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
11622 */
11623 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
11624 var inc = direction > 0 ? 1 : -1,
11625 len = this.items.length,
11626 index = item instanceof OO.ui.OptionWidget ?
11627 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
11628 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
11629 i = inc > 0 ?
11630 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
11631 Math.max( index, -1 ) :
11632 // Default to n-1 instead of -1, if nothing is selected let's start at the end
11633 Math.min( index, len );
11634
11635 while ( len !== 0 ) {
11636 i = ( i + inc + len ) % len;
11637 item = this.items[i];
11638 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
11639 return item;
11640 }
11641 // Stop iterating when we've looped all the way around
11642 if ( i === stopAt ) {
11643 break;
11644 }
11645 }
11646 return null;
11647 };
11648
11649 /**
11650 * Get the next selectable item.
11651 *
11652 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
11653 */
11654 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
11655 var i, len, item;
11656
11657 for ( i = 0, len = this.items.length; i < len; i++ ) {
11658 item = this.items[i];
11659 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
11660 return item;
11661 }
11662 }
11663
11664 return null;
11665 };
11666
11667 /**
11668 * Add items.
11669 *
11670 * @param {OO.ui.OptionWidget[]} items Items to add
11671 * @param {number} [index] Index to insert items after
11672 * @fires add
11673 * @chainable
11674 */
11675 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
11676 // Mixin method
11677 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
11678
11679 // Always provide an index, even if it was omitted
11680 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
11681
11682 return this;
11683 };
11684
11685 /**
11686 * Remove items.
11687 *
11688 * Items will be detached, not removed, so they can be used later.
11689 *
11690 * @param {OO.ui.OptionWidget[]} items Items to remove
11691 * @fires remove
11692 * @chainable
11693 */
11694 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
11695 var i, len, item;
11696
11697 // Deselect items being removed
11698 for ( i = 0, len = items.length; i < len; i++ ) {
11699 item = items[i];
11700 if ( item.isSelected() ) {
11701 this.selectItem( null );
11702 }
11703 }
11704
11705 // Mixin method
11706 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
11707
11708 this.emit( 'remove', items );
11709
11710 return this;
11711 };
11712
11713 /**
11714 * Clear all items.
11715 *
11716 * Items will be detached, not removed, so they can be used later.
11717 *
11718 * @fires remove
11719 * @chainable
11720 */
11721 OO.ui.SelectWidget.prototype.clearItems = function () {
11722 var items = this.items.slice();
11723
11724 // Mixin method
11725 OO.ui.GroupWidget.prototype.clearItems.call( this );
11726
11727 // Clear selection
11728 this.selectItem( null );
11729
11730 this.emit( 'remove', items );
11731
11732 return this;
11733 };
11734
11735 /**
11736 * Select widget containing button options.
11737 *
11738 * Use together with OO.ui.ButtonOptionWidget.
11739 *
11740 * @class
11741 * @extends OO.ui.SelectWidget
11742 *
11743 * @constructor
11744 * @param {Object} [config] Configuration options
11745 */
11746 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
11747 // Parent constructor
11748 OO.ui.ButtonSelectWidget.super.call( this, config );
11749
11750 // Initialization
11751 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
11752 };
11753
11754 /* Setup */
11755
11756 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
11757
11758 /**
11759 * Select widget containing radio button options.
11760 *
11761 * Use together with OO.ui.RadioOptionWidget.
11762 *
11763 * @class
11764 * @extends OO.ui.SelectWidget
11765 *
11766 * @constructor
11767 * @param {Object} [config] Configuration options
11768 */
11769 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
11770 // Parent constructor
11771 OO.ui.RadioSelectWidget.super.call( this, config );
11772
11773 // Initialization
11774 this.$element.addClass( 'oo-ui-radioSelectWidget' );
11775 };
11776
11777 /* Setup */
11778
11779 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
11780
11781 /**
11782 * Overlaid menu of options.
11783 *
11784 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
11785 * the menu.
11786 *
11787 * Use together with OO.ui.MenuOptionWidget.
11788 *
11789 * @class
11790 * @extends OO.ui.SelectWidget
11791 * @mixins OO.ui.ClippableElement
11792 *
11793 * @constructor
11794 * @param {Object} [config] Configuration options
11795 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
11796 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
11797 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
11798 */
11799 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
11800 // Configuration initialization
11801 config = config || {};
11802
11803 // Parent constructor
11804 OO.ui.MenuSelectWidget.super.call( this, config );
11805
11806 // Mixin constructors
11807 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
11808
11809 // Properties
11810 this.flashing = false;
11811 this.visible = false;
11812 this.newItems = null;
11813 this.autoHide = config.autoHide === undefined || !!config.autoHide;
11814 this.$input = config.input ? config.input.$input : null;
11815 this.$widget = config.widget ? config.widget.$element : null;
11816 this.$previousFocus = null;
11817 this.isolated = !config.input;
11818 this.onKeyDownHandler = this.onKeyDown.bind( this );
11819 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
11820
11821 // Initialization
11822 this.$element
11823 .hide()
11824 .attr( 'role', 'menu' )
11825 .addClass( 'oo-ui-menuSelectWidget' );
11826 };
11827
11828 /* Setup */
11829
11830 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
11831 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
11832
11833 /* Methods */
11834
11835 /**
11836 * Handles document mouse down events.
11837 *
11838 * @param {jQuery.Event} e Key down event
11839 */
11840 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
11841 if (
11842 !OO.ui.contains( this.$element[0], e.target, true ) &&
11843 ( !this.$widget || !OO.ui.contains( this.$widget[0], e.target, true ) )
11844 ) {
11845 this.toggle( false );
11846 }
11847 };
11848
11849 /**
11850 * Handles key down events.
11851 *
11852 * @param {jQuery.Event} e Key down event
11853 */
11854 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
11855 var nextItem,
11856 handled = false,
11857 highlightItem = this.getHighlightedItem();
11858
11859 if ( !this.isDisabled() && this.isVisible() ) {
11860 if ( !highlightItem ) {
11861 highlightItem = this.getSelectedItem();
11862 }
11863 switch ( e.keyCode ) {
11864 case OO.ui.Keys.ENTER:
11865 this.chooseItem( highlightItem );
11866 handled = true;
11867 break;
11868 case OO.ui.Keys.UP:
11869 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
11870 handled = true;
11871 break;
11872 case OO.ui.Keys.DOWN:
11873 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
11874 handled = true;
11875 break;
11876 case OO.ui.Keys.ESCAPE:
11877 if ( highlightItem ) {
11878 highlightItem.setHighlighted( false );
11879 }
11880 this.toggle( false );
11881 handled = true;
11882 break;
11883 }
11884
11885 if ( nextItem ) {
11886 this.highlightItem( nextItem );
11887 nextItem.scrollElementIntoView();
11888 }
11889
11890 if ( handled ) {
11891 e.preventDefault();
11892 e.stopPropagation();
11893 return false;
11894 }
11895 }
11896 };
11897
11898 /**
11899 * Bind key down listener.
11900 */
11901 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
11902 if ( this.$input ) {
11903 this.$input.on( 'keydown', this.onKeyDownHandler );
11904 } else {
11905 // Capture menu navigation keys
11906 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
11907 }
11908 };
11909
11910 /**
11911 * Unbind key down listener.
11912 */
11913 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
11914 if ( this.$input ) {
11915 this.$input.off( 'keydown' );
11916 } else {
11917 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
11918 }
11919 };
11920
11921 /**
11922 * Choose an item.
11923 *
11924 * This will close the menu when done, unlike selectItem which only changes selection.
11925 *
11926 * @param {OO.ui.OptionWidget} item Item to choose
11927 * @chainable
11928 */
11929 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
11930 var widget = this;
11931
11932 // Parent method
11933 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
11934
11935 if ( item && !this.flashing ) {
11936 this.flashing = true;
11937 item.flash().done( function () {
11938 widget.toggle( false );
11939 widget.flashing = false;
11940 } );
11941 } else {
11942 this.toggle( false );
11943 }
11944
11945 return this;
11946 };
11947
11948 /**
11949 * @inheritdoc
11950 */
11951 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
11952 var i, len, item;
11953
11954 // Parent method
11955 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
11956
11957 // Auto-initialize
11958 if ( !this.newItems ) {
11959 this.newItems = [];
11960 }
11961
11962 for ( i = 0, len = items.length; i < len; i++ ) {
11963 item = items[i];
11964 if ( this.isVisible() ) {
11965 // Defer fitting label until item has been attached
11966 item.fitLabel();
11967 } else {
11968 this.newItems.push( item );
11969 }
11970 }
11971
11972 // Reevaluate clipping
11973 this.clip();
11974
11975 return this;
11976 };
11977
11978 /**
11979 * @inheritdoc
11980 */
11981 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
11982 // Parent method
11983 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
11984
11985 // Reevaluate clipping
11986 this.clip();
11987
11988 return this;
11989 };
11990
11991 /**
11992 * @inheritdoc
11993 */
11994 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
11995 // Parent method
11996 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
11997
11998 // Reevaluate clipping
11999 this.clip();
12000
12001 return this;
12002 };
12003
12004 /**
12005 * @inheritdoc
12006 */
12007 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
12008 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
12009
12010 var i, len,
12011 change = visible !== this.isVisible(),
12012 elementDoc = this.getElementDocument(),
12013 widgetDoc = this.$widget ? this.$widget[0].ownerDocument : null;
12014
12015 // Parent method
12016 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
12017
12018 if ( change ) {
12019 if ( visible ) {
12020 this.bindKeyDownListener();
12021
12022 // Change focus to enable keyboard navigation
12023 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
12024 this.$previousFocus = this.$( ':focus' );
12025 this.$input[0].focus();
12026 }
12027 if ( this.newItems && this.newItems.length ) {
12028 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
12029 this.newItems[i].fitLabel();
12030 }
12031 this.newItems = null;
12032 }
12033 this.toggleClipping( true );
12034
12035 // Auto-hide
12036 if ( this.autoHide ) {
12037 elementDoc.addEventListener(
12038 'mousedown', this.onDocumentMouseDownHandler, true
12039 );
12040 // Support $widget being in a different document
12041 if ( widgetDoc && widgetDoc !== elementDoc ) {
12042 widgetDoc.addEventListener(
12043 'mousedown', this.onDocumentMouseDownHandler, true
12044 );
12045 }
12046 }
12047 } else {
12048 this.unbindKeyDownListener();
12049 if ( this.isolated && this.$previousFocus ) {
12050 this.$previousFocus[0].focus();
12051 this.$previousFocus = null;
12052 }
12053 elementDoc.removeEventListener(
12054 'mousedown', this.onDocumentMouseDownHandler, true
12055 );
12056 // Support $widget being in a different document
12057 if ( widgetDoc && widgetDoc !== elementDoc ) {
12058 widgetDoc.removeEventListener(
12059 'mousedown', this.onDocumentMouseDownHandler, true
12060 );
12061 }
12062 this.toggleClipping( false );
12063 }
12064 }
12065
12066 return this;
12067 };
12068
12069 /**
12070 * Menu for a text input widget.
12071 *
12072 * This menu is specially designed to be positioned beneath the text input widget. Even if the input
12073 * is in a different frame, the menu's position is automatically calculated and maintained when the
12074 * menu is toggled or the window is resized.
12075 *
12076 * @class
12077 * @extends OO.ui.MenuSelectWidget
12078 *
12079 * @constructor
12080 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
12081 * @param {Object} [config] Configuration options
12082 * @cfg {jQuery} [$container=input.$element] Element to render menu under
12083 */
12084 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( input, config ) {
12085 // Configuration initialization
12086 config = config || {};
12087
12088 // Parent constructor
12089 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
12090
12091 // Properties
12092 this.input = input;
12093 this.$container = config.$container || this.input.$element;
12094 this.onWindowResizeHandler = this.onWindowResize.bind( this );
12095
12096 // Initialization
12097 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
12098 };
12099
12100 /* Setup */
12101
12102 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
12103
12104 /* Methods */
12105
12106 /**
12107 * Handle window resize event.
12108 *
12109 * @param {jQuery.Event} e Window resize event
12110 */
12111 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
12112 this.position();
12113 };
12114
12115 /**
12116 * @inheritdoc
12117 */
12118 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
12119 visible = visible === undefined ? !this.isVisible() : !!visible;
12120
12121 var change = visible !== this.isVisible();
12122
12123 if ( change && visible ) {
12124 // Make sure the width is set before the parent method runs.
12125 // After this we have to call this.position(); again to actually
12126 // position ourselves correctly.
12127 this.position();
12128 }
12129
12130 // Parent method
12131 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
12132
12133 if ( change ) {
12134 if ( this.isVisible() ) {
12135 this.position();
12136 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
12137 } else {
12138 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
12139 }
12140 }
12141
12142 return this;
12143 };
12144
12145 /**
12146 * Position the menu.
12147 *
12148 * @chainable
12149 */
12150 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
12151 var $container = this.$container,
12152 pos = OO.ui.Element.getRelativePosition( $container, this.$element.offsetParent() );
12153
12154 // Position under input
12155 pos.top += $container.height();
12156 this.$element.css( pos );
12157
12158 // Set width
12159 this.setIdealSize( $container.width() );
12160 // We updated the position, so re-evaluate the clipping state
12161 this.clip();
12162
12163 return this;
12164 };
12165
12166 /**
12167 * Structured list of items.
12168 *
12169 * Use with OO.ui.OutlineOptionWidget.
12170 *
12171 * @class
12172 * @extends OO.ui.SelectWidget
12173 *
12174 * @constructor
12175 * @param {Object} [config] Configuration options
12176 */
12177 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
12178 // Configuration initialization
12179 config = config || {};
12180
12181 // Parent constructor
12182 OO.ui.OutlineSelectWidget.super.call( this, config );
12183
12184 // Initialization
12185 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
12186 };
12187
12188 /* Setup */
12189
12190 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
12191
12192 /**
12193 * Switch that slides on and off.
12194 *
12195 * @class
12196 * @extends OO.ui.Widget
12197 * @mixins OO.ui.ToggleWidget
12198 *
12199 * @constructor
12200 * @param {Object} [config] Configuration options
12201 * @cfg {boolean} [value=false] Initial value
12202 */
12203 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
12204 // Parent constructor
12205 OO.ui.ToggleSwitchWidget.super.call( this, config );
12206
12207 // Mixin constructors
12208 OO.ui.ToggleWidget.call( this, config );
12209
12210 // Properties
12211 this.dragging = false;
12212 this.dragStart = null;
12213 this.sliding = false;
12214 this.$glow = this.$( '<span>' );
12215 this.$grip = this.$( '<span>' );
12216
12217 // Events
12218 this.$element.on( 'click', this.onClick.bind( this ) );
12219
12220 // Initialization
12221 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
12222 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
12223 this.$element
12224 .addClass( 'oo-ui-toggleSwitchWidget' )
12225 .append( this.$glow, this.$grip );
12226 };
12227
12228 /* Setup */
12229
12230 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
12231 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
12232
12233 /* Methods */
12234
12235 /**
12236 * Handle mouse down events.
12237 *
12238 * @param {jQuery.Event} e Mouse down event
12239 */
12240 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
12241 if ( !this.isDisabled() && e.which === 1 ) {
12242 this.setValue( !this.value );
12243 }
12244 };
12245
12246 }( OO ) );