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