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