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