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