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