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