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