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