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