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