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