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