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