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