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