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