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