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