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