Update OOjs UI to v0.1.0-pre (1c5e409ab1)
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.1.0-pre (1c5e409ab1)
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-09T01:20:39Z
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|Window} 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 framed: false,
6433 icon: 'info',
6434 title: config.help
6435 } );
6436
6437 this.popupButtonWidget.getPopup().$body.append( this.$( '<span>' ).text( config.help ) );
6438 this.$help = this.popupButtonWidget.$element;
6439 } else {
6440 this.$help = this.$( '<div>' );
6441 }
6442
6443 // Events
6444 if ( this.field instanceof OO.ui.InputWidget ) {
6445 this.$label.on( 'click', OO.ui.bind( this.onLabelClick, this ) );
6446 }
6447 this.field.connect( this, { disable: 'onFieldDisable' } );
6448
6449 // Initialization
6450 this.$element.addClass( 'oo-ui-fieldLayout' );
6451 this.$field
6452 .addClass( 'oo-ui-fieldLayout-field' )
6453 .toggleClass( 'oo-ui-fieldLayout-disable', this.field.isDisabled() )
6454 .append( this.field.$element );
6455 this.setAlignment( config.align );
6456 };
6457
6458 /* Setup */
6459
6460 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
6461 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
6462
6463 /* Methods */
6464
6465 /**
6466 * Handle field disable events.
6467 *
6468 * @param {boolean} value Field is disabled
6469 */
6470 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
6471 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
6472 };
6473
6474 /**
6475 * Handle label mouse click events.
6476 *
6477 * @param {jQuery.Event} e Mouse click event
6478 */
6479 OO.ui.FieldLayout.prototype.onLabelClick = function () {
6480 this.field.simulateLabelClick();
6481 return false;
6482 };
6483
6484 /**
6485 * Get the field.
6486 *
6487 * @return {OO.ui.Widget} Field widget
6488 */
6489 OO.ui.FieldLayout.prototype.getField = function () {
6490 return this.field;
6491 };
6492
6493 /**
6494 * Set the field alignment mode.
6495 *
6496 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
6497 * @chainable
6498 */
6499 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
6500 if ( value !== this.align ) {
6501 // Default to 'left'
6502 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
6503 value = 'left';
6504 }
6505 // Reorder elements
6506 if ( value === 'inline' ) {
6507 this.$element.append( this.$field, this.$label, this.$help );
6508 } else {
6509 this.$element.append( this.$help, this.$label, this.$field );
6510 }
6511 // Set classes
6512 if ( this.align ) {
6513 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
6514 }
6515 this.align = value;
6516 // The following classes can be used here:
6517 // oo-ui-fieldLayout-align-left
6518 // oo-ui-fieldLayout-align-right
6519 // oo-ui-fieldLayout-align-top
6520 // oo-ui-fieldLayout-align-inline
6521 this.$element.addClass( 'oo-ui-fieldLayout-align-' + this.align );
6522 }
6523
6524 return this;
6525 };
6526
6527 /**
6528 * Layout made of a fieldset and optional legend.
6529 *
6530 * Just add OO.ui.FieldLayout items.
6531 *
6532 * @class
6533 * @extends OO.ui.Layout
6534 * @mixins OO.ui.LabelElement
6535 * @mixins OO.ui.IconElement
6536 * @mixins OO.ui.GroupElement
6537 *
6538 * @constructor
6539 * @param {Object} [config] Configuration options
6540 * @cfg {string} [icon] Symbolic icon name
6541 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
6542 */
6543 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
6544 // Config initialization
6545 config = config || {};
6546
6547 // Parent constructor
6548 OO.ui.FieldsetLayout.super.call( this, config );
6549
6550 // Mixin constructors
6551 OO.ui.IconElement.call( this, config );
6552 OO.ui.LabelElement.call( this, config );
6553 OO.ui.GroupElement.call( this, config );
6554
6555 // Initialization
6556 this.$element
6557 .addClass( 'oo-ui-fieldsetLayout' )
6558 .prepend( this.$icon, this.$label, this.$group );
6559 if ( $.isArray( config.items ) ) {
6560 this.addItems( config.items );
6561 }
6562 };
6563
6564 /* Setup */
6565
6566 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
6567 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
6568 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
6569 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
6570
6571 /* Static Properties */
6572
6573 OO.ui.FieldsetLayout.static.tagName = 'div';
6574
6575 /**
6576 * Layout with an HTML form.
6577 *
6578 * @class
6579 * @extends OO.ui.Layout
6580 *
6581 * @constructor
6582 * @param {Object} [config] Configuration options
6583 */
6584 OO.ui.FormLayout = function OoUiFormLayout( config ) {
6585 // Configuration initialization
6586 config = config || {};
6587
6588 // Parent constructor
6589 OO.ui.FormLayout.super.call( this, config );
6590
6591 // Events
6592 this.$element.on( 'submit', OO.ui.bind( this.onFormSubmit, this ) );
6593
6594 // Initialization
6595 this.$element.addClass( 'oo-ui-formLayout' );
6596 };
6597
6598 /* Setup */
6599
6600 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
6601
6602 /* Events */
6603
6604 /**
6605 * @event submit
6606 */
6607
6608 /* Static Properties */
6609
6610 OO.ui.FormLayout.static.tagName = 'form';
6611
6612 /* Methods */
6613
6614 /**
6615 * Handle form submit events.
6616 *
6617 * @param {jQuery.Event} e Submit event
6618 * @fires submit
6619 */
6620 OO.ui.FormLayout.prototype.onFormSubmit = function () {
6621 this.emit( 'submit' );
6622 return false;
6623 };
6624
6625 /**
6626 * Layout made of proportionally sized columns and rows.
6627 *
6628 * @class
6629 * @extends OO.ui.Layout
6630 *
6631 * @constructor
6632 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
6633 * @param {Object} [config] Configuration options
6634 * @cfg {number[]} [widths] Widths of columns as ratios
6635 * @cfg {number[]} [heights] Heights of columns as ratios
6636 */
6637 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
6638 var i, len, widths;
6639
6640 // Config initialization
6641 config = config || {};
6642
6643 // Parent constructor
6644 OO.ui.GridLayout.super.call( this, config );
6645
6646 // Properties
6647 this.panels = [];
6648 this.widths = [];
6649 this.heights = [];
6650
6651 // Initialization
6652 this.$element.addClass( 'oo-ui-gridLayout' );
6653 for ( i = 0, len = panels.length; i < len; i++ ) {
6654 this.panels.push( panels[i] );
6655 this.$element.append( panels[i].$element );
6656 }
6657 if ( config.widths || config.heights ) {
6658 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
6659 } else {
6660 // Arrange in columns by default
6661 widths = [];
6662 for ( i = 0, len = this.panels.length; i < len; i++ ) {
6663 widths[i] = 1;
6664 }
6665 this.layout( widths, [ 1 ] );
6666 }
6667 };
6668
6669 /* Setup */
6670
6671 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
6672
6673 /* Events */
6674
6675 /**
6676 * @event layout
6677 */
6678
6679 /**
6680 * @event update
6681 */
6682
6683 /* Static Properties */
6684
6685 OO.ui.GridLayout.static.tagName = 'div';
6686
6687 /* Methods */
6688
6689 /**
6690 * Set grid dimensions.
6691 *
6692 * @param {number[]} widths Widths of columns as ratios
6693 * @param {number[]} heights Heights of rows as ratios
6694 * @fires layout
6695 * @throws {Error} If grid is not large enough to fit all panels
6696 */
6697 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
6698 var x, y,
6699 xd = 0,
6700 yd = 0,
6701 cols = widths.length,
6702 rows = heights.length;
6703
6704 // Verify grid is big enough to fit panels
6705 if ( cols * rows < this.panels.length ) {
6706 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
6707 }
6708
6709 // Sum up denominators
6710 for ( x = 0; x < cols; x++ ) {
6711 xd += widths[x];
6712 }
6713 for ( y = 0; y < rows; y++ ) {
6714 yd += heights[y];
6715 }
6716 // Store factors
6717 this.widths = [];
6718 this.heights = [];
6719 for ( x = 0; x < cols; x++ ) {
6720 this.widths[x] = widths[x] / xd;
6721 }
6722 for ( y = 0; y < rows; y++ ) {
6723 this.heights[y] = heights[y] / yd;
6724 }
6725 // Synchronize view
6726 this.update();
6727 this.emit( 'layout' );
6728 };
6729
6730 /**
6731 * Update panel positions and sizes.
6732 *
6733 * @fires update
6734 */
6735 OO.ui.GridLayout.prototype.update = function () {
6736 var x, y, panel,
6737 i = 0,
6738 left = 0,
6739 top = 0,
6740 dimensions,
6741 width = 0,
6742 height = 0,
6743 cols = this.widths.length,
6744 rows = this.heights.length;
6745
6746 for ( y = 0; y < rows; y++ ) {
6747 height = this.heights[y];
6748 for ( x = 0; x < cols; x++ ) {
6749 panel = this.panels[i];
6750 width = this.widths[x];
6751 dimensions = {
6752 width: Math.round( width * 100 ) + '%',
6753 height: Math.round( height * 100 ) + '%',
6754 top: Math.round( top * 100 ) + '%',
6755 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
6756 visibility: width === 0 || height === 0 ? 'hidden' : ''
6757 };
6758 // If RTL, reverse:
6759 if ( OO.ui.Element.getDir( this.$.context ) === 'rtl' ) {
6760 dimensions.right = Math.round( left * 100 ) + '%';
6761 } else {
6762 dimensions.left = Math.round( left * 100 ) + '%';
6763 }
6764 panel.$element.css( dimensions );
6765 i++;
6766 left += width;
6767 }
6768 top += height;
6769 left = 0;
6770 }
6771
6772 this.emit( 'update' );
6773 };
6774
6775 /**
6776 * Get a panel at a given position.
6777 *
6778 * The x and y position is affected by the current grid layout.
6779 *
6780 * @param {number} x Horizontal position
6781 * @param {number} y Vertical position
6782 * @return {OO.ui.PanelLayout} The panel at the given postion
6783 */
6784 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
6785 return this.panels[( x * this.widths.length ) + y];
6786 };
6787
6788 /**
6789 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
6790 *
6791 * @class
6792 * @extends OO.ui.Layout
6793 *
6794 * @constructor
6795 * @param {Object} [config] Configuration options
6796 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
6797 * @cfg {boolean} [padded=false] Pad the content from the edges
6798 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
6799 */
6800 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
6801 // Config initialization
6802 config = config || {};
6803
6804 // Parent constructor
6805 OO.ui.PanelLayout.super.call( this, config );
6806
6807 // Initialization
6808 this.$element.addClass( 'oo-ui-panelLayout' );
6809 if ( config.scrollable ) {
6810 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
6811 }
6812
6813 if ( config.padded ) {
6814 this.$element.addClass( 'oo-ui-panelLayout-padded' );
6815 }
6816
6817 if ( config.expanded === undefined || config.expanded ) {
6818 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
6819 }
6820 };
6821
6822 /* Setup */
6823
6824 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
6825
6826 /**
6827 * Page within an booklet layout.
6828 *
6829 * @class
6830 * @extends OO.ui.PanelLayout
6831 *
6832 * @constructor
6833 * @param {string} name Unique symbolic name of page
6834 * @param {Object} [config] Configuration options
6835 * @param {string} [outlineItem] Outline item widget
6836 */
6837 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
6838 // Configuration initialization
6839 config = $.extend( { scrollable: true }, config );
6840
6841 // Parent constructor
6842 OO.ui.PageLayout.super.call( this, config );
6843
6844 // Properties
6845 this.name = name;
6846 this.outlineItem = config.outlineItem || null;
6847 this.active = false;
6848
6849 // Initialization
6850 this.$element.addClass( 'oo-ui-pageLayout' );
6851 };
6852
6853 /* Setup */
6854
6855 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
6856
6857 /* Events */
6858
6859 /**
6860 * @event active
6861 * @param {boolean} active Page is active
6862 */
6863
6864 /* Methods */
6865
6866 /**
6867 * Get page name.
6868 *
6869 * @return {string} Symbolic name of page
6870 */
6871 OO.ui.PageLayout.prototype.getName = function () {
6872 return this.name;
6873 };
6874
6875 /**
6876 * Check if page is active.
6877 *
6878 * @return {boolean} Page is active
6879 */
6880 OO.ui.PageLayout.prototype.isActive = function () {
6881 return this.active;
6882 };
6883
6884 /**
6885 * Get outline item.
6886 *
6887 * @return {OO.ui.OutlineItemWidget|null} Outline item widget
6888 */
6889 OO.ui.PageLayout.prototype.getOutlineItem = function () {
6890 return this.outlineItem;
6891 };
6892
6893 /**
6894 * Set outline item.
6895 *
6896 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
6897 * outline item as desired; this method is called for setting (with an object) and unsetting
6898 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
6899 * operating on null instead of an OO.ui.OutlineItemWidget object.
6900 *
6901 * @param {OO.ui.OutlineItemWidget|null} outlineItem Outline item widget, null to clear
6902 * @chainable
6903 */
6904 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
6905 this.outlineItem = outlineItem || null;
6906 if ( outlineItem ) {
6907 this.setupOutlineItem();
6908 }
6909 return this;
6910 };
6911
6912 /**
6913 * Setup outline item.
6914 *
6915 * @localdoc Subclasses should override this method to adjust the outline item as desired.
6916 *
6917 * @param {OO.ui.OutlineItemWidget} outlineItem Outline item widget to setup
6918 * @chainable
6919 */
6920 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
6921 return this;
6922 };
6923
6924 /**
6925 * Set page active state.
6926 *
6927 * @param {boolean} Page is active
6928 * @fires active
6929 */
6930 OO.ui.PageLayout.prototype.setActive = function ( active ) {
6931 active = !!active;
6932
6933 if ( active !== this.active ) {
6934 this.active = active;
6935 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
6936 this.emit( 'active', this.active );
6937 }
6938 };
6939
6940 /**
6941 * Layout containing a series of mutually exclusive pages.
6942 *
6943 * @class
6944 * @extends OO.ui.PanelLayout
6945 * @mixins OO.ui.GroupElement
6946 *
6947 * @constructor
6948 * @param {Object} [config] Configuration options
6949 * @cfg {boolean} [continuous=false] Show all pages, one after another
6950 * @cfg {string} [icon=''] Symbolic icon name
6951 * @cfg {OO.ui.Layout[]} [items] Layouts to add
6952 */
6953 OO.ui.StackLayout = function OoUiStackLayout( config ) {
6954 // Config initialization
6955 config = $.extend( { scrollable: true }, config );
6956
6957 // Parent constructor
6958 OO.ui.StackLayout.super.call( this, config );
6959
6960 // Mixin constructors
6961 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
6962
6963 // Properties
6964 this.currentItem = null;
6965 this.continuous = !!config.continuous;
6966
6967 // Initialization
6968 this.$element.addClass( 'oo-ui-stackLayout' );
6969 if ( this.continuous ) {
6970 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
6971 }
6972 if ( $.isArray( config.items ) ) {
6973 this.addItems( config.items );
6974 }
6975 };
6976
6977 /* Setup */
6978
6979 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
6980 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
6981
6982 /* Events */
6983
6984 /**
6985 * @event set
6986 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
6987 */
6988
6989 /* Methods */
6990
6991 /**
6992 * Get the current item.
6993 *
6994 * @return {OO.ui.Layout|null}
6995 */
6996 OO.ui.StackLayout.prototype.getCurrentItem = function () {
6997 return this.currentItem;
6998 };
6999
7000 /**
7001 * Unset the current item.
7002 *
7003 * @private
7004 * @param {OO.ui.StackLayout} layout
7005 * @fires set
7006 */
7007 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
7008 var prevItem = this.currentItem;
7009 if ( prevItem === null ) {
7010 return;
7011 }
7012
7013 this.currentItem = null;
7014 this.emit( 'set', null );
7015 };
7016
7017 /**
7018 * Add items.
7019 *
7020 * Adding an existing item (by value) will move it.
7021 *
7022 * @param {OO.ui.Layout[]} items Items to add
7023 * @param {number} [index] Index to insert items after
7024 * @chainable
7025 */
7026 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
7027 // Mixin method
7028 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
7029
7030 if ( !this.currentItem && items.length ) {
7031 this.setItem( items[0] );
7032 }
7033
7034 return this;
7035 };
7036
7037 /**
7038 * Remove items.
7039 *
7040 * Items will be detached, not removed, so they can be used later.
7041 *
7042 * @param {OO.ui.Layout[]} items Items to remove
7043 * @chainable
7044 * @fires set
7045 */
7046 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
7047 // Mixin method
7048 OO.ui.GroupElement.prototype.removeItems.call( this, items );
7049
7050 if ( $.inArray( this.currentItem, items ) !== -1 ) {
7051 if ( this.items.length ) {
7052 this.setItem( this.items[0] );
7053 } else {
7054 this.unsetCurrentItem();
7055 }
7056 }
7057
7058 return this;
7059 };
7060
7061 /**
7062 * Clear all items.
7063 *
7064 * Items will be detached, not removed, so they can be used later.
7065 *
7066 * @chainable
7067 * @fires set
7068 */
7069 OO.ui.StackLayout.prototype.clearItems = function () {
7070 this.unsetCurrentItem();
7071 OO.ui.GroupElement.prototype.clearItems.call( this );
7072
7073 return this;
7074 };
7075
7076 /**
7077 * Show item.
7078 *
7079 * Any currently shown item will be hidden.
7080 *
7081 * FIXME: If the passed item to show has not been added in the items list, then
7082 * this method drops it and unsets the current item.
7083 *
7084 * @param {OO.ui.Layout} item Item to show
7085 * @chainable
7086 * @fires set
7087 */
7088 OO.ui.StackLayout.prototype.setItem = function ( item ) {
7089 var i, len;
7090
7091 if ( item !== this.currentItem ) {
7092 if ( !this.continuous ) {
7093 for ( i = 0, len = this.items.length; i < len; i++ ) {
7094 this.items[i].$element.css( 'display', '' );
7095 }
7096 }
7097 if ( $.inArray( item, this.items ) !== -1 ) {
7098 if ( !this.continuous ) {
7099 item.$element.css( 'display', 'block' );
7100 }
7101 this.currentItem = item;
7102 this.emit( 'set', item );
7103 } else {
7104 this.unsetCurrentItem();
7105 }
7106 }
7107
7108 return this;
7109 };
7110
7111 /**
7112 * Horizontal bar layout of tools as icon buttons.
7113 *
7114 * @class
7115 * @extends OO.ui.ToolGroup
7116 *
7117 * @constructor
7118 * @param {OO.ui.Toolbar} toolbar
7119 * @param {Object} [config] Configuration options
7120 */
7121 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
7122 // Parent constructor
7123 OO.ui.BarToolGroup.super.call( this, toolbar, config );
7124
7125 // Initialization
7126 this.$element.addClass( 'oo-ui-barToolGroup' );
7127 };
7128
7129 /* Setup */
7130
7131 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
7132
7133 /* Static Properties */
7134
7135 OO.ui.BarToolGroup.static.titleTooltips = true;
7136
7137 OO.ui.BarToolGroup.static.accelTooltips = true;
7138
7139 OO.ui.BarToolGroup.static.name = 'bar';
7140
7141 /**
7142 * Popup list of tools with an icon and optional label.
7143 *
7144 * @abstract
7145 * @class
7146 * @extends OO.ui.ToolGroup
7147 * @mixins OO.ui.IconElement
7148 * @mixins OO.ui.IndicatorElement
7149 * @mixins OO.ui.LabelElement
7150 * @mixins OO.ui.TitledElement
7151 * @mixins OO.ui.ClippableElement
7152 *
7153 * @constructor
7154 * @param {OO.ui.Toolbar} toolbar
7155 * @param {Object} [config] Configuration options
7156 * @cfg {string} [header] Text to display at the top of the pop-up
7157 */
7158 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
7159 // Configuration initialization
7160 config = config || {};
7161
7162 // Parent constructor
7163 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
7164
7165 // Mixin constructors
7166 OO.ui.IconElement.call( this, config );
7167 OO.ui.IndicatorElement.call( this, config );
7168 OO.ui.LabelElement.call( this, config );
7169 OO.ui.TitledElement.call( this, config );
7170 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
7171
7172 // Properties
7173 this.active = false;
7174 this.dragging = false;
7175 this.onBlurHandler = OO.ui.bind( this.onBlur, this );
7176 this.$handle = this.$( '<span>' );
7177
7178 // Events
7179 this.$handle.on( {
7180 'mousedown touchstart': OO.ui.bind( this.onHandlePointerDown, this ),
7181 'mouseup touchend': OO.ui.bind( this.onHandlePointerUp, this )
7182 } );
7183
7184 // Initialization
7185 this.$handle
7186 .addClass( 'oo-ui-popupToolGroup-handle' )
7187 .append( this.$icon, this.$label, this.$indicator );
7188 // If the pop-up should have a header, add it to the top of the toolGroup.
7189 // Note: If this feature is useful for other widgets, we could abstract it into an
7190 // OO.ui.HeaderedElement mixin constructor.
7191 if ( config.header !== undefined ) {
7192 this.$group
7193 .prepend( this.$( '<span>' )
7194 .addClass( 'oo-ui-popupToolGroup-header' )
7195 .text( config.header )
7196 );
7197 }
7198 this.$element
7199 .addClass( 'oo-ui-popupToolGroup' )
7200 .prepend( this.$handle );
7201 };
7202
7203 /* Setup */
7204
7205 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
7206 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
7207 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
7208 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
7209 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
7210 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
7211
7212 /* Static Properties */
7213
7214 /* Methods */
7215
7216 /**
7217 * @inheritdoc
7218 */
7219 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
7220 // Parent method
7221 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
7222
7223 if ( this.isDisabled() && this.isElementAttached() ) {
7224 this.setActive( false );
7225 }
7226 };
7227
7228 /**
7229 * Handle focus being lost.
7230 *
7231 * The event is actually generated from a mouseup, so it is not a normal blur event object.
7232 *
7233 * @param {jQuery.Event} e Mouse up event
7234 */
7235 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
7236 // Only deactivate when clicking outside the dropdown element
7237 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
7238 this.setActive( false );
7239 }
7240 };
7241
7242 /**
7243 * @inheritdoc
7244 */
7245 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
7246 // e.which is 0 for touch events, 1 for left mouse button
7247 if ( !this.isDisabled() && e.which <= 1 ) {
7248 this.setActive( false );
7249 }
7250 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
7251 };
7252
7253 /**
7254 * Handle mouse up events.
7255 *
7256 * @param {jQuery.Event} e Mouse up event
7257 */
7258 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
7259 return false;
7260 };
7261
7262 /**
7263 * Handle mouse down events.
7264 *
7265 * @param {jQuery.Event} e Mouse down event
7266 */
7267 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
7268 // e.which is 0 for touch events, 1 for left mouse button
7269 if ( !this.isDisabled() && e.which <= 1 ) {
7270 this.setActive( !this.active );
7271 }
7272 return false;
7273 };
7274
7275 /**
7276 * Switch into active mode.
7277 *
7278 * When active, mouseup events anywhere in the document will trigger deactivation.
7279 */
7280 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
7281 value = !!value;
7282 if ( this.active !== value ) {
7283 this.active = value;
7284 if ( value ) {
7285 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
7286
7287 // Try anchoring the popup to the left first
7288 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
7289 this.toggleClipping( true );
7290 if ( this.isClippedHorizontally() ) {
7291 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
7292 this.toggleClipping( false );
7293 this.$element
7294 .removeClass( 'oo-ui-popupToolGroup-left' )
7295 .addClass( 'oo-ui-popupToolGroup-right' );
7296 this.toggleClipping( true );
7297 }
7298 } else {
7299 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
7300 this.$element.removeClass(
7301 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
7302 );
7303 this.toggleClipping( false );
7304 }
7305 }
7306 };
7307
7308 /**
7309 * Drop down list layout of tools as labeled icon buttons.
7310 *
7311 * @class
7312 * @extends OO.ui.PopupToolGroup
7313 *
7314 * @constructor
7315 * @param {OO.ui.Toolbar} toolbar
7316 * @param {Object} [config] Configuration options
7317 */
7318 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
7319 // Parent constructor
7320 OO.ui.ListToolGroup.super.call( this, toolbar, config );
7321
7322 // Initialization
7323 this.$element.addClass( 'oo-ui-listToolGroup' );
7324 };
7325
7326 /* Setup */
7327
7328 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
7329
7330 /* Static Properties */
7331
7332 OO.ui.ListToolGroup.static.accelTooltips = true;
7333
7334 OO.ui.ListToolGroup.static.name = 'list';
7335
7336 /**
7337 * Drop down menu layout of tools as selectable menu items.
7338 *
7339 * @class
7340 * @extends OO.ui.PopupToolGroup
7341 *
7342 * @constructor
7343 * @param {OO.ui.Toolbar} toolbar
7344 * @param {Object} [config] Configuration options
7345 */
7346 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
7347 // Configuration initialization
7348 config = config || {};
7349
7350 // Parent constructor
7351 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
7352
7353 // Events
7354 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
7355
7356 // Initialization
7357 this.$element.addClass( 'oo-ui-menuToolGroup' );
7358 };
7359
7360 /* Setup */
7361
7362 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
7363
7364 /* Static Properties */
7365
7366 OO.ui.MenuToolGroup.static.accelTooltips = true;
7367
7368 OO.ui.MenuToolGroup.static.name = 'menu';
7369
7370 /* Methods */
7371
7372 /**
7373 * Handle the toolbar state being updated.
7374 *
7375 * When the state changes, the title of each active item in the menu will be joined together and
7376 * used as a label for the group. The label will be empty if none of the items are active.
7377 */
7378 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
7379 var name,
7380 labelTexts = [];
7381
7382 for ( name in this.tools ) {
7383 if ( this.tools[name].isActive() ) {
7384 labelTexts.push( this.tools[name].getTitle() );
7385 }
7386 }
7387
7388 this.setLabel( labelTexts.join( ', ' ) || ' ' );
7389 };
7390
7391 /**
7392 * Tool that shows a popup when selected.
7393 *
7394 * @abstract
7395 * @class
7396 * @extends OO.ui.Tool
7397 * @mixins OO.ui.PopupElement
7398 *
7399 * @constructor
7400 * @param {OO.ui.Toolbar} toolbar
7401 * @param {Object} [config] Configuration options
7402 */
7403 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
7404 // Parent constructor
7405 OO.ui.PopupTool.super.call( this, toolbar, config );
7406
7407 // Mixin constructors
7408 OO.ui.PopupElement.call( this, config );
7409
7410 // Initialization
7411 this.$element
7412 .addClass( 'oo-ui-popupTool' )
7413 .append( this.popup.$element );
7414 };
7415
7416 /* Setup */
7417
7418 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
7419 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
7420
7421 /* Methods */
7422
7423 /**
7424 * Handle the tool being selected.
7425 *
7426 * @inheritdoc
7427 */
7428 OO.ui.PopupTool.prototype.onSelect = function () {
7429 if ( !this.isDisabled() ) {
7430 this.popup.toggle();
7431 }
7432 this.setActive( false );
7433 return false;
7434 };
7435
7436 /**
7437 * Handle the toolbar state being updated.
7438 *
7439 * @inheritdoc
7440 */
7441 OO.ui.PopupTool.prototype.onUpdateState = function () {
7442 this.setActive( false );
7443 };
7444
7445 /**
7446 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
7447 *
7448 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
7449 *
7450 * @abstract
7451 * @class
7452 * @extends OO.ui.GroupElement
7453 *
7454 * @constructor
7455 * @param {Object} [config] Configuration options
7456 */
7457 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
7458 // Parent constructor
7459 OO.ui.GroupWidget.super.call( this, config );
7460 };
7461
7462 /* Setup */
7463
7464 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
7465
7466 /* Methods */
7467
7468 /**
7469 * Set the disabled state of the widget.
7470 *
7471 * This will also update the disabled state of child widgets.
7472 *
7473 * @param {boolean} disabled Disable widget
7474 * @chainable
7475 */
7476 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
7477 var i, len;
7478
7479 // Parent method
7480 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
7481 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
7482
7483 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
7484 if ( this.items ) {
7485 for ( i = 0, len = this.items.length; i < len; i++ ) {
7486 this.items[i].updateDisabled();
7487 }
7488 }
7489
7490 return this;
7491 };
7492
7493 /**
7494 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
7495 *
7496 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
7497 * allows bidrectional communication.
7498 *
7499 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
7500 *
7501 * @abstract
7502 * @class
7503 *
7504 * @constructor
7505 */
7506 OO.ui.ItemWidget = function OoUiItemWidget() {
7507 //
7508 };
7509
7510 /* Methods */
7511
7512 /**
7513 * Check if widget is disabled.
7514 *
7515 * Checks parent if present, making disabled state inheritable.
7516 *
7517 * @return {boolean} Widget is disabled
7518 */
7519 OO.ui.ItemWidget.prototype.isDisabled = function () {
7520 return this.disabled ||
7521 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
7522 };
7523
7524 /**
7525 * Set group element is in.
7526 *
7527 * @param {OO.ui.GroupElement|null} group Group element, null if none
7528 * @chainable
7529 */
7530 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
7531 // Parent method
7532 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
7533 OO.ui.Element.prototype.setElementGroup.call( this, group );
7534
7535 // Initialize item disabled states
7536 this.updateDisabled();
7537
7538 return this;
7539 };
7540
7541 /**
7542 * Mixin that adds a menu showing suggested values for a text input.
7543 *
7544 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
7545 *
7546 * @class
7547 * @abstract
7548 *
7549 * @constructor
7550 * @param {OO.ui.TextInputWidget} input Input widget
7551 * @param {Object} [config] Configuration options
7552 * @cfg {jQuery} [$overlay=this.$( 'body' )] Overlay layer
7553 */
7554 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
7555 // Config intialization
7556 config = config || {};
7557
7558 // Properties
7559 this.lookupInput = input;
7560 this.$overlay = config.$overlay || this.$( 'body,.oo-ui-window-overlay' ).last();
7561 this.lookupMenu = new OO.ui.TextInputMenuWidget( this, {
7562 $: OO.ui.Element.getJQuery( this.$overlay ),
7563 input: this.lookupInput,
7564 $container: config.$container
7565 } );
7566 this.lookupCache = {};
7567 this.lookupQuery = null;
7568 this.lookupRequest = null;
7569 this.populating = false;
7570
7571 // Events
7572 this.$overlay.append( this.lookupMenu.$element );
7573
7574 this.lookupInput.$input.on( {
7575 focus: OO.ui.bind( this.onLookupInputFocus, this ),
7576 blur: OO.ui.bind( this.onLookupInputBlur, this ),
7577 mousedown: OO.ui.bind( this.onLookupInputMouseDown, this )
7578 } );
7579 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
7580
7581 // Initialization
7582 this.$element.addClass( 'oo-ui-lookupWidget' );
7583 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
7584 };
7585
7586 /* Methods */
7587
7588 /**
7589 * Handle input focus event.
7590 *
7591 * @param {jQuery.Event} e Input focus event
7592 */
7593 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
7594 this.openLookupMenu();
7595 };
7596
7597 /**
7598 * Handle input blur event.
7599 *
7600 * @param {jQuery.Event} e Input blur event
7601 */
7602 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
7603 this.lookupMenu.toggle( false );
7604 };
7605
7606 /**
7607 * Handle input mouse down event.
7608 *
7609 * @param {jQuery.Event} e Input mouse down event
7610 */
7611 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
7612 this.openLookupMenu();
7613 };
7614
7615 /**
7616 * Handle input change event.
7617 *
7618 * @param {string} value New input value
7619 */
7620 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
7621 this.openLookupMenu();
7622 };
7623
7624 /**
7625 * Get lookup menu.
7626 *
7627 * @return {OO.ui.TextInputMenuWidget}
7628 */
7629 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
7630 return this.lookupMenu;
7631 };
7632
7633 /**
7634 * Open the menu.
7635 *
7636 * @chainable
7637 */
7638 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
7639 var value = this.lookupInput.getValue();
7640
7641 if ( this.lookupMenu.$input.is( ':focus' ) && $.trim( value ) !== '' ) {
7642 this.populateLookupMenu();
7643 this.lookupMenu.toggle( true );
7644 } else {
7645 this.lookupMenu
7646 .clearItems()
7647 .toggle( false );
7648 }
7649
7650 return this;
7651 };
7652
7653 /**
7654 * Populate lookup menu with current information.
7655 *
7656 * @chainable
7657 */
7658 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
7659 var widget = this;
7660
7661 if ( !this.populating ) {
7662 this.populating = true;
7663 this.getLookupMenuItems()
7664 .done( function ( items ) {
7665 widget.lookupMenu.clearItems();
7666 if ( items.length ) {
7667 widget.lookupMenu
7668 .addItems( items )
7669 .toggle( true );
7670 widget.initializeLookupMenuSelection();
7671 widget.openLookupMenu();
7672 } else {
7673 widget.lookupMenu.toggle( true );
7674 }
7675 widget.populating = false;
7676 } )
7677 .fail( function () {
7678 widget.lookupMenu.clearItems();
7679 widget.populating = false;
7680 } );
7681 }
7682
7683 return this;
7684 };
7685
7686 /**
7687 * Set selection in the lookup menu with current information.
7688 *
7689 * @chainable
7690 */
7691 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
7692 if ( !this.lookupMenu.getSelectedItem() ) {
7693 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
7694 }
7695 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
7696 };
7697
7698 /**
7699 * Get lookup menu items for the current query.
7700 *
7701 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
7702 * of the done event
7703 */
7704 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
7705 var widget = this,
7706 value = this.lookupInput.getValue(),
7707 deferred = $.Deferred();
7708
7709 if ( value && value !== this.lookupQuery ) {
7710 // Abort current request if query has changed
7711 if ( this.lookupRequest ) {
7712 this.lookupRequest.abort();
7713 this.lookupQuery = null;
7714 this.lookupRequest = null;
7715 }
7716 if ( value in this.lookupCache ) {
7717 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
7718 } else {
7719 this.lookupQuery = value;
7720 this.lookupRequest = this.getLookupRequest()
7721 .always( function () {
7722 widget.lookupQuery = null;
7723 widget.lookupRequest = null;
7724 } )
7725 .done( function ( data ) {
7726 widget.lookupCache[value] = widget.getLookupCacheItemFromData( data );
7727 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[value] ) );
7728 } )
7729 .fail( function () {
7730 deferred.reject();
7731 } );
7732 this.pushPending();
7733 this.lookupRequest.always( function () {
7734 widget.popPending();
7735 } );
7736 }
7737 }
7738 return deferred.promise();
7739 };
7740
7741 /**
7742 * Get a new request object of the current lookup query value.
7743 *
7744 * @abstract
7745 * @return {jqXHR} jQuery AJAX object, or promise object with an .abort() method
7746 */
7747 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
7748 // Stub, implemented in subclass
7749 return null;
7750 };
7751
7752 /**
7753 * Handle successful lookup request.
7754 *
7755 * Overriding methods should call #populateLookupMenu when results are available and cache results
7756 * for future lookups in #lookupCache as an array of #OO.ui.MenuItemWidget objects.
7757 *
7758 * @abstract
7759 * @param {Mixed} data Response from server
7760 */
7761 OO.ui.LookupInputWidget.prototype.onLookupRequestDone = function () {
7762 // Stub, implemented in subclass
7763 };
7764
7765 /**
7766 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
7767 *
7768 * @abstract
7769 * @param {Mixed} data Cached result data, usually an array
7770 * @return {OO.ui.MenuItemWidget[]} Menu items
7771 */
7772 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
7773 // Stub, implemented in subclass
7774 return [];
7775 };
7776
7777 /**
7778 * Set of controls for an OO.ui.OutlineWidget.
7779 *
7780 * Controls include moving items up and down, removing items, and adding different kinds of items.
7781 *
7782 * @class
7783 * @extends OO.ui.Widget
7784 * @mixins OO.ui.GroupElement
7785 * @mixins OO.ui.IconElement
7786 *
7787 * @constructor
7788 * @param {OO.ui.OutlineWidget} outline Outline to control
7789 * @param {Object} [config] Configuration options
7790 */
7791 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
7792 // Configuration initialization
7793 config = $.extend( { icon: 'add-item' }, config );
7794
7795 // Parent constructor
7796 OO.ui.OutlineControlsWidget.super.call( this, config );
7797
7798 // Mixin constructors
7799 OO.ui.GroupElement.call( this, config );
7800 OO.ui.IconElement.call( this, config );
7801
7802 // Properties
7803 this.outline = outline;
7804 this.$movers = this.$( '<div>' );
7805 this.upButton = new OO.ui.ButtonWidget( {
7806 $: this.$,
7807 framed: false,
7808 icon: 'collapse',
7809 title: OO.ui.msg( 'ooui-outline-control-move-up' )
7810 } );
7811 this.downButton = new OO.ui.ButtonWidget( {
7812 $: this.$,
7813 framed: false,
7814 icon: 'expand',
7815 title: OO.ui.msg( 'ooui-outline-control-move-down' )
7816 } );
7817 this.removeButton = new OO.ui.ButtonWidget( {
7818 $: this.$,
7819 framed: false,
7820 icon: 'remove',
7821 title: OO.ui.msg( 'ooui-outline-control-remove' )
7822 } );
7823
7824 // Events
7825 outline.connect( this, {
7826 select: 'onOutlineChange',
7827 add: 'onOutlineChange',
7828 remove: 'onOutlineChange'
7829 } );
7830 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
7831 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
7832 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
7833
7834 // Initialization
7835 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
7836 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
7837 this.$movers
7838 .addClass( 'oo-ui-outlineControlsWidget-movers' )
7839 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
7840 this.$element.append( this.$icon, this.$group, this.$movers );
7841 };
7842
7843 /* Setup */
7844
7845 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
7846 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
7847 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
7848
7849 /* Events */
7850
7851 /**
7852 * @event move
7853 * @param {number} places Number of places to move
7854 */
7855
7856 /**
7857 * @event remove
7858 */
7859
7860 /* Methods */
7861
7862 /**
7863 * Handle outline change events.
7864 */
7865 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
7866 var i, len, firstMovable, lastMovable,
7867 items = this.outline.getItems(),
7868 selectedItem = this.outline.getSelectedItem(),
7869 movable = selectedItem && selectedItem.isMovable(),
7870 removable = selectedItem && selectedItem.isRemovable();
7871
7872 if ( movable ) {
7873 i = -1;
7874 len = items.length;
7875 while ( ++i < len ) {
7876 if ( items[i].isMovable() ) {
7877 firstMovable = items[i];
7878 break;
7879 }
7880 }
7881 i = len;
7882 while ( i-- ) {
7883 if ( items[i].isMovable() ) {
7884 lastMovable = items[i];
7885 break;
7886 }
7887 }
7888 }
7889 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
7890 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
7891 this.removeButton.setDisabled( !removable );
7892 };
7893
7894 /**
7895 * Mixin for widgets with a boolean on/off state.
7896 *
7897 * @abstract
7898 * @class
7899 *
7900 * @constructor
7901 * @param {Object} [config] Configuration options
7902 * @cfg {boolean} [value=false] Initial value
7903 */
7904 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
7905 // Configuration initialization
7906 config = config || {};
7907
7908 // Properties
7909 this.value = null;
7910
7911 // Initialization
7912 this.$element.addClass( 'oo-ui-toggleWidget' );
7913 this.setValue( !!config.value );
7914 };
7915
7916 /* Events */
7917
7918 /**
7919 * @event change
7920 * @param {boolean} value Changed value
7921 */
7922
7923 /* Methods */
7924
7925 /**
7926 * Get the value of the toggle.
7927 *
7928 * @return {boolean}
7929 */
7930 OO.ui.ToggleWidget.prototype.getValue = function () {
7931 return this.value;
7932 };
7933
7934 /**
7935 * Set the value of the toggle.
7936 *
7937 * @param {boolean} value New value
7938 * @fires change
7939 * @chainable
7940 */
7941 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
7942 value = !!value;
7943 if ( this.value !== value ) {
7944 this.value = value;
7945 this.emit( 'change', value );
7946 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
7947 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
7948 }
7949 return this;
7950 };
7951
7952 /**
7953 * Group widget for multiple related buttons.
7954 *
7955 * Use together with OO.ui.ButtonWidget.
7956 *
7957 * @class
7958 * @extends OO.ui.Widget
7959 * @mixins OO.ui.GroupElement
7960 *
7961 * @constructor
7962 * @param {Object} [config] Configuration options
7963 * @cfg {OO.ui.ButtonWidget} [items] Buttons to add
7964 */
7965 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
7966 // Parent constructor
7967 OO.ui.ButtonGroupWidget.super.call( this, config );
7968
7969 // Mixin constructors
7970 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
7971
7972 // Initialization
7973 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
7974 if ( $.isArray( config.items ) ) {
7975 this.addItems( config.items );
7976 }
7977 };
7978
7979 /* Setup */
7980
7981 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
7982 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
7983
7984 /**
7985 * Generic widget for buttons.
7986 *
7987 * @class
7988 * @extends OO.ui.Widget
7989 * @mixins OO.ui.ButtonElement
7990 * @mixins OO.ui.IconElement
7991 * @mixins OO.ui.IndicatorElement
7992 * @mixins OO.ui.LabelElement
7993 * @mixins OO.ui.TitledElement
7994 * @mixins OO.ui.FlaggedElement
7995 *
7996 * @constructor
7997 * @param {Object} [config] Configuration options
7998 * @cfg {string} [href] Hyperlink to visit when clicked
7999 * @cfg {string} [target] Target to open hyperlink in
8000 */
8001 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
8002 // Configuration initialization
8003 config = $.extend( { target: '_blank' }, config );
8004
8005 // Parent constructor
8006 OO.ui.ButtonWidget.super.call( this, config );
8007
8008 // Mixin constructors
8009 OO.ui.ButtonElement.call( this, config );
8010 OO.ui.IconElement.call( this, config );
8011 OO.ui.IndicatorElement.call( this, config );
8012 OO.ui.LabelElement.call( this, config );
8013 OO.ui.TitledElement.call( this, config, $.extend( {}, config, { $titled: this.$button } ) );
8014 OO.ui.FlaggedElement.call( this, config );
8015
8016 // Properties
8017 this.href = null;
8018 this.target = null;
8019 this.isHyperlink = false;
8020
8021 // Events
8022 this.$button.on( {
8023 click: OO.ui.bind( this.onClick, this ),
8024 keypress: OO.ui.bind( this.onKeyPress, this )
8025 } );
8026
8027 // Initialization
8028 this.$button.append( this.$icon, this.$label, this.$indicator );
8029 this.$element
8030 .addClass( 'oo-ui-buttonWidget' )
8031 .append( this.$button );
8032 this.setHref( config.href );
8033 this.setTarget( config.target );
8034 };
8035
8036 /* Setup */
8037
8038 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
8039 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
8040 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
8041 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
8042 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
8043 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
8044 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
8045
8046 /* Events */
8047
8048 /**
8049 * @event click
8050 */
8051
8052 /* Methods */
8053
8054 /**
8055 * Handles mouse click events.
8056 *
8057 * @param {jQuery.Event} e Mouse click event
8058 * @fires click
8059 */
8060 OO.ui.ButtonWidget.prototype.onClick = function () {
8061 if ( !this.isDisabled() ) {
8062 this.emit( 'click' );
8063 if ( this.isHyperlink ) {
8064 return true;
8065 }
8066 }
8067 return false;
8068 };
8069
8070 /**
8071 * Handles keypress events.
8072 *
8073 * @param {jQuery.Event} e Keypress event
8074 * @fires click
8075 */
8076 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
8077 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
8078 this.onClick();
8079 if ( this.isHyperlink ) {
8080 return true;
8081 }
8082 }
8083 return false;
8084 };
8085
8086 /**
8087 * Get hyperlink location.
8088 *
8089 * @return {string} Hyperlink location
8090 */
8091 OO.ui.ButtonWidget.prototype.getHref = function () {
8092 return this.href;
8093 };
8094
8095 /**
8096 * Get hyperlink target.
8097 *
8098 * @return {string} Hyperlink target
8099 */
8100 OO.ui.ButtonWidget.prototype.getTarget = function () {
8101 return this.target;
8102 };
8103
8104 /**
8105 * Set hyperlink location.
8106 *
8107 * @param {string|null} href Hyperlink location, null to remove
8108 */
8109 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
8110 href = typeof href === 'string' ? href : null;
8111
8112 if ( href !== this.href ) {
8113 this.href = href;
8114 if ( href !== null ) {
8115 this.$button.attr( 'href', href );
8116 this.isHyperlink = true;
8117 } else {
8118 this.$button.removeAttr( 'href' );
8119 this.isHyperlink = false;
8120 }
8121 }
8122
8123 return this;
8124 };
8125
8126 /**
8127 * Set hyperlink target.
8128 *
8129 * @param {string|null} target Hyperlink target, null to remove
8130 */
8131 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
8132 target = typeof target === 'string' ? target : null;
8133
8134 if ( target !== this.target ) {
8135 this.target = target;
8136 if ( target !== null ) {
8137 this.$button.attr( 'target', target );
8138 } else {
8139 this.$button.removeAttr( 'target' );
8140 }
8141 }
8142
8143 return this;
8144 };
8145
8146 /**
8147 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
8148 *
8149 * @class
8150 * @extends OO.ui.ButtonWidget
8151 *
8152 * @constructor
8153 * @param {Object} [config] Configuration options
8154 * @cfg {string} [action] Symbolic action name
8155 * @cfg {string[]} [modes] Symbolic mode names
8156 */
8157 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
8158 // Config intialization
8159 config = $.extend( { framed: false }, config );
8160
8161 // Parent constructor
8162 OO.ui.ActionWidget.super.call( this, config );
8163
8164 // Properties
8165 this.action = config.action || '';
8166 this.modes = config.modes || [];
8167 this.width = 0;
8168 this.height = 0;
8169
8170 // Initialization
8171 this.$element.addClass( 'oo-ui-actionWidget' );
8172 };
8173
8174 /* Setup */
8175
8176 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
8177
8178 /* Events */
8179
8180 /**
8181 * @event resize
8182 */
8183
8184 /* Methods */
8185
8186 /**
8187 * Check if action is available in a certain mode.
8188 *
8189 * @param {string} mode Name of mode
8190 * @return {boolean} Has mode
8191 */
8192 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
8193 return this.modes.indexOf( mode ) !== -1;
8194 };
8195
8196 /**
8197 * Get symbolic action name.
8198 *
8199 * @return {string}
8200 */
8201 OO.ui.ActionWidget.prototype.getAction = function () {
8202 return this.action;
8203 };
8204
8205 /**
8206 * Get symbolic action name.
8207 *
8208 * @return {string}
8209 */
8210 OO.ui.ActionWidget.prototype.getModes = function () {
8211 return this.modes.slice();
8212 };
8213
8214 /**
8215 * Emit a resize event if the size has changed.
8216 *
8217 * @chainable
8218 */
8219 OO.ui.ActionWidget.prototype.propagateResize = function () {
8220 var width, height;
8221
8222 if ( this.isElementAttached() ) {
8223 width = this.$element.width();
8224 height = this.$element.height();
8225
8226 if ( width !== this.width || height !== this.height ) {
8227 this.width = width;
8228 this.height = height;
8229 this.emit( 'resize' );
8230 }
8231 }
8232
8233 return this;
8234 };
8235
8236 /**
8237 * @inheritdoc
8238 */
8239 OO.ui.ActionWidget.prototype.setIcon = function () {
8240 // Mixin method
8241 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
8242 this.propagateResize();
8243
8244 return this;
8245 };
8246
8247 /**
8248 * @inheritdoc
8249 */
8250 OO.ui.ActionWidget.prototype.setLabel = function () {
8251 // Mixin method
8252 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
8253 this.propagateResize();
8254
8255 return this;
8256 };
8257
8258 /**
8259 * @inheritdoc
8260 */
8261 OO.ui.ActionWidget.prototype.setFlags = function () {
8262 // Mixin method
8263 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
8264 this.propagateResize();
8265
8266 return this;
8267 };
8268
8269 /**
8270 * @inheritdoc
8271 */
8272 OO.ui.ActionWidget.prototype.clearFlags = function () {
8273 // Mixin method
8274 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
8275 this.propagateResize();
8276
8277 return this;
8278 };
8279
8280 /**
8281 * Toggle visibility of button.
8282 *
8283 * @param {boolean} [show] Show button, omit to toggle visibility
8284 * @chainable
8285 */
8286 OO.ui.ActionWidget.prototype.toggle = function () {
8287 // Parent method
8288 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
8289 this.propagateResize();
8290
8291 return this;
8292 };
8293
8294 /**
8295 * Button that shows and hides a popup.
8296 *
8297 * @class
8298 * @extends OO.ui.ButtonWidget
8299 * @mixins OO.ui.PopupElement
8300 *
8301 * @constructor
8302 * @param {Object} [config] Configuration options
8303 */
8304 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
8305 // Parent constructor
8306 OO.ui.PopupButtonWidget.super.call( this, config );
8307
8308 // Mixin constructors
8309 OO.ui.PopupElement.call( this, config );
8310
8311 // Initialization
8312 this.$element
8313 .addClass( 'oo-ui-popupButtonWidget' )
8314 .append( this.popup.$element );
8315 };
8316
8317 /* Setup */
8318
8319 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
8320 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
8321
8322 /* Methods */
8323
8324 /**
8325 * Handles mouse click events.
8326 *
8327 * @param {jQuery.Event} e Mouse click event
8328 */
8329 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
8330 // Skip clicks within the popup
8331 if ( $.contains( this.popup.$element[0], e.target ) ) {
8332 return;
8333 }
8334
8335 if ( !this.isDisabled() ) {
8336 this.popup.toggle();
8337 // Parent method
8338 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
8339 }
8340 return false;
8341 };
8342
8343 /**
8344 * Button that toggles on and off.
8345 *
8346 * @class
8347 * @extends OO.ui.ButtonWidget
8348 * @mixins OO.ui.ToggleWidget
8349 *
8350 * @constructor
8351 * @param {Object} [config] Configuration options
8352 * @cfg {boolean} [value=false] Initial value
8353 */
8354 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
8355 // Configuration initialization
8356 config = config || {};
8357
8358 // Parent constructor
8359 OO.ui.ToggleButtonWidget.super.call( this, config );
8360
8361 // Mixin constructors
8362 OO.ui.ToggleWidget.call( this, config );
8363
8364 // Initialization
8365 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
8366 };
8367
8368 /* Setup */
8369
8370 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
8371 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
8372
8373 /* Methods */
8374
8375 /**
8376 * @inheritdoc
8377 */
8378 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
8379 if ( !this.isDisabled() ) {
8380 this.setValue( !this.value );
8381 }
8382
8383 // Parent method
8384 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
8385 };
8386
8387 /**
8388 * @inheritdoc
8389 */
8390 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
8391 value = !!value;
8392 if ( value !== this.value ) {
8393 this.setActive( value );
8394 }
8395
8396 // Parent method (from mixin)
8397 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
8398
8399 return this;
8400 };
8401
8402 /**
8403 * Icon widget.
8404 *
8405 * See OO.ui.IconElement for more information.
8406 *
8407 * @class
8408 * @extends OO.ui.Widget
8409 * @mixins OO.ui.IconElement
8410 * @mixins OO.ui.TitledElement
8411 *
8412 * @constructor
8413 * @param {Object} [config] Configuration options
8414 */
8415 OO.ui.IconWidget = function OoUiIconWidget( config ) {
8416 // Config intialization
8417 config = config || {};
8418
8419 // Parent constructor
8420 OO.ui.IconWidget.super.call( this, config );
8421
8422 // Mixin constructors
8423 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
8424 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
8425
8426 // Initialization
8427 this.$element.addClass( 'oo-ui-iconWidget' );
8428 };
8429
8430 /* Setup */
8431
8432 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
8433 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
8434 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
8435
8436 /* Static Properties */
8437
8438 OO.ui.IconWidget.static.tagName = 'span';
8439
8440 /**
8441 * Indicator widget.
8442 *
8443 * See OO.ui.IndicatorElement for more information.
8444 *
8445 * @class
8446 * @extends OO.ui.Widget
8447 * @mixins OO.ui.IndicatorElement
8448 * @mixins OO.ui.TitledElement
8449 *
8450 * @constructor
8451 * @param {Object} [config] Configuration options
8452 */
8453 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
8454 // Config intialization
8455 config = config || {};
8456
8457 // Parent constructor
8458 OO.ui.IndicatorWidget.super.call( this, config );
8459
8460 // Mixin constructors
8461 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
8462 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
8463
8464 // Initialization
8465 this.$element.addClass( 'oo-ui-indicatorWidget' );
8466 };
8467
8468 /* Setup */
8469
8470 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
8471 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
8472 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
8473
8474 /* Static Properties */
8475
8476 OO.ui.IndicatorWidget.static.tagName = 'span';
8477
8478 /**
8479 * Inline menu of options.
8480 *
8481 * Inline menus provide a control for accessing a menu and compose a menu within the widget, which
8482 * can be accessed using the #getMenu method.
8483 *
8484 * Use with OO.ui.MenuOptionWidget.
8485 *
8486 * @class
8487 * @extends OO.ui.Widget
8488 * @mixins OO.ui.IconElement
8489 * @mixins OO.ui.IndicatorElement
8490 * @mixins OO.ui.LabelElement
8491 * @mixins OO.ui.TitledElement
8492 *
8493 * @constructor
8494 * @param {Object} [config] Configuration options
8495 * @cfg {Object} [menu] Configuration options to pass to menu widget
8496 */
8497 OO.ui.InlineMenuWidget = function OoUiInlineMenuWidget( config ) {
8498 // Configuration initialization
8499 config = $.extend( { indicator: 'down' }, config );
8500
8501 // Parent constructor
8502 OO.ui.InlineMenuWidget.super.call( this, config );
8503
8504 // Mixin constructors
8505 OO.ui.IconElement.call( this, config );
8506 OO.ui.IndicatorElement.call( this, config );
8507 OO.ui.LabelElement.call( this, config );
8508 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
8509
8510 // Properties
8511 this.menu = new OO.ui.MenuWidget( $.extend( { $: this.$, widget: this }, config.menu ) );
8512 this.$handle = this.$( '<span>' );
8513
8514 // Events
8515 this.$element.on( { click: OO.ui.bind( this.onClick, this ) } );
8516 this.menu.connect( this, { select: 'onMenuSelect' } );
8517
8518 // Initialization
8519 this.$handle
8520 .addClass( 'oo-ui-inlineMenuWidget-handle' )
8521 .append( this.$icon, this.$label, this.$indicator );
8522 this.$element
8523 .addClass( 'oo-ui-inlineMenuWidget' )
8524 .append( this.$handle, this.menu.$element );
8525 };
8526
8527 /* Setup */
8528
8529 OO.inheritClass( OO.ui.InlineMenuWidget, OO.ui.Widget );
8530 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IconElement );
8531 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IndicatorElement );
8532 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.LabelElement );
8533 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.TitledElement );
8534
8535 /* Methods */
8536
8537 /**
8538 * Get the menu.
8539 *
8540 * @return {OO.ui.MenuWidget} Menu of widget
8541 */
8542 OO.ui.InlineMenuWidget.prototype.getMenu = function () {
8543 return this.menu;
8544 };
8545
8546 /**
8547 * Handles menu select events.
8548 *
8549 * @param {OO.ui.MenuItemWidget} item Selected menu item
8550 */
8551 OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) {
8552 var selectedLabel;
8553
8554 if ( !item ) {
8555 return;
8556 }
8557
8558 selectedLabel = item.getLabel();
8559
8560 // If the label is a DOM element, clone it, because setLabel will append() it
8561 if ( selectedLabel instanceof jQuery ) {
8562 selectedLabel = selectedLabel.clone();
8563 }
8564
8565 this.setLabel( selectedLabel );
8566 };
8567
8568 /**
8569 * Handles mouse click events.
8570 *
8571 * @param {jQuery.Event} e Mouse click event
8572 */
8573 OO.ui.InlineMenuWidget.prototype.onClick = function ( e ) {
8574 // Skip clicks within the menu
8575 if ( $.contains( this.menu.$element[0], e.target ) ) {
8576 return;
8577 }
8578
8579 if ( !this.isDisabled() ) {
8580 if ( this.menu.isVisible() ) {
8581 this.menu.toggle( false );
8582 } else {
8583 this.menu.toggle( true );
8584 }
8585 }
8586 return false;
8587 };
8588
8589 /**
8590 * Base class for input widgets.
8591 *
8592 * @abstract
8593 * @class
8594 * @extends OO.ui.Widget
8595 *
8596 * @constructor
8597 * @param {Object} [config] Configuration options
8598 * @cfg {string} [name=''] HTML input name
8599 * @cfg {string} [value=''] Input value
8600 * @cfg {boolean} [readOnly=false] Prevent changes
8601 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
8602 */
8603 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8604 // Config intialization
8605 config = $.extend( { readOnly: false }, config );
8606
8607 // Parent constructor
8608 OO.ui.InputWidget.super.call( this, config );
8609
8610 // Properties
8611 this.$input = this.getInputElement( config );
8612 this.value = '';
8613 this.readOnly = false;
8614 this.inputFilter = config.inputFilter;
8615
8616 // Events
8617 this.$input.on( 'keydown mouseup cut paste change input select', OO.ui.bind( this.onEdit, this ) );
8618
8619 // Initialization
8620 this.$input
8621 .attr( 'name', config.name )
8622 .prop( 'disabled', this.isDisabled() );
8623 this.setReadOnly( config.readOnly );
8624 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input );
8625 this.setValue( config.value );
8626 };
8627
8628 /* Setup */
8629
8630 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8631
8632 /* Events */
8633
8634 /**
8635 * @event change
8636 * @param value
8637 */
8638
8639 /* Methods */
8640
8641 /**
8642 * Get input element.
8643 *
8644 * @param {Object} [config] Configuration options
8645 * @return {jQuery} Input element
8646 */
8647 OO.ui.InputWidget.prototype.getInputElement = function () {
8648 return this.$( '<input>' );
8649 };
8650
8651 /**
8652 * Handle potentially value-changing events.
8653 *
8654 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8655 */
8656 OO.ui.InputWidget.prototype.onEdit = function () {
8657 var widget = this;
8658 if ( !this.isDisabled() ) {
8659 // Allow the stack to clear so the value will be updated
8660 setTimeout( function () {
8661 widget.setValue( widget.$input.val() );
8662 } );
8663 }
8664 };
8665
8666 /**
8667 * Get the value of the input.
8668 *
8669 * @return {string} Input value
8670 */
8671 OO.ui.InputWidget.prototype.getValue = function () {
8672 return this.value;
8673 };
8674
8675 /**
8676 * Sets the direction of the current input, either RTL or LTR
8677 *
8678 * @param {boolean} isRTL
8679 */
8680 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
8681 if ( isRTL ) {
8682 this.$input.removeClass( 'oo-ui-ltr' );
8683 this.$input.addClass( 'oo-ui-rtl' );
8684 } else {
8685 this.$input.removeClass( 'oo-ui-rtl' );
8686 this.$input.addClass( 'oo-ui-ltr' );
8687 }
8688 };
8689
8690 /**
8691 * Set the value of the input.
8692 *
8693 * @param {string} value New value
8694 * @fires change
8695 * @chainable
8696 */
8697 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8698 value = this.sanitizeValue( value );
8699 if ( this.value !== value ) {
8700 this.value = value;
8701 this.emit( 'change', this.value );
8702 }
8703 // Update the DOM if it has changed. Note that with sanitizeValue, it
8704 // is possible for the DOM value to change without this.value changing.
8705 if ( this.$input.val() !== this.value ) {
8706 this.$input.val( this.value );
8707 }
8708 return this;
8709 };
8710
8711 /**
8712 * Sanitize incoming value.
8713 *
8714 * Ensures value is a string, and converts undefined and null to empty strings.
8715 *
8716 * @param {string} value Original value
8717 * @return {string} Sanitized value
8718 */
8719 OO.ui.InputWidget.prototype.sanitizeValue = function ( value ) {
8720 if ( value === undefined || value === null ) {
8721 return '';
8722 } else if ( this.inputFilter ) {
8723 return this.inputFilter( String( value ) );
8724 } else {
8725 return String( value );
8726 }
8727 };
8728
8729 /**
8730 * Simulate the behavior of clicking on a label bound to this input.
8731 */
8732 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
8733 if ( !this.isDisabled() ) {
8734 if ( this.$input.is( ':checkbox,:radio' ) ) {
8735 this.$input.click();
8736 } else if ( this.$input.is( ':input' ) ) {
8737 this.$input[0].focus();
8738 }
8739 }
8740 };
8741
8742 /**
8743 * Check if the widget is read-only.
8744 *
8745 * @return {boolean}
8746 */
8747 OO.ui.InputWidget.prototype.isReadOnly = function () {
8748 return this.readOnly;
8749 };
8750
8751 /**
8752 * Set the read-only state of the widget.
8753 *
8754 * This should probably change the widgets's appearance and prevent it from being used.
8755 *
8756 * @param {boolean} state Make input read-only
8757 * @chainable
8758 */
8759 OO.ui.InputWidget.prototype.setReadOnly = function ( state ) {
8760 this.readOnly = !!state;
8761 this.$input.prop( 'readOnly', this.readOnly );
8762 return this;
8763 };
8764
8765 /**
8766 * @inheritdoc
8767 */
8768 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8769 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
8770 if ( this.$input ) {
8771 this.$input.prop( 'disabled', this.isDisabled() );
8772 }
8773 return this;
8774 };
8775
8776 /**
8777 * Focus the input.
8778 *
8779 * @chainable
8780 */
8781 OO.ui.InputWidget.prototype.focus = function () {
8782 this.$input[0].focus();
8783 return this;
8784 };
8785
8786 /**
8787 * Blur the input.
8788 *
8789 * @chainable
8790 */
8791 OO.ui.InputWidget.prototype.blur = function () {
8792 this.$input[0].blur();
8793 return this;
8794 };
8795
8796 /**
8797 * Checkbox input widget.
8798 *
8799 * @class
8800 * @extends OO.ui.InputWidget
8801 *
8802 * @constructor
8803 * @param {Object} [config] Configuration options
8804 */
8805 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
8806 // Parent constructor
8807 OO.ui.CheckboxInputWidget.super.call( this, config );
8808
8809 // Initialization
8810 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
8811 };
8812
8813 /* Setup */
8814
8815 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
8816
8817 /* Events */
8818
8819 /* Methods */
8820
8821 /**
8822 * Get input element.
8823 *
8824 * @return {jQuery} Input element
8825 */
8826 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
8827 return this.$( '<input type="checkbox" />' );
8828 };
8829
8830 /**
8831 * Get checked state of the checkbox
8832 *
8833 * @return {boolean} If the checkbox is checked
8834 */
8835 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
8836 return this.value;
8837 };
8838
8839 /**
8840 * Set value
8841 */
8842 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
8843 value = !!value;
8844 if ( this.value !== value ) {
8845 this.value = value;
8846 this.$input.prop( 'checked', this.value );
8847 this.emit( 'change', this.value );
8848 }
8849 };
8850
8851 /**
8852 * @inheritdoc
8853 */
8854 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
8855 var widget = this;
8856 if ( !this.isDisabled() ) {
8857 // Allow the stack to clear so the value will be updated
8858 setTimeout( function () {
8859 widget.setValue( widget.$input.prop( 'checked' ) );
8860 } );
8861 }
8862 };
8863
8864 /**
8865 * Input widget with a text field.
8866 *
8867 * @class
8868 * @extends OO.ui.InputWidget
8869 * @mixins OO.ui.IconElement
8870 * @mixins OO.ui.IndicatorElement
8871 *
8872 * @constructor
8873 * @param {Object} [config] Configuration options
8874 * @cfg {string} [placeholder] Placeholder text
8875 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8876 * @cfg {boolean} [autosize=false] Automatically resize to fit content
8877 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
8878 */
8879 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
8880 // Configuration initialization
8881 config = config || {};
8882
8883 // Parent constructor
8884 OO.ui.TextInputWidget.super.call( this, config );
8885
8886 // Mixin constructors
8887 OO.ui.IconElement.call( this, config );
8888 OO.ui.IndicatorElement.call( this, config );
8889
8890 // Properties
8891 this.pending = 0;
8892 this.multiline = !!config.multiline;
8893 this.autosize = !!config.autosize;
8894 this.maxRows = config.maxRows !== undefined ? config.maxRows : 10;
8895
8896 // Events
8897 this.$input.on( 'keypress', OO.ui.bind( this.onKeyPress, this ) );
8898 this.$element.on( 'DOMNodeInsertedIntoDocument', OO.ui.bind( this.onElementAttach, this ) );
8899 this.$icon.on( 'mousedown', OO.ui.bind( this.onIconMouseDown, this ) );
8900 this.$indicator.on( 'mousedown', OO.ui.bind( this.onIndicatorMouseDown, this ) );
8901
8902 // Initialization
8903 this.$element
8904 .addClass( 'oo-ui-textInputWidget' )
8905 .append( this.$icon, this.$indicator );
8906 if ( config.placeholder ) {
8907 this.$input.attr( 'placeholder', config.placeholder );
8908 }
8909 this.$element.attr( 'role', 'textbox' );
8910 };
8911
8912 /* Setup */
8913
8914 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
8915 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
8916 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
8917
8918 /* Events */
8919
8920 /**
8921 * User presses enter inside the text box.
8922 *
8923 * Not called if input is multiline.
8924 *
8925 * @event enter
8926 */
8927
8928 /**
8929 * User clicks the icon.
8930 *
8931 * @event icon
8932 */
8933
8934 /**
8935 * User clicks the indicator.
8936 *
8937 * @event indicator
8938 */
8939
8940 /* Methods */
8941
8942 /**
8943 * Handle icon mouse down events.
8944 *
8945 * @param {jQuery.Event} e Mouse down event
8946 * @fires icon
8947 */
8948 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
8949 if ( e.which === 1 ) {
8950 this.$input[0].focus();
8951 this.emit( 'icon' );
8952 return false;
8953 }
8954 };
8955
8956 /**
8957 * Handle indicator mouse down events.
8958 *
8959 * @param {jQuery.Event} e Mouse down event
8960 * @fires indicator
8961 */
8962 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
8963 if ( e.which === 1 ) {
8964 this.$input[0].focus();
8965 this.emit( 'indicator' );
8966 return false;
8967 }
8968 };
8969
8970 /**
8971 * Handle key press events.
8972 *
8973 * @param {jQuery.Event} e Key press event
8974 * @fires enter If enter key is pressed and input is not multiline
8975 */
8976 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8977 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8978 this.emit( 'enter' );
8979 }
8980 };
8981
8982 /**
8983 * Handle element attach events.
8984 *
8985 * @param {jQuery.Event} e Element attach event
8986 */
8987 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8988 this.adjustSize();
8989 };
8990
8991 /**
8992 * @inheritdoc
8993 */
8994 OO.ui.TextInputWidget.prototype.onEdit = function () {
8995 this.adjustSize();
8996
8997 // Parent method
8998 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
8999 };
9000
9001 /**
9002 * @inheritdoc
9003 */
9004 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
9005 // Parent method
9006 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
9007
9008 this.adjustSize();
9009 return this;
9010 };
9011
9012 /**
9013 * Automatically adjust the size of the text input.
9014 *
9015 * This only affects multi-line inputs that are auto-sized.
9016 *
9017 * @chainable
9018 */
9019 OO.ui.TextInputWidget.prototype.adjustSize = function () {
9020 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, idealHeight;
9021
9022 if ( this.multiline && this.autosize ) {
9023 $clone = this.$input.clone()
9024 .val( this.$input.val() )
9025 .css( { height: 0 } )
9026 .insertAfter( this.$input );
9027 // Set inline height property to 0 to measure scroll height
9028 scrollHeight = $clone[0].scrollHeight;
9029 // Remove inline height property to measure natural heights
9030 $clone.css( 'height', '' );
9031 innerHeight = $clone.innerHeight();
9032 outerHeight = $clone.outerHeight();
9033 // Measure max rows height
9034 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' );
9035 maxInnerHeight = $clone.innerHeight();
9036 $clone.removeAttr( 'rows' ).css( 'height', '' );
9037 $clone.remove();
9038 idealHeight = Math.min( maxInnerHeight, scrollHeight );
9039 // Only apply inline height when expansion beyond natural height is needed
9040 this.$input.css(
9041 'height',
9042 // Use the difference between the inner and outer height as a buffer
9043 idealHeight > outerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''
9044 );
9045 }
9046 return this;
9047 };
9048
9049 /**
9050 * Get input element.
9051 *
9052 * @param {Object} [config] Configuration options
9053 * @return {jQuery} Input element
9054 */
9055 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
9056 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="text" />' );
9057 };
9058
9059 /* Methods */
9060
9061 /**
9062 * Check if input supports multiple lines.
9063 *
9064 * @return {boolean}
9065 */
9066 OO.ui.TextInputWidget.prototype.isMultiline = function () {
9067 return !!this.multiline;
9068 };
9069
9070 /**
9071 * Check if input automatically adjusts its size.
9072 *
9073 * @return {boolean}
9074 */
9075 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
9076 return !!this.autosize;
9077 };
9078
9079 /**
9080 * Check if input is pending.
9081 *
9082 * @return {boolean}
9083 */
9084 OO.ui.TextInputWidget.prototype.isPending = function () {
9085 return !!this.pending;
9086 };
9087
9088 /**
9089 * Increase the pending stack.
9090 *
9091 * @chainable
9092 */
9093 OO.ui.TextInputWidget.prototype.pushPending = function () {
9094 if ( this.pending === 0 ) {
9095 this.$element.addClass( 'oo-ui-textInputWidget-pending' );
9096 this.$input.addClass( 'oo-ui-texture-pending' );
9097 }
9098 this.pending++;
9099
9100 return this;
9101 };
9102
9103 /**
9104 * Reduce the pending stack.
9105 *
9106 * Clamped at zero.
9107 *
9108 * @chainable
9109 */
9110 OO.ui.TextInputWidget.prototype.popPending = function () {
9111 if ( this.pending === 1 ) {
9112 this.$element.removeClass( 'oo-ui-textInputWidget-pending' );
9113 this.$input.removeClass( 'oo-ui-texture-pending' );
9114 }
9115 this.pending = Math.max( 0, this.pending - 1 );
9116
9117 return this;
9118 };
9119
9120 /**
9121 * Select the contents of the input.
9122 *
9123 * @chainable
9124 */
9125 OO.ui.TextInputWidget.prototype.select = function () {
9126 this.$input.select();
9127 return this;
9128 };
9129
9130 /**
9131 * Text input with a menu of optional values.
9132 *
9133 * @class
9134 * @extends OO.ui.Widget
9135 *
9136 * @constructor
9137 * @param {Object} [config] Configuration options
9138 * @cfg {Object} [menu] Configuration options to pass to menu widget
9139 * @cfg {Object} [input] Configuration options to pass to input widget
9140 */
9141 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
9142 // Configuration initialization
9143 config = config || {};
9144
9145 // Parent constructor
9146 OO.ui.ComboBoxWidget.super.call( this, config );
9147
9148 // Properties
9149 this.input = new OO.ui.TextInputWidget( $.extend(
9150 { $: this.$, indicator: 'down', disabled: this.isDisabled() },
9151 config.input
9152 ) );
9153 this.menu = new OO.ui.MenuWidget( $.extend(
9154 { $: this.$, widget: this, input: this.input, disabled: this.isDisabled() },
9155 config.menu
9156 ) );
9157
9158 // Events
9159 this.input.connect( this, {
9160 change: 'onInputChange',
9161 indicator: 'onInputIndicator',
9162 enter: 'onInputEnter'
9163 } );
9164 this.menu.connect( this, {
9165 choose: 'onMenuChoose',
9166 add: 'onMenuItemsChange',
9167 remove: 'onMenuItemsChange'
9168 } );
9169
9170 // Initialization
9171 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append(
9172 this.input.$element,
9173 this.menu.$element
9174 );
9175 this.onMenuItemsChange();
9176 };
9177
9178 /* Setup */
9179
9180 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
9181
9182 /* Methods */
9183
9184 /**
9185 * Handle input change events.
9186 *
9187 * @param {string} value New value
9188 */
9189 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
9190 var match = this.menu.getItemFromData( value );
9191
9192 this.menu.selectItem( match );
9193
9194 if ( !this.isDisabled() ) {
9195 this.menu.toggle( true );
9196 }
9197 };
9198
9199 /**
9200 * Handle input indicator events.
9201 */
9202 OO.ui.ComboBoxWidget.prototype.onInputIndicator = function () {
9203 if ( !this.isDisabled() ) {
9204 this.menu.toggle();
9205 }
9206 };
9207
9208 /**
9209 * Handle input enter events.
9210 */
9211 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
9212 if ( !this.isDisabled() ) {
9213 this.menu.toggle( false );
9214 }
9215 };
9216
9217 /**
9218 * Handle menu choose events.
9219 *
9220 * @param {OO.ui.OptionWidget} item Chosen item
9221 */
9222 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
9223 if ( item ) {
9224 this.input.setValue( item.getData() );
9225 }
9226 };
9227
9228 /**
9229 * Handle menu item change events.
9230 */
9231 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
9232 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
9233 };
9234
9235 /**
9236 * @inheritdoc
9237 */
9238 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
9239 // Parent method
9240 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
9241
9242 if ( this.input ) {
9243 this.input.setDisabled( this.isDisabled() );
9244 }
9245 if ( this.menu ) {
9246 this.menu.setDisabled( this.isDisabled() );
9247 }
9248
9249 return this;
9250 };
9251
9252 /**
9253 * Label widget.
9254 *
9255 * @class
9256 * @extends OO.ui.Widget
9257 * @mixins OO.ui.LabelElement
9258 *
9259 * @constructor
9260 * @param {Object} [config] Configuration options
9261 */
9262 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
9263 // Config intialization
9264 config = config || {};
9265
9266 // Parent constructor
9267 OO.ui.LabelWidget.super.call( this, config );
9268
9269 // Mixin constructors
9270 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
9271
9272 // Properties
9273 this.input = config.input;
9274
9275 // Events
9276 if ( this.input instanceof OO.ui.InputWidget ) {
9277 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
9278 }
9279
9280 // Initialization
9281 this.$element.addClass( 'oo-ui-labelWidget' );
9282 };
9283
9284 /* Setup */
9285
9286 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
9287 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
9288
9289 /* Static Properties */
9290
9291 OO.ui.LabelWidget.static.tagName = 'span';
9292
9293 /* Methods */
9294
9295 /**
9296 * Handles label mouse click events.
9297 *
9298 * @param {jQuery.Event} e Mouse click event
9299 */
9300 OO.ui.LabelWidget.prototype.onClick = function () {
9301 this.input.simulateLabelClick();
9302 return false;
9303 };
9304
9305 /**
9306 * Generic option widget for use with OO.ui.SelectWidget.
9307 *
9308 * @class
9309 * @extends OO.ui.Widget
9310 * @mixins OO.ui.LabelElement
9311 * @mixins OO.ui.FlaggedElement
9312 *
9313 * @constructor
9314 * @param {Mixed} data Option data
9315 * @param {Object} [config] Configuration options
9316 * @cfg {string} [rel] Value for `rel` attribute in DOM, allowing per-option styling
9317 */
9318 OO.ui.OptionWidget = function OoUiOptionWidget( data, config ) {
9319 // Config intialization
9320 config = config || {};
9321
9322 // Parent constructor
9323 OO.ui.OptionWidget.super.call( this, config );
9324
9325 // Mixin constructors
9326 OO.ui.ItemWidget.call( this );
9327 OO.ui.LabelElement.call( this, config );
9328 OO.ui.FlaggedElement.call( this, config );
9329
9330 // Properties
9331 this.data = data;
9332 this.selected = false;
9333 this.highlighted = false;
9334 this.pressed = false;
9335
9336 // Initialization
9337 this.$element
9338 .data( 'oo-ui-optionWidget', this )
9339 .attr( 'rel', config.rel )
9340 .attr( 'role', 'option' )
9341 .addClass( 'oo-ui-optionWidget' )
9342 .append( this.$label );
9343 this.$element
9344 .prepend( this.$icon )
9345 .append( this.$indicator );
9346 };
9347
9348 /* Setup */
9349
9350 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
9351 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
9352 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
9353 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
9354
9355 /* Static Properties */
9356
9357 OO.ui.OptionWidget.static.selectable = true;
9358
9359 OO.ui.OptionWidget.static.highlightable = true;
9360
9361 OO.ui.OptionWidget.static.pressable = true;
9362
9363 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
9364
9365 /* Methods */
9366
9367 /**
9368 * Check if option can be selected.
9369 *
9370 * @return {boolean} Item is selectable
9371 */
9372 OO.ui.OptionWidget.prototype.isSelectable = function () {
9373 return this.constructor.static.selectable && !this.isDisabled();
9374 };
9375
9376 /**
9377 * Check if option can be highlighted.
9378 *
9379 * @return {boolean} Item is highlightable
9380 */
9381 OO.ui.OptionWidget.prototype.isHighlightable = function () {
9382 return this.constructor.static.highlightable && !this.isDisabled();
9383 };
9384
9385 /**
9386 * Check if option can be pressed.
9387 *
9388 * @return {boolean} Item is pressable
9389 */
9390 OO.ui.OptionWidget.prototype.isPressable = function () {
9391 return this.constructor.static.pressable && !this.isDisabled();
9392 };
9393
9394 /**
9395 * Check if option is selected.
9396 *
9397 * @return {boolean} Item is selected
9398 */
9399 OO.ui.OptionWidget.prototype.isSelected = function () {
9400 return this.selected;
9401 };
9402
9403 /**
9404 * Check if option is highlighted.
9405 *
9406 * @return {boolean} Item is highlighted
9407 */
9408 OO.ui.OptionWidget.prototype.isHighlighted = function () {
9409 return this.highlighted;
9410 };
9411
9412 /**
9413 * Check if option is pressed.
9414 *
9415 * @return {boolean} Item is pressed
9416 */
9417 OO.ui.OptionWidget.prototype.isPressed = function () {
9418 return this.pressed;
9419 };
9420
9421 /**
9422 * Set selected state.
9423 *
9424 * @param {boolean} [state=false] Select option
9425 * @chainable
9426 */
9427 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
9428 if ( this.constructor.static.selectable ) {
9429 this.selected = !!state;
9430 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
9431 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
9432 this.scrollElementIntoView();
9433 }
9434 }
9435 return this;
9436 };
9437
9438 /**
9439 * Set highlighted state.
9440 *
9441 * @param {boolean} [state=false] Highlight option
9442 * @chainable
9443 */
9444 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
9445 if ( this.constructor.static.highlightable ) {
9446 this.highlighted = !!state;
9447 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
9448 }
9449 return this;
9450 };
9451
9452 /**
9453 * Set pressed state.
9454 *
9455 * @param {boolean} [state=false] Press option
9456 * @chainable
9457 */
9458 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
9459 if ( this.constructor.static.pressable ) {
9460 this.pressed = !!state;
9461 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
9462 }
9463 return this;
9464 };
9465
9466 /**
9467 * Make the option's highlight flash.
9468 *
9469 * While flashing, the visual style of the pressed state is removed if present.
9470 *
9471 * @return {jQuery.Promise} Promise resolved when flashing is done
9472 */
9473 OO.ui.OptionWidget.prototype.flash = function () {
9474 var widget = this,
9475 $element = this.$element,
9476 deferred = $.Deferred();
9477
9478 if ( !this.isDisabled() && this.constructor.static.pressable ) {
9479 $element.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
9480 setTimeout( function () {
9481 // Restore original classes
9482 $element
9483 .toggleClass( 'oo-ui-optionWidget-highlighted', widget.highlighted )
9484 .toggleClass( 'oo-ui-optionWidget-pressed', widget.pressed );
9485
9486 setTimeout( function () {
9487 deferred.resolve();
9488 }, 100 );
9489
9490 }, 100 );
9491 }
9492
9493 return deferred.promise();
9494 };
9495
9496 /**
9497 * Get option data.
9498 *
9499 * @return {Mixed} Option data
9500 */
9501 OO.ui.OptionWidget.prototype.getData = function () {
9502 return this.data;
9503 };
9504
9505 /**
9506 * Option widget with an option icon and indicator.
9507 *
9508 * Use together with OO.ui.SelectWidget.
9509 *
9510 * @class
9511 * @extends OO.ui.OptionWidget
9512 * @mixins OO.ui.IconElement
9513 * @mixins OO.ui.IndicatorElement
9514 *
9515 * @constructor
9516 * @param {Mixed} data Option data
9517 * @param {Object} [config] Configuration options
9518 */
9519 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( data, config ) {
9520 // Parent constructor
9521 OO.ui.DecoratedOptionWidget.super.call( this, data, config );
9522
9523 // Mixin constructors
9524 OO.ui.IconElement.call( this, config );
9525 OO.ui.IndicatorElement.call( this, config );
9526
9527 // Initialization
9528 this.$element
9529 .addClass( 'oo-ui-decoratedOptionWidget' )
9530 .prepend( this.$icon )
9531 .append( this.$indicator );
9532 };
9533
9534 /* Setup */
9535
9536 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
9537 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
9538 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
9539
9540 /**
9541 * Option widget that looks like a button.
9542 *
9543 * Use together with OO.ui.ButtonSelectWidget.
9544 *
9545 * @class
9546 * @extends OO.ui.DecoratedOptionWidget
9547 * @mixins OO.ui.ButtonElement
9548 *
9549 * @constructor
9550 * @param {Mixed} data Option data
9551 * @param {Object} [config] Configuration options
9552 */
9553 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( data, config ) {
9554 // Parent constructor
9555 OO.ui.ButtonOptionWidget.super.call( this, data, config );
9556
9557 // Mixin constructors
9558 OO.ui.ButtonElement.call( this, config );
9559
9560 // Initialization
9561 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
9562 this.$button.append( this.$element.contents() );
9563 this.$element.append( this.$button );
9564 };
9565
9566 /* Setup */
9567
9568 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
9569 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
9570
9571 /* Static Properties */
9572
9573 // Allow button mouse down events to pass through so they can be handled by the parent select widget
9574 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
9575
9576 /* Methods */
9577
9578 /**
9579 * @inheritdoc
9580 */
9581 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
9582 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
9583
9584 if ( this.constructor.static.selectable ) {
9585 this.setActive( state );
9586 }
9587
9588 return this;
9589 };
9590
9591 /**
9592 * Item of an OO.ui.MenuWidget.
9593 *
9594 * @class
9595 * @extends OO.ui.DecoratedOptionWidget
9596 *
9597 * @constructor
9598 * @param {Mixed} data Item data
9599 * @param {Object} [config] Configuration options
9600 */
9601 OO.ui.MenuItemWidget = function OoUiMenuItemWidget( data, config ) {
9602 // Configuration initialization
9603 config = $.extend( { icon: 'check' }, config );
9604
9605 // Parent constructor
9606 OO.ui.MenuItemWidget.super.call( this, data, config );
9607
9608 // Initialization
9609 this.$element
9610 .attr( 'role', 'menuitem' )
9611 .addClass( 'oo-ui-menuItemWidget' );
9612 };
9613
9614 /* Setup */
9615
9616 OO.inheritClass( OO.ui.MenuItemWidget, OO.ui.DecoratedOptionWidget );
9617
9618 /**
9619 * Section to group one or more items in a OO.ui.MenuWidget.
9620 *
9621 * @class
9622 * @extends OO.ui.DecoratedOptionWidget
9623 *
9624 * @constructor
9625 * @param {Mixed} data Item data
9626 * @param {Object} [config] Configuration options
9627 */
9628 OO.ui.MenuSectionItemWidget = function OoUiMenuSectionItemWidget( data, config ) {
9629 // Parent constructor
9630 OO.ui.MenuSectionItemWidget.super.call( this, data, config );
9631
9632 // Initialization
9633 this.$element.addClass( 'oo-ui-menuSectionItemWidget' );
9634 };
9635
9636 /* Setup */
9637
9638 OO.inheritClass( OO.ui.MenuSectionItemWidget, OO.ui.DecoratedOptionWidget );
9639
9640 /* Static Properties */
9641
9642 OO.ui.MenuSectionItemWidget.static.selectable = false;
9643
9644 OO.ui.MenuSectionItemWidget.static.highlightable = false;
9645
9646 /**
9647 * Items for an OO.ui.OutlineWidget.
9648 *
9649 * @class
9650 * @extends OO.ui.DecoratedOptionWidget
9651 *
9652 * @constructor
9653 * @param {Mixed} data Item data
9654 * @param {Object} [config] Configuration options
9655 * @cfg {number} [level] Indentation level
9656 * @cfg {boolean} [movable] Allow modification from outline controls
9657 */
9658 OO.ui.OutlineItemWidget = function OoUiOutlineItemWidget( data, config ) {
9659 // Config intialization
9660 config = config || {};
9661
9662 // Parent constructor
9663 OO.ui.OutlineItemWidget.super.call( this, data, config );
9664
9665 // Properties
9666 this.level = 0;
9667 this.movable = !!config.movable;
9668 this.removable = !!config.removable;
9669
9670 // Initialization
9671 this.$element.addClass( 'oo-ui-outlineItemWidget' );
9672 this.setLevel( config.level );
9673 };
9674
9675 /* Setup */
9676
9677 OO.inheritClass( OO.ui.OutlineItemWidget, OO.ui.DecoratedOptionWidget );
9678
9679 /* Static Properties */
9680
9681 OO.ui.OutlineItemWidget.static.highlightable = false;
9682
9683 OO.ui.OutlineItemWidget.static.scrollIntoViewOnSelect = true;
9684
9685 OO.ui.OutlineItemWidget.static.levelClass = 'oo-ui-outlineItemWidget-level-';
9686
9687 OO.ui.OutlineItemWidget.static.levels = 3;
9688
9689 /* Methods */
9690
9691 /**
9692 * Check if item is movable.
9693 *
9694 * Movablilty is used by outline controls.
9695 *
9696 * @return {boolean} Item is movable
9697 */
9698 OO.ui.OutlineItemWidget.prototype.isMovable = function () {
9699 return this.movable;
9700 };
9701
9702 /**
9703 * Check if item is removable.
9704 *
9705 * Removablilty is used by outline controls.
9706 *
9707 * @return {boolean} Item is removable
9708 */
9709 OO.ui.OutlineItemWidget.prototype.isRemovable = function () {
9710 return this.removable;
9711 };
9712
9713 /**
9714 * Get indentation level.
9715 *
9716 * @return {number} Indentation level
9717 */
9718 OO.ui.OutlineItemWidget.prototype.getLevel = function () {
9719 return this.level;
9720 };
9721
9722 /**
9723 * Set movability.
9724 *
9725 * Movablilty is used by outline controls.
9726 *
9727 * @param {boolean} movable Item is movable
9728 * @chainable
9729 */
9730 OO.ui.OutlineItemWidget.prototype.setMovable = function ( movable ) {
9731 this.movable = !!movable;
9732 return this;
9733 };
9734
9735 /**
9736 * Set removability.
9737 *
9738 * Removablilty is used by outline controls.
9739 *
9740 * @param {boolean} movable Item is removable
9741 * @chainable
9742 */
9743 OO.ui.OutlineItemWidget.prototype.setRemovable = function ( removable ) {
9744 this.removable = !!removable;
9745 return this;
9746 };
9747
9748 /**
9749 * Set indentation level.
9750 *
9751 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
9752 * @chainable
9753 */
9754 OO.ui.OutlineItemWidget.prototype.setLevel = function ( level ) {
9755 var levels = this.constructor.static.levels,
9756 levelClass = this.constructor.static.levelClass,
9757 i = levels;
9758
9759 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
9760 while ( i-- ) {
9761 if ( this.level === i ) {
9762 this.$element.addClass( levelClass + i );
9763 } else {
9764 this.$element.removeClass( levelClass + i );
9765 }
9766 }
9767
9768 return this;
9769 };
9770
9771 /**
9772 * Container for content that is overlaid and positioned absolutely.
9773 *
9774 * @class
9775 * @extends OO.ui.Widget
9776 * @mixins OO.ui.LabelElement
9777 *
9778 * @constructor
9779 * @param {Object} [config] Configuration options
9780 * @cfg {number} [width=320] Width of popup in pixels
9781 * @cfg {number} [height] Height of popup, omit to use automatic height
9782 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
9783 * @cfg {string} [align='center'] Alignment of popup to origin
9784 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
9785 * @cfg {jQuery} [$content] Content to append to the popup's body
9786 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
9787 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
9788 * @cfg {boolean} [head] Show label and close button at the top
9789 * @cfg {boolean} [padded] Add padding to the body
9790 */
9791 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
9792 // Config intialization
9793 config = config || {};
9794
9795 // Parent constructor
9796 OO.ui.PopupWidget.super.call( this, config );
9797
9798 // Mixin constructors
9799 OO.ui.LabelElement.call( this, config );
9800 OO.ui.ClippableElement.call( this, config );
9801
9802 // Properties
9803 this.visible = false;
9804 this.$popup = this.$( '<div>' );
9805 this.$head = this.$( '<div>' );
9806 this.$body = this.$( '<div>' );
9807 this.$anchor = this.$( '<div>' );
9808 this.$container = config.$container || this.$( 'body' );
9809 this.autoClose = !!config.autoClose;
9810 this.$autoCloseIgnore = config.$autoCloseIgnore;
9811 this.transitionTimeout = null;
9812 this.anchor = null;
9813 this.width = config.width !== undefined ? config.width : 320;
9814 this.height = config.height !== undefined ? config.height : null;
9815 this.align = config.align || 'center';
9816 this.closeButton = new OO.ui.ButtonWidget( { $: this.$, framed: false, icon: 'close' } );
9817 this.onMouseDownHandler = OO.ui.bind( this.onMouseDown, this );
9818
9819 // Events
9820 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
9821
9822 // Initialization
9823 this.toggleAnchor( config.anchor === undefined || config.anchor );
9824 this.$body.addClass( 'oo-ui-popupWidget-body' );
9825 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
9826 this.$head
9827 .addClass( 'oo-ui-popupWidget-head' )
9828 .append( this.$label, this.closeButton.$element );
9829 if ( !config.head ) {
9830 this.$head.hide();
9831 }
9832 this.$popup
9833 .addClass( 'oo-ui-popupWidget-popup' )
9834 .append( this.$head, this.$body );
9835 this.$element
9836 .hide()
9837 .addClass( 'oo-ui-popupWidget' )
9838 .append( this.$popup, this.$anchor );
9839 // Move content, which was added to #$element by OO.ui.Widget, to the body
9840 if ( config.$content instanceof jQuery ) {
9841 this.$body.append( config.$content );
9842 }
9843 if ( config.padded ) {
9844 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
9845 }
9846 this.setClippableElement( this.$body );
9847 };
9848
9849 /* Setup */
9850
9851 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
9852 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
9853 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
9854
9855 /* Events */
9856
9857 /**
9858 * @event hide
9859 */
9860
9861 /**
9862 * @event show
9863 */
9864
9865 /* Methods */
9866
9867 /**
9868 * Handles mouse down events.
9869 *
9870 * @param {jQuery.Event} e Mouse down event
9871 */
9872 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
9873 if (
9874 this.isVisible() &&
9875 !$.contains( this.$element[0], e.target ) &&
9876 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
9877 ) {
9878 this.toggle( false );
9879 }
9880 };
9881
9882 /**
9883 * Bind mouse down listener.
9884 */
9885 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
9886 // Capture clicks outside popup
9887 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
9888 };
9889
9890 /**
9891 * Handles close button click events.
9892 */
9893 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
9894 if ( this.isVisible() ) {
9895 this.toggle( false );
9896 }
9897 };
9898
9899 /**
9900 * Unbind mouse down listener.
9901 */
9902 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
9903 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
9904 };
9905
9906 /**
9907 * Set whether to show a anchor.
9908 *
9909 * @param {boolean} [show] Show anchor, omit to toggle
9910 */
9911 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
9912 show = show === undefined ? !this.anchored : !!show;
9913
9914 if ( this.anchored !== show ) {
9915 if ( show ) {
9916 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
9917 } else {
9918 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
9919 }
9920 this.anchored = show;
9921 }
9922 };
9923
9924 /**
9925 * Check if showing a anchor.
9926 *
9927 * @return {boolean} anchor is visible
9928 */
9929 OO.ui.PopupWidget.prototype.hasAnchor = function () {
9930 return this.anchor;
9931 };
9932
9933 /**
9934 * @inheritdoc
9935 */
9936 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
9937 show = show === undefined ? !this.isVisible() : !!show;
9938
9939 var change = show !== this.isVisible();
9940
9941 // Parent method
9942 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
9943
9944 if ( change ) {
9945 if ( show ) {
9946 this.toggleClipping( true );
9947 if ( this.autoClose ) {
9948 this.bindMouseDownListener();
9949 }
9950 this.updateDimensions();
9951 } else {
9952 this.toggleClipping( false );
9953 if ( this.autoClose ) {
9954 this.unbindMouseDownListener();
9955 }
9956 }
9957 }
9958
9959 return this;
9960 };
9961
9962 /**
9963 * Set the size of the popup.
9964 *
9965 * Changing the size may also change the popup's position depending on the alignment.
9966 *
9967 * @param {number} width Width
9968 * @param {number} height Height
9969 * @param {boolean} [transition=false] Use a smooth transition
9970 * @chainable
9971 */
9972 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
9973 this.width = width;
9974 this.height = height !== undefined ? height : null;
9975 if ( this.isVisible() ) {
9976 this.updateDimensions( transition );
9977 }
9978 };
9979
9980 /**
9981 * Update the size and position.
9982 *
9983 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
9984 * be called automatically.
9985 *
9986 * @param {boolean} [transition=false] Use a smooth transition
9987 * @chainable
9988 */
9989 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
9990 var widget = this,
9991 padding = 10,
9992 originOffset = Math.round( this.$element.offset().left ),
9993 containerLeft = Math.round( this.$container.offset().left ),
9994 containerWidth = this.$container.innerWidth(),
9995 containerRight = containerLeft + containerWidth,
9996 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[this.align],
9997 anchorWidth = this.$anchor.width(),
9998 popupLeft = popupOffset - padding,
9999 popupRight = popupOffset + padding + this.width + padding,
10000 overlapLeft = ( originOffset + popupLeft ) - containerLeft,
10001 overlapRight = containerRight - ( originOffset + popupRight );
10002
10003 // Prevent transition from being interrupted
10004 clearTimeout( this.transitionTimeout );
10005 if ( transition ) {
10006 // Enable transition
10007 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
10008 }
10009
10010 if ( overlapRight < 0 ) {
10011 popupOffset += overlapRight;
10012 } else if ( overlapLeft < 0 ) {
10013 popupOffset -= overlapLeft;
10014 }
10015
10016 // Adjust offset to avoid anchor being rendered too close to the edge
10017 if ( this.align === 'right' ) {
10018 popupOffset += anchorWidth;
10019 } else if ( this.align === 'left' ) {
10020 popupOffset -= anchorWidth;
10021 }
10022
10023 // Position body relative to anchor and resize
10024 this.$popup.css( {
10025 left: popupOffset,
10026 width: this.width,
10027 height: this.height !== null ? this.height : 'auto'
10028 } );
10029
10030 if ( transition ) {
10031 // Prevent transitioning after transition is complete
10032 this.transitionTimeout = setTimeout( function () {
10033 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
10034 }, 200 );
10035 } else {
10036 // Prevent transitioning immediately
10037 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
10038 }
10039
10040 return this;
10041 };
10042
10043 /**
10044 * Search widget.
10045 *
10046 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
10047 * Results are cleared and populated each time the query is changed.
10048 *
10049 * @class
10050 * @extends OO.ui.Widget
10051 *
10052 * @constructor
10053 * @param {Object} [config] Configuration options
10054 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
10055 * @cfg {string} [value] Initial query value
10056 */
10057 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
10058 // Configuration intialization
10059 config = config || {};
10060
10061 // Parent constructor
10062 OO.ui.SearchWidget.super.call( this, config );
10063
10064 // Properties
10065 this.query = new OO.ui.TextInputWidget( {
10066 $: this.$,
10067 icon: 'search',
10068 placeholder: config.placeholder,
10069 value: config.value
10070 } );
10071 this.results = new OO.ui.SelectWidget( { $: this.$ } );
10072 this.$query = this.$( '<div>' );
10073 this.$results = this.$( '<div>' );
10074
10075 // Events
10076 this.query.connect( this, {
10077 change: 'onQueryChange',
10078 enter: 'onQueryEnter'
10079 } );
10080 this.results.connect( this, {
10081 highlight: 'onResultsHighlight',
10082 select: 'onResultsSelect'
10083 } );
10084 this.query.$input.on( 'keydown', OO.ui.bind( this.onQueryKeydown, this ) );
10085
10086 // Initialization
10087 this.$query
10088 .addClass( 'oo-ui-searchWidget-query' )
10089 .append( this.query.$element );
10090 this.$results
10091 .addClass( 'oo-ui-searchWidget-results' )
10092 .append( this.results.$element );
10093 this.$element
10094 .addClass( 'oo-ui-searchWidget' )
10095 .append( this.$results, this.$query );
10096 };
10097
10098 /* Setup */
10099
10100 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
10101
10102 /* Events */
10103
10104 /**
10105 * @event highlight
10106 * @param {Object|null} item Item data or null if no item is highlighted
10107 */
10108
10109 /**
10110 * @event select
10111 * @param {Object|null} item Item data or null if no item is selected
10112 */
10113
10114 /* Methods */
10115
10116 /**
10117 * Handle query key down events.
10118 *
10119 * @param {jQuery.Event} e Key down event
10120 */
10121 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
10122 var highlightedItem, nextItem,
10123 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
10124
10125 if ( dir ) {
10126 highlightedItem = this.results.getHighlightedItem();
10127 if ( !highlightedItem ) {
10128 highlightedItem = this.results.getSelectedItem();
10129 }
10130 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
10131 this.results.highlightItem( nextItem );
10132 nextItem.scrollElementIntoView();
10133 }
10134 };
10135
10136 /**
10137 * Handle select widget select events.
10138 *
10139 * Clears existing results. Subclasses should repopulate items according to new query.
10140 *
10141 * @param {string} value New value
10142 */
10143 OO.ui.SearchWidget.prototype.onQueryChange = function () {
10144 // Reset
10145 this.results.clearItems();
10146 };
10147
10148 /**
10149 * Handle select widget enter key events.
10150 *
10151 * Selects highlighted item.
10152 *
10153 * @param {string} value New value
10154 */
10155 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
10156 // Reset
10157 this.results.selectItem( this.results.getHighlightedItem() );
10158 };
10159
10160 /**
10161 * Handle select widget highlight events.
10162 *
10163 * @param {OO.ui.OptionWidget} item Highlighted item
10164 * @fires highlight
10165 */
10166 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
10167 this.emit( 'highlight', item ? item.getData() : null );
10168 };
10169
10170 /**
10171 * Handle select widget select events.
10172 *
10173 * @param {OO.ui.OptionWidget} item Selected item
10174 * @fires select
10175 */
10176 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
10177 this.emit( 'select', item ? item.getData() : null );
10178 };
10179
10180 /**
10181 * Get the query input.
10182 *
10183 * @return {OO.ui.TextInputWidget} Query input
10184 */
10185 OO.ui.SearchWidget.prototype.getQuery = function () {
10186 return this.query;
10187 };
10188
10189 /**
10190 * Get the results list.
10191 *
10192 * @return {OO.ui.SelectWidget} Select list
10193 */
10194 OO.ui.SearchWidget.prototype.getResults = function () {
10195 return this.results;
10196 };
10197
10198 /**
10199 * Generic selection of options.
10200 *
10201 * Items can contain any rendering, and are uniquely identified by a has of thier data. Any widget
10202 * that provides options, from which the user must choose one, should be built on this class.
10203 *
10204 * Use together with OO.ui.OptionWidget.
10205 *
10206 * @class
10207 * @extends OO.ui.Widget
10208 * @mixins OO.ui.GroupElement
10209 *
10210 * @constructor
10211 * @param {Object} [config] Configuration options
10212 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
10213 */
10214 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
10215 // Config intialization
10216 config = config || {};
10217
10218 // Parent constructor
10219 OO.ui.SelectWidget.super.call( this, config );
10220
10221 // Mixin constructors
10222 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
10223
10224 // Properties
10225 this.pressed = false;
10226 this.selecting = null;
10227 this.hashes = {};
10228 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
10229 this.onMouseMoveHandler = OO.ui.bind( this.onMouseMove, this );
10230
10231 // Events
10232 this.$element.on( {
10233 mousedown: OO.ui.bind( this.onMouseDown, this ),
10234 mouseover: OO.ui.bind( this.onMouseOver, this ),
10235 mouseleave: OO.ui.bind( this.onMouseLeave, this )
10236 } );
10237
10238 // Initialization
10239 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
10240 if ( $.isArray( config.items ) ) {
10241 this.addItems( config.items );
10242 }
10243 };
10244
10245 /* Setup */
10246
10247 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
10248
10249 // Need to mixin base class as well
10250 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
10251 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
10252
10253 /* Events */
10254
10255 /**
10256 * @event highlight
10257 * @param {OO.ui.OptionWidget|null} item Highlighted item
10258 */
10259
10260 /**
10261 * @event press
10262 * @param {OO.ui.OptionWidget|null} item Pressed item
10263 */
10264
10265 /**
10266 * @event select
10267 * @param {OO.ui.OptionWidget|null} item Selected item
10268 */
10269
10270 /**
10271 * @event choose
10272 * @param {OO.ui.OptionWidget|null} item Chosen item
10273 */
10274
10275 /**
10276 * @event add
10277 * @param {OO.ui.OptionWidget[]} items Added items
10278 * @param {number} index Index items were added at
10279 */
10280
10281 /**
10282 * @event remove
10283 * @param {OO.ui.OptionWidget[]} items Removed items
10284 */
10285
10286 /* Methods */
10287
10288 /**
10289 * Handle mouse down events.
10290 *
10291 * @private
10292 * @param {jQuery.Event} e Mouse down event
10293 */
10294 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
10295 var item;
10296
10297 if ( !this.isDisabled() && e.which === 1 ) {
10298 this.togglePressed( true );
10299 item = this.getTargetItem( e );
10300 if ( item && item.isSelectable() ) {
10301 this.pressItem( item );
10302 this.selecting = item;
10303 this.getElementDocument().addEventListener(
10304 'mouseup',
10305 this.onMouseUpHandler,
10306 true
10307 );
10308 this.getElementDocument().addEventListener(
10309 'mousemove',
10310 this.onMouseMoveHandler,
10311 true
10312 );
10313 }
10314 }
10315 return false;
10316 };
10317
10318 /**
10319 * Handle mouse up events.
10320 *
10321 * @private
10322 * @param {jQuery.Event} e Mouse up event
10323 */
10324 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
10325 var item;
10326
10327 this.togglePressed( false );
10328 if ( !this.selecting ) {
10329 item = this.getTargetItem( e );
10330 if ( item && item.isSelectable() ) {
10331 this.selecting = item;
10332 }
10333 }
10334 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
10335 this.pressItem( null );
10336 this.chooseItem( this.selecting );
10337 this.selecting = null;
10338 }
10339
10340 this.getElementDocument().removeEventListener(
10341 'mouseup',
10342 this.onMouseUpHandler,
10343 true
10344 );
10345 this.getElementDocument().removeEventListener(
10346 'mousemove',
10347 this.onMouseMoveHandler,
10348 true
10349 );
10350
10351 return false;
10352 };
10353
10354 /**
10355 * Handle mouse move events.
10356 *
10357 * @private
10358 * @param {jQuery.Event} e Mouse move event
10359 */
10360 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
10361 var item;
10362
10363 if ( !this.isDisabled() && this.pressed ) {
10364 item = this.getTargetItem( e );
10365 if ( item && item !== this.selecting && item.isSelectable() ) {
10366 this.pressItem( item );
10367 this.selecting = item;
10368 }
10369 }
10370 return false;
10371 };
10372
10373 /**
10374 * Handle mouse over events.
10375 *
10376 * @private
10377 * @param {jQuery.Event} e Mouse over event
10378 */
10379 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
10380 var item;
10381
10382 if ( !this.isDisabled() ) {
10383 item = this.getTargetItem( e );
10384 this.highlightItem( item && item.isHighlightable() ? item : null );
10385 }
10386 return false;
10387 };
10388
10389 /**
10390 * Handle mouse leave events.
10391 *
10392 * @private
10393 * @param {jQuery.Event} e Mouse over event
10394 */
10395 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
10396 if ( !this.isDisabled() ) {
10397 this.highlightItem( null );
10398 }
10399 return false;
10400 };
10401
10402 /**
10403 * Get the closest item to a jQuery.Event.
10404 *
10405 * @private
10406 * @param {jQuery.Event} e
10407 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
10408 */
10409 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
10410 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
10411 if ( $item.length ) {
10412 return $item.data( 'oo-ui-optionWidget' );
10413 }
10414 return null;
10415 };
10416
10417 /**
10418 * Get selected item.
10419 *
10420 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
10421 */
10422 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
10423 var i, len;
10424
10425 for ( i = 0, len = this.items.length; i < len; i++ ) {
10426 if ( this.items[i].isSelected() ) {
10427 return this.items[i];
10428 }
10429 }
10430 return null;
10431 };
10432
10433 /**
10434 * Get highlighted item.
10435 *
10436 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
10437 */
10438 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
10439 var i, len;
10440
10441 for ( i = 0, len = this.items.length; i < len; i++ ) {
10442 if ( this.items[i].isHighlighted() ) {
10443 return this.items[i];
10444 }
10445 }
10446 return null;
10447 };
10448
10449 /**
10450 * Get an existing item with equivilant data.
10451 *
10452 * @param {Object} data Item data to search for
10453 * @return {OO.ui.OptionWidget|null} Item with equivilent value, `null` if none exists
10454 */
10455 OO.ui.SelectWidget.prototype.getItemFromData = function ( data ) {
10456 var hash = OO.getHash( data );
10457
10458 if ( hash in this.hashes ) {
10459 return this.hashes[hash];
10460 }
10461
10462 return null;
10463 };
10464
10465 /**
10466 * Toggle pressed state.
10467 *
10468 * @param {boolean} pressed An option is being pressed
10469 */
10470 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
10471 if ( pressed === undefined ) {
10472 pressed = !this.pressed;
10473 }
10474 if ( pressed !== this.pressed ) {
10475 this.$element
10476 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
10477 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
10478 this.pressed = pressed;
10479 }
10480 };
10481
10482 /**
10483 * Highlight an item.
10484 *
10485 * Highlighting is mutually exclusive.
10486 *
10487 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
10488 * @fires highlight
10489 * @chainable
10490 */
10491 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
10492 var i, len, highlighted,
10493 changed = false;
10494
10495 for ( i = 0, len = this.items.length; i < len; i++ ) {
10496 highlighted = this.items[i] === item;
10497 if ( this.items[i].isHighlighted() !== highlighted ) {
10498 this.items[i].setHighlighted( highlighted );
10499 changed = true;
10500 }
10501 }
10502 if ( changed ) {
10503 this.emit( 'highlight', item );
10504 }
10505
10506 return this;
10507 };
10508
10509 /**
10510 * Select an item.
10511 *
10512 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
10513 * @fires select
10514 * @chainable
10515 */
10516 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
10517 var i, len, selected,
10518 changed = false;
10519
10520 for ( i = 0, len = this.items.length; i < len; i++ ) {
10521 selected = this.items[i] === item;
10522 if ( this.items[i].isSelected() !== selected ) {
10523 this.items[i].setSelected( selected );
10524 changed = true;
10525 }
10526 }
10527 if ( changed ) {
10528 this.emit( 'select', item );
10529 }
10530
10531 return this;
10532 };
10533
10534 /**
10535 * Press an item.
10536 *
10537 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
10538 * @fires press
10539 * @chainable
10540 */
10541 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
10542 var i, len, pressed,
10543 changed = false;
10544
10545 for ( i = 0, len = this.items.length; i < len; i++ ) {
10546 pressed = this.items[i] === item;
10547 if ( this.items[i].isPressed() !== pressed ) {
10548 this.items[i].setPressed( pressed );
10549 changed = true;
10550 }
10551 }
10552 if ( changed ) {
10553 this.emit( 'press', item );
10554 }
10555
10556 return this;
10557 };
10558
10559 /**
10560 * Choose an item.
10561 *
10562 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
10563 * an item is selected using the keyboard or mouse.
10564 *
10565 * @param {OO.ui.OptionWidget} item Item to choose
10566 * @fires choose
10567 * @chainable
10568 */
10569 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
10570 this.selectItem( item );
10571 this.emit( 'choose', item );
10572
10573 return this;
10574 };
10575
10576 /**
10577 * Get an item relative to another one.
10578 *
10579 * @param {OO.ui.OptionWidget} item Item to start at
10580 * @param {number} direction Direction to move in
10581 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
10582 */
10583 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
10584 var inc = direction > 0 ? 1 : -1,
10585 len = this.items.length,
10586 index = item instanceof OO.ui.OptionWidget ?
10587 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
10588 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
10589 i = inc > 0 ?
10590 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
10591 Math.max( index, -1 ) :
10592 // Default to n-1 instead of -1, if nothing is selected let's start at the end
10593 Math.min( index, len );
10594
10595 while ( true ) {
10596 i = ( i + inc + len ) % len;
10597 item = this.items[i];
10598 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
10599 return item;
10600 }
10601 // Stop iterating when we've looped all the way around
10602 if ( i === stopAt ) {
10603 break;
10604 }
10605 }
10606 return null;
10607 };
10608
10609 /**
10610 * Get the next selectable item.
10611 *
10612 * @return {OO.ui.OptionWidget|null} Item, `null` if ther aren't any selectable items
10613 */
10614 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
10615 var i, len, item;
10616
10617 for ( i = 0, len = this.items.length; i < len; i++ ) {
10618 item = this.items[i];
10619 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
10620 return item;
10621 }
10622 }
10623
10624 return null;
10625 };
10626
10627 /**
10628 * Add items.
10629 *
10630 * When items are added with the same values as existing items, the existing items will be
10631 * automatically removed before the new items are added.
10632 *
10633 * @param {OO.ui.OptionWidget[]} items Items to add
10634 * @param {number} [index] Index to insert items after
10635 * @fires add
10636 * @chainable
10637 */
10638 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
10639 var i, len, item, hash,
10640 remove = [];
10641
10642 for ( i = 0, len = items.length; i < len; i++ ) {
10643 item = items[i];
10644 hash = OO.getHash( item.getData() );
10645 if ( hash in this.hashes ) {
10646 // Remove item with same value
10647 remove.push( this.hashes[hash] );
10648 }
10649 this.hashes[hash] = item;
10650 }
10651 if ( remove.length ) {
10652 this.removeItems( remove );
10653 }
10654
10655 // Mixin method
10656 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
10657
10658 // Always provide an index, even if it was omitted
10659 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
10660
10661 return this;
10662 };
10663
10664 /**
10665 * Remove items.
10666 *
10667 * Items will be detached, not removed, so they can be used later.
10668 *
10669 * @param {OO.ui.OptionWidget[]} items Items to remove
10670 * @fires remove
10671 * @chainable
10672 */
10673 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
10674 var i, len, item, hash;
10675
10676 for ( i = 0, len = items.length; i < len; i++ ) {
10677 item = items[i];
10678 hash = OO.getHash( item.getData() );
10679 if ( hash in this.hashes ) {
10680 // Remove existing item
10681 delete this.hashes[hash];
10682 }
10683 if ( item.isSelected() ) {
10684 this.selectItem( null );
10685 }
10686 }
10687
10688 // Mixin method
10689 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
10690
10691 this.emit( 'remove', items );
10692
10693 return this;
10694 };
10695
10696 /**
10697 * Clear all items.
10698 *
10699 * Items will be detached, not removed, so they can be used later.
10700 *
10701 * @fires remove
10702 * @chainable
10703 */
10704 OO.ui.SelectWidget.prototype.clearItems = function () {
10705 var items = this.items.slice();
10706
10707 // Clear all items
10708 this.hashes = {};
10709 // Mixin method
10710 OO.ui.GroupWidget.prototype.clearItems.call( this );
10711 this.selectItem( null );
10712
10713 this.emit( 'remove', items );
10714
10715 return this;
10716 };
10717
10718 /**
10719 * Select widget containing button options.
10720 *
10721 * Use together with OO.ui.ButtonOptionWidget.
10722 *
10723 * @class
10724 * @extends OO.ui.SelectWidget
10725 *
10726 * @constructor
10727 * @param {Object} [config] Configuration options
10728 */
10729 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
10730 // Parent constructor
10731 OO.ui.ButtonSelectWidget.super.call( this, config );
10732
10733 // Initialization
10734 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
10735 };
10736
10737 /* Setup */
10738
10739 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
10740
10741 /**
10742 * Overlaid menu of options.
10743 *
10744 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
10745 * the menu.
10746 *
10747 * Use together with OO.ui.MenuItemWidget.
10748 *
10749 * @class
10750 * @extends OO.ui.SelectWidget
10751 * @mixins OO.ui.ClippableElement
10752 *
10753 * @constructor
10754 * @param {Object} [config] Configuration options
10755 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
10756 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
10757 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
10758 */
10759 OO.ui.MenuWidget = function OoUiMenuWidget( config ) {
10760 // Config intialization
10761 config = config || {};
10762
10763 // Parent constructor
10764 OO.ui.MenuWidget.super.call( this, config );
10765
10766 // Mixin constructors
10767 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
10768
10769 // Properties
10770 this.flashing = false;
10771 this.visible = false;
10772 this.newItems = null;
10773 this.autoHide = config.autoHide === undefined || !!config.autoHide;
10774 this.$input = config.input ? config.input.$input : null;
10775 this.$widget = config.widget ? config.widget.$element : null;
10776 this.$previousFocus = null;
10777 this.isolated = !config.input;
10778 this.onKeyDownHandler = OO.ui.bind( this.onKeyDown, this );
10779 this.onDocumentMouseDownHandler = OO.ui.bind( this.onDocumentMouseDown, this );
10780
10781 // Initialization
10782 this.$element
10783 .hide()
10784 .attr( 'role', 'menu' )
10785 .addClass( 'oo-ui-menuWidget' );
10786 };
10787
10788 /* Setup */
10789
10790 OO.inheritClass( OO.ui.MenuWidget, OO.ui.SelectWidget );
10791 OO.mixinClass( OO.ui.MenuWidget, OO.ui.ClippableElement );
10792
10793 /* Methods */
10794
10795 /**
10796 * Handles document mouse down events.
10797 *
10798 * @param {jQuery.Event} e Key down event
10799 */
10800 OO.ui.MenuWidget.prototype.onDocumentMouseDown = function ( e ) {
10801 if ( !$.contains( this.$element[0], e.target ) && ( !this.$widget || !$.contains( this.$widget[0], e.target ) ) ) {
10802 this.toggle( false );
10803 }
10804 };
10805
10806 /**
10807 * Handles key down events.
10808 *
10809 * @param {jQuery.Event} e Key down event
10810 */
10811 OO.ui.MenuWidget.prototype.onKeyDown = function ( e ) {
10812 var nextItem,
10813 handled = false,
10814 highlightItem = this.getHighlightedItem();
10815
10816 if ( !this.isDisabled() && this.isVisible() ) {
10817 if ( !highlightItem ) {
10818 highlightItem = this.getSelectedItem();
10819 }
10820 switch ( e.keyCode ) {
10821 case OO.ui.Keys.ENTER:
10822 this.chooseItem( highlightItem );
10823 handled = true;
10824 break;
10825 case OO.ui.Keys.UP:
10826 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
10827 handled = true;
10828 break;
10829 case OO.ui.Keys.DOWN:
10830 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
10831 handled = true;
10832 break;
10833 case OO.ui.Keys.ESCAPE:
10834 if ( highlightItem ) {
10835 highlightItem.setHighlighted( false );
10836 }
10837 this.toggle( false );
10838 handled = true;
10839 break;
10840 }
10841
10842 if ( nextItem ) {
10843 this.highlightItem( nextItem );
10844 nextItem.scrollElementIntoView();
10845 }
10846
10847 if ( handled ) {
10848 e.preventDefault();
10849 e.stopPropagation();
10850 return false;
10851 }
10852 }
10853 };
10854
10855 /**
10856 * Bind key down listener.
10857 */
10858 OO.ui.MenuWidget.prototype.bindKeyDownListener = function () {
10859 if ( this.$input ) {
10860 this.$input.on( 'keydown', this.onKeyDownHandler );
10861 } else {
10862 // Capture menu navigation keys
10863 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
10864 }
10865 };
10866
10867 /**
10868 * Unbind key down listener.
10869 */
10870 OO.ui.MenuWidget.prototype.unbindKeyDownListener = function () {
10871 if ( this.$input ) {
10872 this.$input.off( 'keydown' );
10873 } else {
10874 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
10875 }
10876 };
10877
10878 /**
10879 * Choose an item.
10880 *
10881 * This will close the menu when done, unlike selectItem which only changes selection.
10882 *
10883 * @param {OO.ui.OptionWidget} item Item to choose
10884 * @chainable
10885 */
10886 OO.ui.MenuWidget.prototype.chooseItem = function ( item ) {
10887 var widget = this;
10888
10889 // Parent method
10890 OO.ui.MenuWidget.super.prototype.chooseItem.call( this, item );
10891
10892 if ( item && !this.flashing ) {
10893 this.flashing = true;
10894 item.flash().done( function () {
10895 widget.toggle( false );
10896 widget.flashing = false;
10897 } );
10898 } else {
10899 this.toggle( false );
10900 }
10901
10902 return this;
10903 };
10904
10905 /**
10906 * @inheritdoc
10907 */
10908 OO.ui.MenuWidget.prototype.addItems = function ( items, index ) {
10909 var i, len, item;
10910
10911 // Parent method
10912 OO.ui.MenuWidget.super.prototype.addItems.call( this, items, index );
10913
10914 // Auto-initialize
10915 if ( !this.newItems ) {
10916 this.newItems = [];
10917 }
10918
10919 for ( i = 0, len = items.length; i < len; i++ ) {
10920 item = items[i];
10921 if ( this.isVisible() ) {
10922 // Defer fitting label until item has been attached
10923 item.fitLabel();
10924 } else {
10925 this.newItems.push( item );
10926 }
10927 }
10928
10929 // Reevaluate clipping
10930 this.clip();
10931
10932 return this;
10933 };
10934
10935 /**
10936 * @inheritdoc
10937 */
10938 OO.ui.MenuWidget.prototype.removeItems = function ( items ) {
10939 // Parent method
10940 OO.ui.MenuWidget.super.prototype.removeItems.call( this, items );
10941
10942 // Reevaluate clipping
10943 this.clip();
10944
10945 return this;
10946 };
10947
10948 /**
10949 * @inheritdoc
10950 */
10951 OO.ui.MenuWidget.prototype.clearItems = function () {
10952 // Parent method
10953 OO.ui.MenuWidget.super.prototype.clearItems.call( this );
10954
10955 // Reevaluate clipping
10956 this.clip();
10957
10958 return this;
10959 };
10960
10961 /**
10962 * @inheritdoc
10963 */
10964 OO.ui.MenuWidget.prototype.toggle = function ( visible ) {
10965 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
10966
10967 var i, len,
10968 change = visible !== this.isVisible();
10969
10970 // Parent method
10971 OO.ui.MenuWidget.super.prototype.toggle.call( this, visible );
10972
10973 if ( change ) {
10974 if ( visible ) {
10975 this.bindKeyDownListener();
10976
10977 // Change focus to enable keyboard navigation
10978 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
10979 this.$previousFocus = this.$( ':focus' );
10980 this.$input[0].focus();
10981 }
10982 if ( this.newItems && this.newItems.length ) {
10983 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
10984 this.newItems[i].fitLabel();
10985 }
10986 this.newItems = null;
10987 }
10988 this.toggleClipping( true );
10989
10990 // Auto-hide
10991 if ( this.autoHide ) {
10992 this.getElementDocument().addEventListener(
10993 'mousedown', this.onDocumentMouseDownHandler, true
10994 );
10995 }
10996 } else {
10997 this.unbindKeyDownListener();
10998 if ( this.isolated && this.$previousFocus ) {
10999 this.$previousFocus[0].focus();
11000 this.$previousFocus = null;
11001 }
11002 this.getElementDocument().removeEventListener(
11003 'mousedown', this.onDocumentMouseDownHandler, true
11004 );
11005 this.toggleClipping( false );
11006 }
11007 }
11008
11009 return this;
11010 };
11011
11012 /**
11013 * Menu for a text input widget.
11014 *
11015 * This menu is specially designed to be positioned beneath the text input widget. Even if the input
11016 * is in a different frame, the menu's position is automatically calulated and maintained when the
11017 * menu is toggled or the window is resized.
11018 *
11019 * @class
11020 * @extends OO.ui.MenuWidget
11021 *
11022 * @constructor
11023 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
11024 * @param {Object} [config] Configuration options
11025 * @cfg {jQuery} [$container=input.$element] Element to render menu under
11026 */
11027 OO.ui.TextInputMenuWidget = function OoUiTextInputMenuWidget( input, config ) {
11028 // Parent constructor
11029 OO.ui.TextInputMenuWidget.super.call( this, config );
11030
11031 // Properties
11032 this.input = input;
11033 this.$container = config.$container || this.input.$element;
11034 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
11035
11036 // Initialization
11037 this.$element.addClass( 'oo-ui-textInputMenuWidget' );
11038 };
11039
11040 /* Setup */
11041
11042 OO.inheritClass( OO.ui.TextInputMenuWidget, OO.ui.MenuWidget );
11043
11044 /* Methods */
11045
11046 /**
11047 * Handle window resize event.
11048 *
11049 * @param {jQuery.Event} e Window resize event
11050 */
11051 OO.ui.TextInputMenuWidget.prototype.onWindowResize = function () {
11052 this.position();
11053 };
11054
11055 /**
11056 * @inheritdoc
11057 */
11058 OO.ui.TextInputMenuWidget.prototype.toggle = function ( visible ) {
11059 visible = !!visible;
11060
11061 var change = visible !== this.isVisible();
11062
11063 // Parent method
11064 OO.ui.TextInputMenuWidget.super.prototype.toggle.call( this, visible );
11065
11066 if ( change ) {
11067 if ( this.isVisible() ) {
11068 this.position();
11069 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
11070 } else {
11071 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
11072 }
11073 }
11074 return this;
11075 };
11076
11077 /**
11078 * Position the menu.
11079 *
11080 * @chainable
11081 */
11082 OO.ui.TextInputMenuWidget.prototype.position = function () {
11083 var frameOffset,
11084 $container = this.$container,
11085 dimensions = $container.offset();
11086
11087 // Position under input
11088 dimensions.top += $container.height();
11089
11090 // Compensate for frame position if in a differnt frame
11091 if ( this.input.$.$iframe && this.input.$.context !== this.$element[0].ownerDocument ) {
11092 frameOffset = OO.ui.Element.getRelativePosition(
11093 this.input.$.$iframe, this.$element.offsetParent()
11094 );
11095 dimensions.left += frameOffset.left;
11096 dimensions.top += frameOffset.top;
11097 } else {
11098 // Fix for RTL (for some reason, no need to fix if the frameoffset is set)
11099 if ( this.$element.css( 'direction' ) === 'rtl' ) {
11100 dimensions.right = this.$element.parent().position().left -
11101 $container.width() - dimensions.left;
11102 // Erase the value for 'left':
11103 delete dimensions.left;
11104 }
11105 }
11106 this.$element.css( dimensions );
11107 this.setIdealSize( $container.width() );
11108
11109 return this;
11110 };
11111
11112 /**
11113 * Structured list of items.
11114 *
11115 * Use with OO.ui.OutlineItemWidget.
11116 *
11117 * @class
11118 * @extends OO.ui.SelectWidget
11119 *
11120 * @constructor
11121 * @param {Object} [config] Configuration options
11122 */
11123 OO.ui.OutlineWidget = function OoUiOutlineWidget( config ) {
11124 // Config intialization
11125 config = config || {};
11126
11127 // Parent constructor
11128 OO.ui.OutlineWidget.super.call( this, config );
11129
11130 // Initialization
11131 this.$element.addClass( 'oo-ui-outlineWidget' );
11132 };
11133
11134 /* Setup */
11135
11136 OO.inheritClass( OO.ui.OutlineWidget, OO.ui.SelectWidget );
11137
11138 /**
11139 * Switch that slides on and off.
11140 *
11141 * @class
11142 * @extends OO.ui.Widget
11143 * @mixins OO.ui.ToggleWidget
11144 *
11145 * @constructor
11146 * @param {Object} [config] Configuration options
11147 * @cfg {boolean} [value=false] Initial value
11148 */
11149 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
11150 // Parent constructor
11151 OO.ui.ToggleSwitchWidget.super.call( this, config );
11152
11153 // Mixin constructors
11154 OO.ui.ToggleWidget.call( this, config );
11155
11156 // Properties
11157 this.dragging = false;
11158 this.dragStart = null;
11159 this.sliding = false;
11160 this.$glow = this.$( '<span>' );
11161 this.$grip = this.$( '<span>' );
11162
11163 // Events
11164 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
11165
11166 // Initialization
11167 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
11168 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
11169 this.$element
11170 .addClass( 'oo-ui-toggleSwitchWidget' )
11171 .append( this.$glow, this.$grip );
11172 };
11173
11174 /* Setup */
11175
11176 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
11177 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
11178
11179 /* Methods */
11180
11181 /**
11182 * Handle mouse down events.
11183 *
11184 * @param {jQuery.Event} e Mouse down event
11185 */
11186 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
11187 if ( !this.isDisabled() && e.which === 1 ) {
11188 this.setValue( !this.value );
11189 }
11190 };
11191
11192 }( OO ) );