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