Merge "Don't double escape in Linker::formatLinksInComment"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.6.5
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-02-02T03:28:54Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Get the user's language and any fallback languages.
49 *
50 * These language codes are used to localize user interface elements in the user's language.
51 *
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
54 *
55 * @return {string[]} Language codes, in descending order of priority
56 */
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
59 };
60
61 /**
62 * Get a value in an object keyed by language code.
63 *
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
68 */
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
71
72 // Requested language
73 if ( obj[ lang ] ) {
74 return obj[ lang ];
75 }
76 // Known user language
77 langs = OO.ui.getUserLanguages();
78 for ( i = 0, len = langs.length; i < len; i++ ) {
79 lang = langs[ i ];
80 if ( obj[ lang ] ) {
81 return obj[ lang ];
82 }
83 }
84 // Fallback language
85 if ( obj[ fallback ] ) {
86 return obj[ fallback ];
87 }
88 // First existing language
89 for ( lang in obj ) {
90 return obj[ lang ];
91 }
92
93 return undefined;
94 };
95
96 /**
97 * Check if a node is contained within another node
98 *
99 * Similar to jQuery#contains except a list of containers can be supplied
100 * and a boolean argument allows you to include the container in the match list
101 *
102 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
103 * @param {HTMLElement} contained Node to find
104 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
105 * @return {boolean} The node is in the list of target nodes
106 */
107 OO.ui.contains = function ( containers, contained, matchContainers ) {
108 var i;
109 if ( !Array.isArray( containers ) ) {
110 containers = [ containers ];
111 }
112 for ( i = containers.length - 1; i >= 0; i-- ) {
113 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
114 return true;
115 }
116 }
117 return false;
118 };
119
120 ( function () {
121 /**
122 * Message store for the default implementation of OO.ui.msg
123 *
124 * Environments that provide a localization system should not use this, but should override
125 * OO.ui.msg altogether.
126 *
127 * @private
128 */
129 var messages = {
130 // Tool tip for a button that moves items in a list down one place
131 'ooui-outline-control-move-down': 'Move item down',
132 // Tool tip for a button that moves items in a list up one place
133 'ooui-outline-control-move-up': 'Move item up',
134 // Tool tip for a button that removes items from a list
135 'ooui-outline-control-remove': 'Remove item',
136 // Label for the toolbar group that contains a list of all other available tools
137 'ooui-toolbar-more': 'More',
138 // Label for the fake tool that expands the full list of tools in a toolbar group
139 'ooui-toolgroup-expand': 'More',
140 // Label for the fake tool that collapses the full list of tools in a toolbar group
141 'ooui-toolgroup-collapse': 'Fewer',
142 // Default label for the accept button of a confirmation dialog
143 'ooui-dialog-message-accept': 'OK',
144 // Default label for the reject button of a confirmation dialog
145 'ooui-dialog-message-reject': 'Cancel',
146 // Title for process dialog error description
147 'ooui-dialog-process-error': 'Something went wrong',
148 // Label for process dialog dismiss error button, visible when describing errors
149 'ooui-dialog-process-dismiss': 'Dismiss',
150 // Label for process dialog retry action button, visible when describing only recoverable errors
151 'ooui-dialog-process-retry': 'Try again',
152 // Label for process dialog retry action button, visible when describing only warnings
153 'ooui-dialog-process-continue': 'Continue'
154 };
155
156 /**
157 * Get a localized message.
158 *
159 * In environments that provide a localization system, this function should be overridden to
160 * return the message translated in the user's language. The default implementation always returns
161 * English messages.
162 *
163 * After the message key, message parameters may optionally be passed. In the default implementation,
164 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
165 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
166 * they support unnamed, ordered message parameters.
167 *
168 * @abstract
169 * @param {string} key Message key
170 * @param {Mixed...} [params] Message parameters
171 * @return {string} Translated message with parameters substituted
172 */
173 OO.ui.msg = function ( key ) {
174 var message = messages[ key ],
175 params = Array.prototype.slice.call( arguments, 1 );
176 if ( typeof message === 'string' ) {
177 // Perform $1 substitution
178 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
179 var i = parseInt( n, 10 );
180 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
181 } );
182 } else {
183 // Return placeholder if message not found
184 message = '[' + key + ']';
185 }
186 return message;
187 };
188
189 /**
190 * Package a message and arguments for deferred resolution.
191 *
192 * Use this when you are statically specifying a message and the message may not yet be present.
193 *
194 * @param {string} key Message key
195 * @param {Mixed...} [params] Message parameters
196 * @return {Function} Function that returns the resolved message when executed
197 */
198 OO.ui.deferMsg = function () {
199 var args = arguments;
200 return function () {
201 return OO.ui.msg.apply( OO.ui, args );
202 };
203 };
204
205 /**
206 * Resolve a message.
207 *
208 * If the message is a function it will be executed, otherwise it will pass through directly.
209 *
210 * @param {Function|string} msg Deferred message, or message text
211 * @return {string} Resolved message
212 */
213 OO.ui.resolveMsg = function ( msg ) {
214 if ( $.isFunction( msg ) ) {
215 return msg();
216 }
217 return msg;
218 };
219
220 } )();
221
222 /**
223 * Element that can be marked as pending.
224 *
225 * @abstract
226 * @class
227 *
228 * @constructor
229 * @param {Object} [config] Configuration options
230 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
231 */
232 OO.ui.PendingElement = function OoUiPendingElement( config ) {
233 // Configuration initialization
234 config = config || {};
235
236 // Properties
237 this.pending = 0;
238 this.$pending = null;
239
240 // Initialisation
241 this.setPendingElement( config.$pending || this.$element );
242 };
243
244 /* Setup */
245
246 OO.initClass( OO.ui.PendingElement );
247
248 /* Methods */
249
250 /**
251 * Set the pending element (and clean up any existing one).
252 *
253 * @param {jQuery} $pending The element to set to pending.
254 */
255 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
256 if ( this.$pending ) {
257 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
258 }
259
260 this.$pending = $pending;
261 if ( this.pending > 0 ) {
262 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
263 }
264 };
265
266 /**
267 * Check if input is pending.
268 *
269 * @return {boolean}
270 */
271 OO.ui.PendingElement.prototype.isPending = function () {
272 return !!this.pending;
273 };
274
275 /**
276 * Increase the pending stack.
277 *
278 * @chainable
279 */
280 OO.ui.PendingElement.prototype.pushPending = function () {
281 if ( this.pending === 0 ) {
282 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
283 this.updateThemeClasses();
284 }
285 this.pending++;
286
287 return this;
288 };
289
290 /**
291 * Reduce the pending stack.
292 *
293 * Clamped at zero.
294 *
295 * @chainable
296 */
297 OO.ui.PendingElement.prototype.popPending = function () {
298 if ( this.pending === 1 ) {
299 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
300 this.updateThemeClasses();
301 }
302 this.pending = Math.max( 0, this.pending - 1 );
303
304 return this;
305 };
306
307 /**
308 * List of actions.
309 *
310 * @abstract
311 * @class
312 * @mixins OO.EventEmitter
313 *
314 * @constructor
315 * @param {Object} [config] Configuration options
316 */
317 OO.ui.ActionSet = function OoUiActionSet( config ) {
318 // Configuration initialization
319 config = config || {};
320
321 // Mixin constructors
322 OO.EventEmitter.call( this );
323
324 // Properties
325 this.list = [];
326 this.categories = {
327 actions: 'getAction',
328 flags: 'getFlags',
329 modes: 'getModes'
330 };
331 this.categorized = {};
332 this.special = {};
333 this.others = [];
334 this.organized = false;
335 this.changing = false;
336 this.changed = false;
337 };
338
339 /* Setup */
340
341 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
342
343 /* Static Properties */
344
345 /**
346 * Symbolic name of dialog.
347 *
348 * @abstract
349 * @static
350 * @inheritable
351 * @property {string}
352 */
353 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
354
355 /* Events */
356
357 /**
358 * @event click
359 * @param {OO.ui.ActionWidget} action Action that was clicked
360 */
361
362 /**
363 * @event resize
364 * @param {OO.ui.ActionWidget} action Action that was resized
365 */
366
367 /**
368 * @event add
369 * @param {OO.ui.ActionWidget[]} added Actions added
370 */
371
372 /**
373 * @event remove
374 * @param {OO.ui.ActionWidget[]} added Actions removed
375 */
376
377 /**
378 * @event change
379 */
380
381 /* Methods */
382
383 /**
384 * Handle action change events.
385 *
386 * @fires change
387 */
388 OO.ui.ActionSet.prototype.onActionChange = function () {
389 this.organized = false;
390 if ( this.changing ) {
391 this.changed = true;
392 } else {
393 this.emit( 'change' );
394 }
395 };
396
397 /**
398 * Check if a action is one of the special actions.
399 *
400 * @param {OO.ui.ActionWidget} action Action to check
401 * @return {boolean} Action is special
402 */
403 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
404 var flag;
405
406 for ( flag in this.special ) {
407 if ( action === this.special[ flag ] ) {
408 return true;
409 }
410 }
411
412 return false;
413 };
414
415 /**
416 * Get actions.
417 *
418 * @param {Object} [filters] Filters to use, omit to get all actions
419 * @param {string|string[]} [filters.actions] Actions that actions must have
420 * @param {string|string[]} [filters.flags] Flags that actions must have
421 * @param {string|string[]} [filters.modes] Modes that actions must have
422 * @param {boolean} [filters.visible] Actions must be visible
423 * @param {boolean} [filters.disabled] Actions must be disabled
424 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
425 */
426 OO.ui.ActionSet.prototype.get = function ( filters ) {
427 var i, len, list, category, actions, index, match, matches;
428
429 if ( filters ) {
430 this.organize();
431
432 // Collect category candidates
433 matches = [];
434 for ( category in this.categorized ) {
435 list = filters[ category ];
436 if ( list ) {
437 if ( !Array.isArray( list ) ) {
438 list = [ list ];
439 }
440 for ( i = 0, len = list.length; i < len; i++ ) {
441 actions = this.categorized[ category ][ list[ i ] ];
442 if ( Array.isArray( actions ) ) {
443 matches.push.apply( matches, actions );
444 }
445 }
446 }
447 }
448 // Remove by boolean filters
449 for ( i = 0, len = matches.length; i < len; i++ ) {
450 match = matches[ i ];
451 if (
452 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
453 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
454 ) {
455 matches.splice( i, 1 );
456 len--;
457 i--;
458 }
459 }
460 // Remove duplicates
461 for ( i = 0, len = matches.length; i < len; i++ ) {
462 match = matches[ i ];
463 index = matches.lastIndexOf( match );
464 while ( index !== i ) {
465 matches.splice( index, 1 );
466 len--;
467 index = matches.lastIndexOf( match );
468 }
469 }
470 return matches;
471 }
472 return this.list.slice();
473 };
474
475 /**
476 * Get special actions.
477 *
478 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
479 * Special flags can be configured by changing #static-specialFlags in a subclass.
480 *
481 * @return {OO.ui.ActionWidget|null} Safe action
482 */
483 OO.ui.ActionSet.prototype.getSpecial = function () {
484 this.organize();
485 return $.extend( {}, this.special );
486 };
487
488 /**
489 * Get other actions.
490 *
491 * Other actions include all non-special visible actions.
492 *
493 * @return {OO.ui.ActionWidget[]} Other actions
494 */
495 OO.ui.ActionSet.prototype.getOthers = function () {
496 this.organize();
497 return this.others.slice();
498 };
499
500 /**
501 * Toggle actions based on their modes.
502 *
503 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
504 * visibility; matching actions will be shown, non-matching actions will be hidden.
505 *
506 * @param {string} mode Mode actions must have
507 * @chainable
508 * @fires toggle
509 * @fires change
510 */
511 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
512 var i, len, action;
513
514 this.changing = true;
515 for ( i = 0, len = this.list.length; i < len; i++ ) {
516 action = this.list[ i ];
517 action.toggle( action.hasMode( mode ) );
518 }
519
520 this.organized = false;
521 this.changing = false;
522 this.emit( 'change' );
523
524 return this;
525 };
526
527 /**
528 * Change which actions are able to be performed.
529 *
530 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
531 *
532 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
533 * indicate actions are able to be performed
534 * @chainable
535 */
536 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
537 var i, len, action, item;
538
539 for ( i = 0, len = this.list.length; i < len; i++ ) {
540 item = this.list[ i ];
541 action = item.getAction();
542 if ( actions[ action ] !== undefined ) {
543 item.setDisabled( !actions[ action ] );
544 }
545 }
546
547 return this;
548 };
549
550 /**
551 * Executes a function once per action.
552 *
553 * When making changes to multiple actions, use this method instead of iterating over the actions
554 * manually to defer emitting a change event until after all actions have been changed.
555 *
556 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
557 * @param {Function} callback Callback to run for each action; callback is invoked with three
558 * arguments: the action, the action's index, the list of actions being iterated over
559 * @chainable
560 */
561 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
562 this.changed = false;
563 this.changing = true;
564 this.get( filter ).forEach( callback );
565 this.changing = false;
566 if ( this.changed ) {
567 this.emit( 'change' );
568 }
569
570 return this;
571 };
572
573 /**
574 * Add actions.
575 *
576 * @param {OO.ui.ActionWidget[]} actions Actions to add
577 * @chainable
578 * @fires add
579 * @fires change
580 */
581 OO.ui.ActionSet.prototype.add = function ( actions ) {
582 var i, len, action;
583
584 this.changing = true;
585 for ( i = 0, len = actions.length; i < len; i++ ) {
586 action = actions[ i ];
587 action.connect( this, {
588 click: [ 'emit', 'click', action ],
589 resize: [ 'emit', 'resize', action ],
590 toggle: [ 'onActionChange' ]
591 } );
592 this.list.push( action );
593 }
594 this.organized = false;
595 this.emit( 'add', actions );
596 this.changing = false;
597 this.emit( 'change' );
598
599 return this;
600 };
601
602 /**
603 * Remove actions.
604 *
605 * @param {OO.ui.ActionWidget[]} actions Actions to remove
606 * @chainable
607 * @fires remove
608 * @fires change
609 */
610 OO.ui.ActionSet.prototype.remove = function ( actions ) {
611 var i, len, index, action;
612
613 this.changing = true;
614 for ( i = 0, len = actions.length; i < len; i++ ) {
615 action = actions[ i ];
616 index = this.list.indexOf( action );
617 if ( index !== -1 ) {
618 action.disconnect( this );
619 this.list.splice( index, 1 );
620 }
621 }
622 this.organized = false;
623 this.emit( 'remove', actions );
624 this.changing = false;
625 this.emit( 'change' );
626
627 return this;
628 };
629
630 /**
631 * Remove all actions.
632 *
633 * @chainable
634 * @fires remove
635 * @fires change
636 */
637 OO.ui.ActionSet.prototype.clear = function () {
638 var i, len, action,
639 removed = this.list.slice();
640
641 this.changing = true;
642 for ( i = 0, len = this.list.length; i < len; i++ ) {
643 action = this.list[ i ];
644 action.disconnect( this );
645 }
646
647 this.list = [];
648
649 this.organized = false;
650 this.emit( 'remove', removed );
651 this.changing = false;
652 this.emit( 'change' );
653
654 return this;
655 };
656
657 /**
658 * Organize actions.
659 *
660 * This is called whenever organized information is requested. It will only reorganize the actions
661 * if something has changed since the last time it ran.
662 *
663 * @private
664 * @chainable
665 */
666 OO.ui.ActionSet.prototype.organize = function () {
667 var i, iLen, j, jLen, flag, action, category, list, item, special,
668 specialFlags = this.constructor.static.specialFlags;
669
670 if ( !this.organized ) {
671 this.categorized = {};
672 this.special = {};
673 this.others = [];
674 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
675 action = this.list[ i ];
676 if ( action.isVisible() ) {
677 // Populate categories
678 for ( category in this.categories ) {
679 if ( !this.categorized[ category ] ) {
680 this.categorized[ category ] = {};
681 }
682 list = action[ this.categories[ category ] ]();
683 if ( !Array.isArray( list ) ) {
684 list = [ list ];
685 }
686 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
687 item = list[ j ];
688 if ( !this.categorized[ category ][ item ] ) {
689 this.categorized[ category ][ item ] = [];
690 }
691 this.categorized[ category ][ item ].push( action );
692 }
693 }
694 // Populate special/others
695 special = false;
696 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
697 flag = specialFlags[ j ];
698 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
699 this.special[ flag ] = action;
700 special = true;
701 break;
702 }
703 }
704 if ( !special ) {
705 this.others.push( action );
706 }
707 }
708 }
709 this.organized = true;
710 }
711
712 return this;
713 };
714
715 /**
716 * DOM element abstraction.
717 *
718 * @abstract
719 * @class
720 *
721 * @constructor
722 * @param {Object} [config] Configuration options
723 * @cfg {Function} [$] jQuery for the frame the widget is in
724 * @cfg {string[]} [classes] CSS class names to add
725 * @cfg {string} [id] HTML id attribute
726 * @cfg {string} [text] Text to insert
727 * @cfg {jQuery} [$content] Content elements to append (after text)
728 * @cfg {Mixed} [data] Element data
729 */
730 OO.ui.Element = function OoUiElement( config ) {
731 // Configuration initialization
732 config = config || {};
733
734 // Properties
735 this.$ = config.$ || OO.ui.Element.static.getJQuery( document );
736 this.data = config.data;
737 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
738 this.elementGroup = null;
739 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
740 this.updateThemeClassesPending = false;
741
742 // Initialization
743 if ( $.isArray( config.classes ) ) {
744 this.$element.addClass( config.classes.join( ' ' ) );
745 }
746 if ( config.id ) {
747 this.$element.attr( 'id', config.id );
748 }
749 if ( config.text ) {
750 this.$element.text( config.text );
751 }
752 if ( config.$content ) {
753 this.$element.append( config.$content );
754 }
755 };
756
757 /* Setup */
758
759 OO.initClass( OO.ui.Element );
760
761 /* Static Properties */
762
763 /**
764 * HTML tag name.
765 *
766 * This may be ignored if #getTagName is overridden.
767 *
768 * @static
769 * @inheritable
770 * @property {string}
771 */
772 OO.ui.Element.static.tagName = 'div';
773
774 /* Static Methods */
775
776 /**
777 * Get a jQuery function within a specific document.
778 *
779 * @static
780 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
781 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
782 * not in an iframe
783 * @return {Function} Bound jQuery function
784 */
785 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
786 function wrapper( selector ) {
787 return $( selector, wrapper.context );
788 }
789
790 wrapper.context = this.getDocument( context );
791
792 if ( $iframe ) {
793 wrapper.$iframe = $iframe;
794 }
795
796 return wrapper;
797 };
798
799 /**
800 * Get the document of an element.
801 *
802 * @static
803 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
804 * @return {HTMLDocument|null} Document object
805 */
806 OO.ui.Element.static.getDocument = function ( obj ) {
807 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
808 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
809 // Empty jQuery selections might have a context
810 obj.context ||
811 // HTMLElement
812 obj.ownerDocument ||
813 // Window
814 obj.document ||
815 // HTMLDocument
816 ( obj.nodeType === 9 && obj ) ||
817 null;
818 };
819
820 /**
821 * Get the window of an element or document.
822 *
823 * @static
824 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
825 * @return {Window} Window object
826 */
827 OO.ui.Element.static.getWindow = function ( obj ) {
828 var doc = this.getDocument( obj );
829 return doc.parentWindow || doc.defaultView;
830 };
831
832 /**
833 * Get the direction of an element or document.
834 *
835 * @static
836 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
837 * @return {string} Text direction, either 'ltr' or 'rtl'
838 */
839 OO.ui.Element.static.getDir = function ( obj ) {
840 var isDoc, isWin;
841
842 if ( obj instanceof jQuery ) {
843 obj = obj[ 0 ];
844 }
845 isDoc = obj.nodeType === 9;
846 isWin = obj.document !== undefined;
847 if ( isDoc || isWin ) {
848 if ( isWin ) {
849 obj = obj.document;
850 }
851 obj = obj.body;
852 }
853 return $( obj ).css( 'direction' );
854 };
855
856 /**
857 * Get the offset between two frames.
858 *
859 * TODO: Make this function not use recursion.
860 *
861 * @static
862 * @param {Window} from Window of the child frame
863 * @param {Window} [to=window] Window of the parent frame
864 * @param {Object} [offset] Offset to start with, used internally
865 * @return {Object} Offset object, containing left and top properties
866 */
867 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
868 var i, len, frames, frame, rect;
869
870 if ( !to ) {
871 to = window;
872 }
873 if ( !offset ) {
874 offset = { top: 0, left: 0 };
875 }
876 if ( from.parent === from ) {
877 return offset;
878 }
879
880 // Get iframe element
881 frames = from.parent.document.getElementsByTagName( 'iframe' );
882 for ( i = 0, len = frames.length; i < len; i++ ) {
883 if ( frames[ i ].contentWindow === from ) {
884 frame = frames[ i ];
885 break;
886 }
887 }
888
889 // Recursively accumulate offset values
890 if ( frame ) {
891 rect = frame.getBoundingClientRect();
892 offset.left += rect.left;
893 offset.top += rect.top;
894 if ( from !== to ) {
895 this.getFrameOffset( from.parent, offset );
896 }
897 }
898 return offset;
899 };
900
901 /**
902 * Get the offset between two elements.
903 *
904 * The two elements may be in a different frame, but in that case the frame $element is in must
905 * be contained in the frame $anchor is in.
906 *
907 * @static
908 * @param {jQuery} $element Element whose position to get
909 * @param {jQuery} $anchor Element to get $element's position relative to
910 * @return {Object} Translated position coordinates, containing top and left properties
911 */
912 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
913 var iframe, iframePos,
914 pos = $element.offset(),
915 anchorPos = $anchor.offset(),
916 elementDocument = this.getDocument( $element ),
917 anchorDocument = this.getDocument( $anchor );
918
919 // If $element isn't in the same document as $anchor, traverse up
920 while ( elementDocument !== anchorDocument ) {
921 iframe = elementDocument.defaultView.frameElement;
922 if ( !iframe ) {
923 throw new Error( '$element frame is not contained in $anchor frame' );
924 }
925 iframePos = $( iframe ).offset();
926 pos.left += iframePos.left;
927 pos.top += iframePos.top;
928 elementDocument = iframe.ownerDocument;
929 }
930 pos.left -= anchorPos.left;
931 pos.top -= anchorPos.top;
932 return pos;
933 };
934
935 /**
936 * Get element border sizes.
937 *
938 * @static
939 * @param {HTMLElement} el Element to measure
940 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
941 */
942 OO.ui.Element.static.getBorders = function ( el ) {
943 var doc = el.ownerDocument,
944 win = doc.parentWindow || doc.defaultView,
945 style = win && win.getComputedStyle ?
946 win.getComputedStyle( el, null ) :
947 el.currentStyle,
948 $el = $( el ),
949 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
950 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
951 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
952 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
953
954 return {
955 top: top,
956 left: left,
957 bottom: bottom,
958 right: right
959 };
960 };
961
962 /**
963 * Get dimensions of an element or window.
964 *
965 * @static
966 * @param {HTMLElement|Window} el Element to measure
967 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
968 */
969 OO.ui.Element.static.getDimensions = function ( el ) {
970 var $el, $win,
971 doc = el.ownerDocument || el.document,
972 win = doc.parentWindow || doc.defaultView;
973
974 if ( win === el || el === doc.documentElement ) {
975 $win = $( win );
976 return {
977 borders: { top: 0, left: 0, bottom: 0, right: 0 },
978 scroll: {
979 top: $win.scrollTop(),
980 left: $win.scrollLeft()
981 },
982 scrollbar: { right: 0, bottom: 0 },
983 rect: {
984 top: 0,
985 left: 0,
986 bottom: $win.innerHeight(),
987 right: $win.innerWidth()
988 }
989 };
990 } else {
991 $el = $( el );
992 return {
993 borders: this.getBorders( el ),
994 scroll: {
995 top: $el.scrollTop(),
996 left: $el.scrollLeft()
997 },
998 scrollbar: {
999 right: $el.innerWidth() - el.clientWidth,
1000 bottom: $el.innerHeight() - el.clientHeight
1001 },
1002 rect: el.getBoundingClientRect()
1003 };
1004 }
1005 };
1006
1007 /**
1008 * Get scrollable object parent
1009 *
1010 * documentElement can't be used to get or set the scrollTop
1011 * property on Blink. Changing and testing its value lets us
1012 * use 'body' or 'documentElement' based on what is working.
1013 *
1014 * https://code.google.com/p/chromium/issues/detail?id=303131
1015 *
1016 * @static
1017 * @param {HTMLElement} el Element to find scrollable parent for
1018 * @return {HTMLElement} Scrollable parent
1019 */
1020 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1021 var scrollTop, body;
1022
1023 if ( OO.ui.scrollableElement === undefined ) {
1024 body = el.ownerDocument.body;
1025 scrollTop = body.scrollTop;
1026 body.scrollTop = 1;
1027
1028 if ( body.scrollTop === 1 ) {
1029 body.scrollTop = scrollTop;
1030 OO.ui.scrollableElement = 'body';
1031 } else {
1032 OO.ui.scrollableElement = 'documentElement';
1033 }
1034 }
1035
1036 return el.ownerDocument[ OO.ui.scrollableElement ];
1037 };
1038
1039 /**
1040 * Get closest scrollable container.
1041 *
1042 * Traverses up until either a scrollable element or the root is reached, in which case the window
1043 * will be returned.
1044 *
1045 * @static
1046 * @param {HTMLElement} el Element to find scrollable container for
1047 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1048 * @return {HTMLElement} Closest scrollable container
1049 */
1050 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1051 var i, val,
1052 props = [ 'overflow' ],
1053 $parent = $( el ).parent();
1054
1055 if ( dimension === 'x' || dimension === 'y' ) {
1056 props.push( 'overflow-' + dimension );
1057 }
1058
1059 while ( $parent.length ) {
1060 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1061 return $parent[ 0 ];
1062 }
1063 i = props.length;
1064 while ( i-- ) {
1065 val = $parent.css( props[ i ] );
1066 if ( val === 'auto' || val === 'scroll' ) {
1067 return $parent[ 0 ];
1068 }
1069 }
1070 $parent = $parent.parent();
1071 }
1072 return this.getDocument( el ).body;
1073 };
1074
1075 /**
1076 * Scroll element into view.
1077 *
1078 * @static
1079 * @param {HTMLElement} el Element to scroll into view
1080 * @param {Object} [config] Configuration options
1081 * @param {string} [config.duration] jQuery animation duration value
1082 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1083 * to scroll in both directions
1084 * @param {Function} [config.complete] Function to call when scrolling completes
1085 */
1086 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1087 // Configuration initialization
1088 config = config || {};
1089
1090 var rel, anim = {},
1091 callback = typeof config.complete === 'function' && config.complete,
1092 sc = this.getClosestScrollableContainer( el, config.direction ),
1093 $sc = $( sc ),
1094 eld = this.getDimensions( el ),
1095 scd = this.getDimensions( sc ),
1096 $win = $( this.getWindow( el ) );
1097
1098 // Compute the distances between the edges of el and the edges of the scroll viewport
1099 if ( $sc.is( 'html, body' ) ) {
1100 // If the scrollable container is the root, this is easy
1101 rel = {
1102 top: eld.rect.top,
1103 bottom: $win.innerHeight() - eld.rect.bottom,
1104 left: eld.rect.left,
1105 right: $win.innerWidth() - eld.rect.right
1106 };
1107 } else {
1108 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1109 rel = {
1110 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1111 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1112 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1113 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1114 };
1115 }
1116
1117 if ( !config.direction || config.direction === 'y' ) {
1118 if ( rel.top < 0 ) {
1119 anim.scrollTop = scd.scroll.top + rel.top;
1120 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1121 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1122 }
1123 }
1124 if ( !config.direction || config.direction === 'x' ) {
1125 if ( rel.left < 0 ) {
1126 anim.scrollLeft = scd.scroll.left + rel.left;
1127 } else if ( rel.left > 0 && rel.right < 0 ) {
1128 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1129 }
1130 }
1131 if ( !$.isEmptyObject( anim ) ) {
1132 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1133 if ( callback ) {
1134 $sc.queue( function ( next ) {
1135 callback();
1136 next();
1137 } );
1138 }
1139 } else {
1140 if ( callback ) {
1141 callback();
1142 }
1143 }
1144 };
1145
1146 /**
1147 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1148 * and reserve space for them, because it probably doesn't.
1149 *
1150 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1151 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1152 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1153 * and then reattach (or show) them back.
1154 *
1155 * @static
1156 * @param {HTMLElement} el Element to reconsider the scrollbars on
1157 */
1158 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1159 var i, len, nodes = [];
1160 // Detach all children
1161 while ( el.firstChild ) {
1162 nodes.push( el.firstChild );
1163 el.removeChild( el.firstChild );
1164 }
1165 // Force reflow
1166 void el.offsetHeight;
1167 // Reattach all children
1168 for ( i = 0, len = nodes.length; i < len; i++ ) {
1169 el.appendChild( nodes[ i ] );
1170 }
1171 };
1172
1173 /* Methods */
1174
1175 /**
1176 * Get element data.
1177 *
1178 * @return {Mixed} Element data
1179 */
1180 OO.ui.Element.prototype.getData = function () {
1181 return this.data;
1182 };
1183
1184 /**
1185 * Set element data.
1186 *
1187 * @param {Mixed} Element data
1188 * @chainable
1189 */
1190 OO.ui.Element.prototype.setData = function ( data ) {
1191 this.data = data;
1192 return this;
1193 };
1194
1195 /**
1196 * Check if element supports one or more methods.
1197 *
1198 * @param {string|string[]} methods Method or list of methods to check
1199 * @return {boolean} All methods are supported
1200 */
1201 OO.ui.Element.prototype.supports = function ( methods ) {
1202 var i, len,
1203 support = 0;
1204
1205 methods = $.isArray( methods ) ? methods : [ methods ];
1206 for ( i = 0, len = methods.length; i < len; i++ ) {
1207 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1208 support++;
1209 }
1210 }
1211
1212 return methods.length === support;
1213 };
1214
1215 /**
1216 * Update the theme-provided classes.
1217 *
1218 * @localdoc This is called in element mixins and widget classes any time state changes.
1219 * Updating is debounced, minimizing overhead of changing multiple attributes and
1220 * guaranteeing that theme updates do not occur within an element's constructor
1221 */
1222 OO.ui.Element.prototype.updateThemeClasses = function () {
1223 if ( !this.updateThemeClassesPending ) {
1224 this.updateThemeClassesPending = true;
1225 setTimeout( this.debouncedUpdateThemeClassesHandler );
1226 }
1227 };
1228
1229 /**
1230 * @private
1231 */
1232 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1233 OO.ui.theme.updateElementClasses( this );
1234 this.updateThemeClassesPending = false;
1235 };
1236
1237 /**
1238 * Get the HTML tag name.
1239 *
1240 * Override this method to base the result on instance information.
1241 *
1242 * @return {string} HTML tag name
1243 */
1244 OO.ui.Element.prototype.getTagName = function () {
1245 return this.constructor.static.tagName;
1246 };
1247
1248 /**
1249 * Check if the element is attached to the DOM
1250 * @return {boolean} The element is attached to the DOM
1251 */
1252 OO.ui.Element.prototype.isElementAttached = function () {
1253 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1254 };
1255
1256 /**
1257 * Get the DOM document.
1258 *
1259 * @return {HTMLDocument} Document object
1260 */
1261 OO.ui.Element.prototype.getElementDocument = function () {
1262 // Don't use this.$.context because subclasses can rebind this.$
1263 // Don't cache this in other ways either because subclasses could can change this.$element
1264 return OO.ui.Element.static.getDocument( this.$element );
1265 };
1266
1267 /**
1268 * Get the DOM window.
1269 *
1270 * @return {Window} Window object
1271 */
1272 OO.ui.Element.prototype.getElementWindow = function () {
1273 return OO.ui.Element.static.getWindow( this.$element );
1274 };
1275
1276 /**
1277 * Get closest scrollable container.
1278 */
1279 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1280 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1281 };
1282
1283 /**
1284 * Get group element is in.
1285 *
1286 * @return {OO.ui.GroupElement|null} Group element, null if none
1287 */
1288 OO.ui.Element.prototype.getElementGroup = function () {
1289 return this.elementGroup;
1290 };
1291
1292 /**
1293 * Set group element is in.
1294 *
1295 * @param {OO.ui.GroupElement|null} group Group element, null if none
1296 * @chainable
1297 */
1298 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1299 this.elementGroup = group;
1300 return this;
1301 };
1302
1303 /**
1304 * Scroll element into view.
1305 *
1306 * @param {Object} [config] Configuration options
1307 */
1308 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1309 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1310 };
1311
1312 /**
1313 * Container for elements.
1314 *
1315 * @abstract
1316 * @class
1317 * @extends OO.ui.Element
1318 * @mixins OO.EventEmitter
1319 *
1320 * @constructor
1321 * @param {Object} [config] Configuration options
1322 */
1323 OO.ui.Layout = function OoUiLayout( config ) {
1324 // Configuration initialization
1325 config = config || {};
1326
1327 // Parent constructor
1328 OO.ui.Layout.super.call( this, config );
1329
1330 // Mixin constructors
1331 OO.EventEmitter.call( this );
1332
1333 // Initialization
1334 this.$element.addClass( 'oo-ui-layout' );
1335 };
1336
1337 /* Setup */
1338
1339 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1340 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1341
1342 /**
1343 * User interface control.
1344 *
1345 * @abstract
1346 * @class
1347 * @extends OO.ui.Element
1348 * @mixins OO.EventEmitter
1349 *
1350 * @constructor
1351 * @param {Object} [config] Configuration options
1352 * @cfg {boolean} [disabled=false] Disable
1353 */
1354 OO.ui.Widget = function OoUiWidget( config ) {
1355 // Initialize config
1356 config = $.extend( { disabled: false }, config );
1357
1358 // Parent constructor
1359 OO.ui.Widget.super.call( this, config );
1360
1361 // Mixin constructors
1362 OO.EventEmitter.call( this );
1363
1364 // Properties
1365 this.visible = true;
1366 this.disabled = null;
1367 this.wasDisabled = null;
1368
1369 // Initialization
1370 this.$element.addClass( 'oo-ui-widget' );
1371 this.setDisabled( !!config.disabled );
1372 };
1373
1374 /* Setup */
1375
1376 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1377 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1378
1379 /* Events */
1380
1381 /**
1382 * @event disable
1383 * @param {boolean} disabled Widget is disabled
1384 */
1385
1386 /**
1387 * @event toggle
1388 * @param {boolean} visible Widget is visible
1389 */
1390
1391 /* Methods */
1392
1393 /**
1394 * Check if the widget is disabled.
1395 *
1396 * @return {boolean} Button is disabled
1397 */
1398 OO.ui.Widget.prototype.isDisabled = function () {
1399 return this.disabled;
1400 };
1401
1402 /**
1403 * Check if widget is visible.
1404 *
1405 * @return {boolean} Widget is visible
1406 */
1407 OO.ui.Widget.prototype.isVisible = function () {
1408 return this.visible;
1409 };
1410
1411 /**
1412 * Set the disabled state of the widget.
1413 *
1414 * This should probably change the widgets' appearance and prevent it from being used.
1415 *
1416 * @param {boolean} disabled Disable widget
1417 * @chainable
1418 */
1419 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1420 var isDisabled;
1421
1422 this.disabled = !!disabled;
1423 isDisabled = this.isDisabled();
1424 if ( isDisabled !== this.wasDisabled ) {
1425 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1426 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1427 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1428 this.emit( 'disable', isDisabled );
1429 this.updateThemeClasses();
1430 }
1431 this.wasDisabled = isDisabled;
1432
1433 return this;
1434 };
1435
1436 /**
1437 * Toggle visibility of widget.
1438 *
1439 * @param {boolean} [show] Make widget visible, omit to toggle visibility
1440 * @fires visible
1441 * @chainable
1442 */
1443 OO.ui.Widget.prototype.toggle = function ( show ) {
1444 show = show === undefined ? !this.visible : !!show;
1445
1446 if ( show !== this.isVisible() ) {
1447 this.visible = show;
1448 this.$element.toggle( show );
1449 this.emit( 'toggle', show );
1450 }
1451
1452 return this;
1453 };
1454
1455 /**
1456 * Update the disabled state, in case of changes in parent widget.
1457 *
1458 * @chainable
1459 */
1460 OO.ui.Widget.prototype.updateDisabled = function () {
1461 this.setDisabled( this.disabled );
1462 return this;
1463 };
1464
1465 /**
1466 * Container for elements in a child frame.
1467 *
1468 * Use together with OO.ui.WindowManager.
1469 *
1470 * @abstract
1471 * @class
1472 * @extends OO.ui.Element
1473 * @mixins OO.EventEmitter
1474 *
1475 * When a window is opened, the setup and ready processes are executed. Similarly, the hold and
1476 * teardown processes are executed when the window is closed.
1477 *
1478 * - {@link OO.ui.WindowManager#openWindow} or {@link #open} methods are used to start opening
1479 * - Window manager begins opening window
1480 * - {@link #getSetupProcess} method is called and its result executed
1481 * - {@link #getReadyProcess} method is called and its result executed
1482 * - Window is now open
1483 *
1484 * - {@link OO.ui.WindowManager#closeWindow} or {@link #close} methods are used to start closing
1485 * - Window manager begins closing window
1486 * - {@link #getHoldProcess} method is called and its result executed
1487 * - {@link #getTeardownProcess} method is called and its result executed
1488 * - Window is now closed
1489 *
1490 * Each process (setup, ready, hold and teardown) can be extended in subclasses by overriding
1491 * {@link #getSetupProcess}, {@link #getReadyProcess}, {@link #getHoldProcess} and
1492 * {@link #getTeardownProcess} respectively. Each process is executed in series, so asynchronous
1493 * processing can complete. Always assume window processes are executed asynchronously. See
1494 * OO.ui.Process for more details about how to work with processes. Some events, as well as the
1495 * #open and #close methods, provide promises which are resolved when the window enters a new state.
1496 *
1497 * Sizing of windows is specified using symbolic names which are interpreted by the window manager.
1498 * If the requested size is not recognized, the window manager will choose a sensible fallback.
1499 *
1500 * @constructor
1501 * @param {Object} [config] Configuration options
1502 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large`, `larger` or
1503 * `full`; omit to use #static-size
1504 */
1505 OO.ui.Window = function OoUiWindow( config ) {
1506 // Configuration initialization
1507 config = config || {};
1508
1509 // Parent constructor
1510 OO.ui.Window.super.call( this, config );
1511
1512 // Mixin constructors
1513 OO.EventEmitter.call( this );
1514
1515 // Properties
1516 this.manager = null;
1517 this.initialized = false;
1518 this.visible = false;
1519 this.opening = null;
1520 this.closing = null;
1521 this.opened = null;
1522 this.timing = null;
1523 this.loading = null;
1524 this.size = config.size || this.constructor.static.size;
1525 this.$frame = this.$( '<div>' );
1526 this.$overlay = this.$( '<div>' );
1527
1528 // Initialization
1529 this.$element
1530 .addClass( 'oo-ui-window' )
1531 .append( this.$frame, this.$overlay );
1532 this.$frame.addClass( 'oo-ui-window-frame' );
1533 this.$overlay.addClass( 'oo-ui-window-overlay' );
1534
1535 // NOTE: Additional initialization will occur when #setManager is called
1536 };
1537
1538 /* Setup */
1539
1540 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1541 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1542
1543 /* Static Properties */
1544
1545 /**
1546 * Symbolic name of size.
1547 *
1548 * Size is used if no size is configured during construction.
1549 *
1550 * @static
1551 * @inheritable
1552 * @property {string}
1553 */
1554 OO.ui.Window.static.size = 'medium';
1555
1556 /* Static Methods */
1557
1558 /**
1559 * Transplant the CSS styles from as parent document to a frame's document.
1560 *
1561 * This loops over the style sheets in the parent document, and copies their nodes to the
1562 * frame's document. It then polls the document to see when all styles have loaded, and once they
1563 * have, resolves the promise.
1564 *
1565 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
1566 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
1567 * Firefox, where the styles won't load until the iframe becomes visible.
1568 *
1569 * For details of how we arrived at the strategy used in this function, see #load.
1570 *
1571 * @static
1572 * @inheritable
1573 * @param {HTMLDocument} parentDoc Document to transplant styles from
1574 * @param {HTMLDocument} frameDoc Document to transplant styles to
1575 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
1576 * @return {jQuery.Promise} Promise resolved when styles have loaded
1577 */
1578 OO.ui.Window.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
1579 var i, numSheets, styleNode, styleText, newNode, timeoutID, pollNodeId, $pendingPollNodes,
1580 $pollNodes = $( [] ),
1581 // Fake font-family value
1582 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
1583 nextIndex = parentDoc.oouiFrameTransplantStylesNextIndex || 0,
1584 deferred = $.Deferred();
1585
1586 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
1587 styleNode = parentDoc.styleSheets[ i ].ownerNode;
1588 if ( styleNode.disabled ) {
1589 continue;
1590 }
1591
1592 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
1593 // External stylesheet; use @import
1594 styleText = '@import url(' + styleNode.href + ');';
1595 } else {
1596 // Internal stylesheet; just copy the text
1597 // For IE10 we need to fall back to .cssText, BUT that's undefined in
1598 // other browsers, so fall back to '' rather than 'undefined'
1599 styleText = styleNode.textContent || parentDoc.styleSheets[ i ].cssText || '';
1600 }
1601
1602 // Create a node with a unique ID that we're going to monitor to see when the CSS
1603 // has loaded
1604 if ( styleNode.oouiFrameTransplantStylesId ) {
1605 // If we're nesting transplantStyles operations and this node already has
1606 // a CSS rule to wait for loading, reuse it
1607 pollNodeId = styleNode.oouiFrameTransplantStylesId;
1608 } else {
1609 // Otherwise, create a new ID
1610 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + nextIndex;
1611 nextIndex++;
1612
1613 // Add #pollNodeId { font-family: ... } to the end of the stylesheet / after the @import
1614 // The font-family rule will only take effect once the @import finishes
1615 styleText += '\n' + '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
1616 }
1617
1618 // Create a node with id=pollNodeId
1619 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
1620 .attr( 'id', pollNodeId )
1621 .appendTo( frameDoc.body )
1622 );
1623
1624 // Add our modified CSS as a <style> tag
1625 newNode = frameDoc.createElement( 'style' );
1626 newNode.textContent = styleText;
1627 newNode.oouiFrameTransplantStylesId = pollNodeId;
1628 frameDoc.head.appendChild( newNode );
1629 }
1630 frameDoc.oouiFrameTransplantStylesNextIndex = nextIndex;
1631
1632 // Poll every 100ms until all external stylesheets have loaded
1633 $pendingPollNodes = $pollNodes;
1634 timeoutID = setTimeout( function pollExternalStylesheets() {
1635 while (
1636 $pendingPollNodes.length > 0 &&
1637 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
1638 ) {
1639 $pendingPollNodes = $pendingPollNodes.slice( 1 );
1640 }
1641
1642 if ( $pendingPollNodes.length === 0 ) {
1643 // We're done!
1644 if ( timeoutID !== null ) {
1645 timeoutID = null;
1646 $pollNodes.remove();
1647 deferred.resolve();
1648 }
1649 } else {
1650 timeoutID = setTimeout( pollExternalStylesheets, 100 );
1651 }
1652 }, 100 );
1653 // ...but give up after a while
1654 if ( timeout !== 0 ) {
1655 setTimeout( function () {
1656 if ( timeoutID ) {
1657 clearTimeout( timeoutID );
1658 timeoutID = null;
1659 $pollNodes.remove();
1660 deferred.reject();
1661 }
1662 }, timeout || 5000 );
1663 }
1664
1665 return deferred.promise();
1666 };
1667
1668 /* Methods */
1669
1670 /**
1671 * Handle mouse down events.
1672 *
1673 * @param {jQuery.Event} e Mouse down event
1674 */
1675 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1676 // Prevent clicking on the click-block from stealing focus
1677 if ( e.target === this.$element[ 0 ] ) {
1678 return false;
1679 }
1680 };
1681
1682 /**
1683 * Check if window has been initialized.
1684 *
1685 * @return {boolean} Window has been initialized
1686 */
1687 OO.ui.Window.prototype.isInitialized = function () {
1688 return this.initialized;
1689 };
1690
1691 /**
1692 * Check if window is visible.
1693 *
1694 * @return {boolean} Window is visible
1695 */
1696 OO.ui.Window.prototype.isVisible = function () {
1697 return this.visible;
1698 };
1699
1700 /**
1701 * Check if window is loading.
1702 *
1703 * @return {boolean} Window is loading
1704 */
1705 OO.ui.Window.prototype.isLoading = function () {
1706 return this.loading && this.loading.state() === 'pending';
1707 };
1708
1709 /**
1710 * Check if window is loaded.
1711 *
1712 * @return {boolean} Window is loaded
1713 */
1714 OO.ui.Window.prototype.isLoaded = function () {
1715 return this.loading && this.loading.state() === 'resolved';
1716 };
1717
1718 /**
1719 * Check if window is opening.
1720 *
1721 * This is a wrapper around OO.ui.WindowManager#isOpening.
1722 *
1723 * @return {boolean} Window is opening
1724 */
1725 OO.ui.Window.prototype.isOpening = function () {
1726 return this.manager.isOpening( this );
1727 };
1728
1729 /**
1730 * Check if window is closing.
1731 *
1732 * This is a wrapper around OO.ui.WindowManager#isClosing.
1733 *
1734 * @return {boolean} Window is closing
1735 */
1736 OO.ui.Window.prototype.isClosing = function () {
1737 return this.manager.isClosing( this );
1738 };
1739
1740 /**
1741 * Check if window is opened.
1742 *
1743 * This is a wrapper around OO.ui.WindowManager#isOpened.
1744 *
1745 * @return {boolean} Window is opened
1746 */
1747 OO.ui.Window.prototype.isOpened = function () {
1748 return this.manager.isOpened( this );
1749 };
1750
1751 /**
1752 * Get the window manager.
1753 *
1754 * @return {OO.ui.WindowManager} Manager of window
1755 */
1756 OO.ui.Window.prototype.getManager = function () {
1757 return this.manager;
1758 };
1759
1760 /**
1761 * Get the window size.
1762 *
1763 * @return {string} Symbolic size name, e.g. `small`, `medium`, `large`, `larger`, `full`
1764 */
1765 OO.ui.Window.prototype.getSize = function () {
1766 return this.size;
1767 };
1768
1769 /**
1770 * Disable transitions on window's frame for the duration of the callback function, then enable them
1771 * back.
1772 *
1773 * @private
1774 * @param {Function} callback Function to call while transitions are disabled
1775 */
1776 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1777 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1778 // Disable transitions first, otherwise we'll get values from when the window was animating.
1779 var oldTransition,
1780 styleObj = this.$frame[ 0 ].style;
1781 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1782 styleObj.MozTransition || styleObj.WebkitTransition;
1783 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1784 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1785 callback();
1786 // Force reflow to make sure the style changes done inside callback really are not transitioned
1787 this.$frame.height();
1788 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1789 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1790 };
1791
1792 /**
1793 * Get the height of the dialog contents.
1794 *
1795 * @return {number} Content height
1796 */
1797 OO.ui.Window.prototype.getContentHeight = function () {
1798 var bodyHeight,
1799 win = this,
1800 bodyStyleObj = this.$body[ 0 ].style,
1801 frameStyleObj = this.$frame[ 0 ].style;
1802
1803 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1804 // Disable transitions first, otherwise we'll get values from when the window was animating.
1805 this.withoutSizeTransitions( function () {
1806 var oldHeight = frameStyleObj.height,
1807 oldPosition = bodyStyleObj.position;
1808 frameStyleObj.height = '1px';
1809 // Force body to resize to new width
1810 bodyStyleObj.position = 'relative';
1811 bodyHeight = win.getBodyHeight();
1812 frameStyleObj.height = oldHeight;
1813 bodyStyleObj.position = oldPosition;
1814 } );
1815
1816 return (
1817 // Add buffer for border
1818 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1819 // Use combined heights of children
1820 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1821 );
1822 };
1823
1824 /**
1825 * Get the height of the dialog contents.
1826 *
1827 * When this function is called, the dialog will temporarily have been resized
1828 * to height=1px, so .scrollHeight measurements can be taken accurately.
1829 *
1830 * @return {number} Height of content
1831 */
1832 OO.ui.Window.prototype.getBodyHeight = function () {
1833 return this.$body[ 0 ].scrollHeight;
1834 };
1835
1836 /**
1837 * Get the directionality of the frame
1838 *
1839 * @return {string} Directionality, 'ltr' or 'rtl'
1840 */
1841 OO.ui.Window.prototype.getDir = function () {
1842 return this.dir;
1843 };
1844
1845 /**
1846 * Get a process for setting up a window for use.
1847 *
1848 * Each time the window is opened this process will set it up for use in a particular context, based
1849 * on the `data` argument.
1850 *
1851 * When you override this method, you can add additional setup steps to the process the parent
1852 * method provides using the 'first' and 'next' methods.
1853 *
1854 * @abstract
1855 * @param {Object} [data] Window opening data
1856 * @return {OO.ui.Process} Setup process
1857 */
1858 OO.ui.Window.prototype.getSetupProcess = function () {
1859 return new OO.ui.Process();
1860 };
1861
1862 /**
1863 * Get a process for readying a window for use.
1864 *
1865 * Each time the window is open and setup, this process will ready it up for use in a particular
1866 * context, based on the `data` argument.
1867 *
1868 * When you override this method, you can add additional setup steps to the process the parent
1869 * method provides using the 'first' and 'next' methods.
1870 *
1871 * @abstract
1872 * @param {Object} [data] Window opening data
1873 * @return {OO.ui.Process} Setup process
1874 */
1875 OO.ui.Window.prototype.getReadyProcess = function () {
1876 return new OO.ui.Process();
1877 };
1878
1879 /**
1880 * Get a process for holding a window from use.
1881 *
1882 * Each time the window is closed, this process will hold it from use in a particular context, based
1883 * on the `data` argument.
1884 *
1885 * When you override this method, you can add additional setup steps to the process the parent
1886 * method provides using the 'first' and 'next' methods.
1887 *
1888 * @abstract
1889 * @param {Object} [data] Window closing data
1890 * @return {OO.ui.Process} Hold process
1891 */
1892 OO.ui.Window.prototype.getHoldProcess = function () {
1893 return new OO.ui.Process();
1894 };
1895
1896 /**
1897 * Get a process for tearing down a window after use.
1898 *
1899 * Each time the window is closed this process will tear it down and do something with the user's
1900 * interactions within the window, based on the `data` argument.
1901 *
1902 * When you override this method, you can add additional teardown steps to the process the parent
1903 * method provides using the 'first' and 'next' methods.
1904 *
1905 * @abstract
1906 * @param {Object} [data] Window closing data
1907 * @return {OO.ui.Process} Teardown process
1908 */
1909 OO.ui.Window.prototype.getTeardownProcess = function () {
1910 return new OO.ui.Process();
1911 };
1912
1913 /**
1914 * Toggle visibility of window.
1915 *
1916 * If the window is isolated and hasn't fully loaded yet, the visibility property will be used
1917 * instead of display.
1918 *
1919 * @param {boolean} [show] Make window visible, omit to toggle visibility
1920 * @fires toggle
1921 * @chainable
1922 */
1923 OO.ui.Window.prototype.toggle = function ( show ) {
1924 show = show === undefined ? !this.visible : !!show;
1925
1926 if ( show !== this.isVisible() ) {
1927 this.visible = show;
1928
1929 if ( this.isolated && !this.isLoaded() ) {
1930 // Hide the window using visibility instead of display until loading is complete
1931 // Can't use display: none; because that prevents the iframe from loading in Firefox
1932 this.$element.css( 'visibility', show ? 'visible' : 'hidden' );
1933 } else {
1934 this.$element.toggle( show ).css( 'visibility', '' );
1935 }
1936 this.emit( 'toggle', show );
1937 }
1938
1939 return this;
1940 };
1941
1942 /**
1943 * Set the window manager.
1944 *
1945 * This must be called before initialize. Calling it more than once will cause an error.
1946 *
1947 * @param {OO.ui.WindowManager} manager Manager for this window
1948 * @throws {Error} If called more than once
1949 * @chainable
1950 */
1951 OO.ui.Window.prototype.setManager = function ( manager ) {
1952 if ( this.manager ) {
1953 throw new Error( 'Cannot set window manager, window already has a manager' );
1954 }
1955
1956 // Properties
1957 this.manager = manager;
1958 this.isolated = manager.shouldIsolate();
1959
1960 // Initialization
1961 if ( this.isolated ) {
1962 this.$iframe = this.$( '<iframe>' );
1963 this.$iframe.attr( { frameborder: 0, scrolling: 'no' } );
1964 this.$frame.append( this.$iframe );
1965 this.$ = function () {
1966 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
1967 };
1968 // WARNING: Do not use this.$ again until #initialize is called
1969 } else {
1970 this.$content = this.$( '<div>' );
1971 this.$document = $( this.getElementDocument() );
1972 this.$content.addClass( 'oo-ui-window-content' ).attr( 'tabIndex', 0 );
1973 this.$frame.append( this.$content );
1974 }
1975 this.toggle( false );
1976
1977 // Figure out directionality:
1978 this.dir = OO.ui.Element.static.getDir( this.$iframe || this.$content ) || 'ltr';
1979
1980 return this;
1981 };
1982
1983 /**
1984 * Set the window size.
1985 *
1986 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1987 * @chainable
1988 */
1989 OO.ui.Window.prototype.setSize = function ( size ) {
1990 this.size = size;
1991 this.updateSize();
1992 return this;
1993 };
1994
1995 /**
1996 * Update the window size.
1997 *
1998 * @chainable
1999 */
2000 OO.ui.Window.prototype.updateSize = function () {
2001 this.manager.updateWindowSize( this );
2002 return this;
2003 };
2004
2005 /**
2006 * Set window dimensions.
2007 *
2008 * Properties are applied to the frame container.
2009 *
2010 * @param {Object} dim CSS dimension properties
2011 * @param {string|number} [dim.width] Width
2012 * @param {string|number} [dim.minWidth] Minimum width
2013 * @param {string|number} [dim.maxWidth] Maximum width
2014 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2015 * @param {string|number} [dim.minWidth] Minimum height
2016 * @param {string|number} [dim.maxWidth] Maximum height
2017 * @chainable
2018 */
2019 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2020 var height,
2021 win = this,
2022 styleObj = this.$frame[ 0 ].style;
2023
2024 // Calculate the height we need to set using the correct width
2025 if ( dim.height === undefined ) {
2026 this.withoutSizeTransitions( function () {
2027 var oldWidth = styleObj.width;
2028 win.$frame.css( 'width', dim.width || '' );
2029 height = win.getContentHeight();
2030 styleObj.width = oldWidth;
2031 } );
2032 } else {
2033 height = dim.height;
2034 }
2035
2036 this.$frame.css( {
2037 width: dim.width || '',
2038 minWidth: dim.minWidth || '',
2039 maxWidth: dim.maxWidth || '',
2040 height: height || '',
2041 minHeight: dim.minHeight || '',
2042 maxHeight: dim.maxHeight || ''
2043 } );
2044
2045 return this;
2046 };
2047
2048 /**
2049 * Initialize window contents.
2050 *
2051 * The first time the window is opened, #initialize is called when it's safe to begin populating
2052 * its contents. See #getSetupProcess for a way to make changes each time the window opens.
2053 *
2054 * Once this method is called, this.$ can be used to create elements within the frame.
2055 *
2056 * @throws {Error} If not attached to a manager
2057 * @chainable
2058 */
2059 OO.ui.Window.prototype.initialize = function () {
2060 if ( !this.manager ) {
2061 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2062 }
2063
2064 // Properties
2065 this.$head = this.$( '<div>' );
2066 this.$body = this.$( '<div>' );
2067 this.$foot = this.$( '<div>' );
2068 this.$innerOverlay = this.$( '<div>' );
2069
2070 // Events
2071 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2072
2073 // Initialization
2074 this.$head.addClass( 'oo-ui-window-head' );
2075 this.$body.addClass( 'oo-ui-window-body' );
2076 this.$foot.addClass( 'oo-ui-window-foot' );
2077 this.$innerOverlay.addClass( 'oo-ui-window-inner-overlay' );
2078 this.$content.append( this.$head, this.$body, this.$foot, this.$innerOverlay );
2079
2080 return this;
2081 };
2082
2083 /**
2084 * Open window.
2085 *
2086 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
2087 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
2088 *
2089 * @param {Object} [data] Window opening data
2090 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
2091 * first argument will be a promise which will be resolved when the window begins closing
2092 */
2093 OO.ui.Window.prototype.open = function ( data ) {
2094 return this.manager.openWindow( this, data );
2095 };
2096
2097 /**
2098 * Close window.
2099 *
2100 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
2101 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
2102 *
2103 * @param {Object} [data] Window closing data
2104 * @return {jQuery.Promise} Promise resolved when window is closed
2105 */
2106 OO.ui.Window.prototype.close = function ( data ) {
2107 return this.manager.closeWindow( this, data );
2108 };
2109
2110 /**
2111 * Setup window.
2112 *
2113 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2114 * by other systems.
2115 *
2116 * @param {Object} [data] Window opening data
2117 * @return {jQuery.Promise} Promise resolved when window is setup
2118 */
2119 OO.ui.Window.prototype.setup = function ( data ) {
2120 var win = this,
2121 deferred = $.Deferred();
2122
2123 this.$element.show();
2124 this.visible = true;
2125 this.getSetupProcess( data ).execute().done( function () {
2126 // Force redraw by asking the browser to measure the elements' widths
2127 win.$element.addClass( 'oo-ui-window-setup' ).width();
2128 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2129 deferred.resolve();
2130 } );
2131
2132 return deferred.promise();
2133 };
2134
2135 /**
2136 * Ready window.
2137 *
2138 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2139 * by other systems.
2140 *
2141 * @param {Object} [data] Window opening data
2142 * @return {jQuery.Promise} Promise resolved when window is ready
2143 */
2144 OO.ui.Window.prototype.ready = function ( data ) {
2145 var win = this,
2146 deferred = $.Deferred();
2147
2148 this.$content.focus();
2149 this.getReadyProcess( data ).execute().done( function () {
2150 // Force redraw by asking the browser to measure the elements' widths
2151 win.$element.addClass( 'oo-ui-window-ready' ).width();
2152 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2153 deferred.resolve();
2154 } );
2155
2156 return deferred.promise();
2157 };
2158
2159 /**
2160 * Hold window.
2161 *
2162 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2163 * by other systems.
2164 *
2165 * @param {Object} [data] Window closing data
2166 * @return {jQuery.Promise} Promise resolved when window is held
2167 */
2168 OO.ui.Window.prototype.hold = function ( data ) {
2169 var win = this,
2170 deferred = $.Deferred();
2171
2172 this.getHoldProcess( data ).execute().done( function () {
2173 // Get the focused element within the window's content
2174 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2175
2176 // Blur the focused element
2177 if ( $focus.length ) {
2178 $focus[ 0 ].blur();
2179 }
2180
2181 // Force redraw by asking the browser to measure the elements' widths
2182 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2183 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2184 deferred.resolve();
2185 } );
2186
2187 return deferred.promise();
2188 };
2189
2190 /**
2191 * Teardown window.
2192 *
2193 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2194 * by other systems.
2195 *
2196 * @param {Object} [data] Window closing data
2197 * @return {jQuery.Promise} Promise resolved when window is torn down
2198 */
2199 OO.ui.Window.prototype.teardown = function ( data ) {
2200 var win = this,
2201 deferred = $.Deferred();
2202
2203 this.getTeardownProcess( data ).execute().done( function () {
2204 // Force redraw by asking the browser to measure the elements' widths
2205 win.$element.removeClass( 'oo-ui-window-load oo-ui-window-setup' ).width();
2206 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2207 win.$element.hide();
2208 win.visible = false;
2209 deferred.resolve();
2210 } );
2211
2212 return deferred.promise();
2213 };
2214
2215 /**
2216 * Load the frame contents.
2217 *
2218 * Once the iframe's stylesheets are loaded the returned promise will be resolved. Calling while
2219 * loading will return a promise but not trigger a new loading cycle. Calling after loading is
2220 * complete will return a promise that's already been resolved.
2221 *
2222 * Sounds simple right? Read on...
2223 *
2224 * When you create a dynamic iframe using open/write/close, the window.load event for the
2225 * iframe is triggered when you call close, and there's no further load event to indicate that
2226 * everything is actually loaded.
2227 *
2228 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
2229 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
2230 * are added to document.styleSheets immediately, and the only way you can determine whether they've
2231 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
2232 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
2233 *
2234 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>`
2235 * tags. Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets
2236 * until the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the
2237 * `@import` has finished. And because the contents of the `<style>` tag are from the same origin,
2238 * accessing .cssRules is allowed.
2239 *
2240 * However, now that we control the styles we're injecting, we might as well do away with
2241 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
2242 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
2243 * and wait for its font-family to change to someValue. Because `@import` is blocking, the
2244 * font-family rule is not applied until after the `@import` finishes.
2245 *
2246 * All this stylesheet injection and polling magic is in #transplantStyles.
2247 *
2248 * @return {jQuery.Promise} Promise resolved when loading is complete
2249 */
2250 OO.ui.Window.prototype.load = function () {
2251 var sub, doc, loading,
2252 win = this;
2253
2254 this.$element.addClass( 'oo-ui-window-load' );
2255
2256 // Non-isolated windows are already "loaded"
2257 if ( !this.loading && !this.isolated ) {
2258 this.loading = $.Deferred().resolve();
2259 this.initialize();
2260 // Set initialized state after so sub-classes aren't confused by it being set by calling
2261 // their parent initialize method
2262 this.initialized = true;
2263 }
2264
2265 // Return existing promise if already loading or loaded
2266 if ( this.loading ) {
2267 return this.loading.promise();
2268 }
2269
2270 // Load the frame
2271 loading = this.loading = $.Deferred();
2272 sub = this.$iframe.prop( 'contentWindow' );
2273 doc = sub.document;
2274
2275 // Initialize contents
2276 doc.open();
2277 doc.write(
2278 '<!doctype html>' +
2279 '<html>' +
2280 '<body class="oo-ui-window-isolated oo-ui-' + this.dir + '"' +
2281 ' style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
2282 '<div class="oo-ui-window-content"></div>' +
2283 '</body>' +
2284 '</html>'
2285 );
2286 doc.close();
2287
2288 // Properties
2289 this.$ = OO.ui.Element.static.getJQuery( doc, this.$iframe );
2290 this.$content = this.$( '.oo-ui-window-content' ).attr( 'tabIndex', 0 );
2291 this.$document = this.$( doc );
2292
2293 // Initialization
2294 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[ 0 ] )
2295 .always( function () {
2296 // Initialize isolated windows
2297 win.initialize();
2298 // Set initialized state after so sub-classes aren't confused by it being set by calling
2299 // their parent initialize method
2300 win.initialized = true;
2301 // Undo the visibility: hidden; hack and apply display: none;
2302 // We can do this safely now that the iframe has initialized
2303 // (don't do this from within #initialize because it has to happen
2304 // after the all subclasses have been handled as well).
2305 win.toggle( win.isVisible() );
2306
2307 loading.resolve();
2308 } );
2309
2310 return loading.promise();
2311 };
2312
2313 /**
2314 * Base class for all dialogs.
2315 *
2316 * Logic:
2317 * - Manage the window (open and close, etc.).
2318 * - Store the internal name and display title.
2319 * - A stack to track one or more pending actions.
2320 * - Manage a set of actions that can be performed.
2321 * - Configure and create action widgets.
2322 *
2323 * User interface:
2324 * - Close the dialog with Escape key.
2325 * - Visually lock the dialog while an action is in
2326 * progress (aka "pending").
2327 *
2328 * Subclass responsibilities:
2329 * - Display the title somewhere.
2330 * - Add content to the dialog.
2331 * - Provide a UI to close the dialog.
2332 * - Display the action widgets somewhere.
2333 *
2334 * @abstract
2335 * @class
2336 * @extends OO.ui.Window
2337 * @mixins OO.ui.PendingElement
2338 *
2339 * @constructor
2340 * @param {Object} [config] Configuration options
2341 */
2342 OO.ui.Dialog = function OoUiDialog( config ) {
2343 // Parent constructor
2344 OO.ui.Dialog.super.call( this, config );
2345
2346 // Mixin constructors
2347 OO.ui.PendingElement.call( this );
2348
2349 // Properties
2350 this.actions = new OO.ui.ActionSet();
2351 this.attachedActions = [];
2352 this.currentAction = null;
2353 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2354
2355 // Events
2356 this.actions.connect( this, {
2357 click: 'onActionClick',
2358 resize: 'onActionResize',
2359 change: 'onActionsChange'
2360 } );
2361
2362 // Initialization
2363 this.$element
2364 .addClass( 'oo-ui-dialog' )
2365 .attr( 'role', 'dialog' );
2366 };
2367
2368 /* Setup */
2369
2370 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2371 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2372
2373 /* Static Properties */
2374
2375 /**
2376 * Symbolic name of dialog.
2377 *
2378 * @abstract
2379 * @static
2380 * @inheritable
2381 * @property {string}
2382 */
2383 OO.ui.Dialog.static.name = '';
2384
2385 /**
2386 * Dialog title.
2387 *
2388 * @abstract
2389 * @static
2390 * @inheritable
2391 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2392 */
2393 OO.ui.Dialog.static.title = '';
2394
2395 /**
2396 * List of OO.ui.ActionWidget configuration options.
2397 *
2398 * @static
2399 * inheritable
2400 * @property {Object[]}
2401 */
2402 OO.ui.Dialog.static.actions = [];
2403
2404 /**
2405 * Close dialog when the escape key is pressed.
2406 *
2407 * @static
2408 * @abstract
2409 * @inheritable
2410 * @property {boolean}
2411 */
2412 OO.ui.Dialog.static.escapable = true;
2413
2414 /* Methods */
2415
2416 /**
2417 * Handle frame document key down events.
2418 *
2419 * @param {jQuery.Event} e Key down event
2420 */
2421 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2422 if ( e.which === OO.ui.Keys.ESCAPE ) {
2423 this.close();
2424 e.preventDefault();
2425 e.stopPropagation();
2426 }
2427 };
2428
2429 /**
2430 * Handle action resized events.
2431 *
2432 * @param {OO.ui.ActionWidget} action Action that was resized
2433 */
2434 OO.ui.Dialog.prototype.onActionResize = function () {
2435 // Override in subclass
2436 };
2437
2438 /**
2439 * Handle action click events.
2440 *
2441 * @param {OO.ui.ActionWidget} action Action that was clicked
2442 */
2443 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2444 if ( !this.isPending() ) {
2445 this.currentAction = action;
2446 this.executeAction( action.getAction() );
2447 }
2448 };
2449
2450 /**
2451 * Handle actions change event.
2452 */
2453 OO.ui.Dialog.prototype.onActionsChange = function () {
2454 this.detachActions();
2455 if ( !this.isClosing() ) {
2456 this.attachActions();
2457 }
2458 };
2459
2460 /**
2461 * Get set of actions.
2462 *
2463 * @return {OO.ui.ActionSet}
2464 */
2465 OO.ui.Dialog.prototype.getActions = function () {
2466 return this.actions;
2467 };
2468
2469 /**
2470 * Get a process for taking action.
2471 *
2472 * When you override this method, you can add additional accept steps to the process the parent
2473 * method provides using the 'first' and 'next' methods.
2474 *
2475 * @abstract
2476 * @param {string} [action] Symbolic name of action
2477 * @return {OO.ui.Process} Action process
2478 */
2479 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2480 return new OO.ui.Process()
2481 .next( function () {
2482 if ( !action ) {
2483 // An empty action always closes the dialog without data, which should always be
2484 // safe and make no changes
2485 this.close();
2486 }
2487 }, this );
2488 };
2489
2490 /**
2491 * @inheritdoc
2492 *
2493 * @param {Object} [data] Dialog opening data
2494 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use #static-title
2495 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2496 * action item, omit to use #static-actions
2497 */
2498 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2499 data = data || {};
2500
2501 // Parent method
2502 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2503 .next( function () {
2504 var i, len,
2505 items = [],
2506 config = this.constructor.static,
2507 actions = data.actions !== undefined ? data.actions : config.actions;
2508
2509 this.title.setLabel(
2510 data.title !== undefined ? data.title : this.constructor.static.title
2511 );
2512 for ( i = 0, len = actions.length; i < len; i++ ) {
2513 items.push(
2514 new OO.ui.ActionWidget( $.extend( { $: this.$ }, actions[ i ] ) )
2515 );
2516 }
2517 this.actions.add( items );
2518
2519 if ( this.constructor.static.escapable ) {
2520 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2521 }
2522 }, this );
2523 };
2524
2525 /**
2526 * @inheritdoc
2527 */
2528 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2529 // Parent method
2530 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2531 .first( function () {
2532 if ( this.constructor.static.escapable ) {
2533 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2534 }
2535
2536 this.actions.clear();
2537 this.currentAction = null;
2538 }, this );
2539 };
2540
2541 /**
2542 * @inheritdoc
2543 */
2544 OO.ui.Dialog.prototype.initialize = function () {
2545 // Parent method
2546 OO.ui.Dialog.super.prototype.initialize.call( this );
2547
2548 // Properties
2549 this.title = new OO.ui.LabelWidget( { $: this.$ } );
2550
2551 // Initialization
2552 this.$content.addClass( 'oo-ui-dialog-content' );
2553 this.setPendingElement( this.$head );
2554 };
2555
2556 /**
2557 * Attach action actions.
2558 */
2559 OO.ui.Dialog.prototype.attachActions = function () {
2560 // Remember the list of potentially attached actions
2561 this.attachedActions = this.actions.get();
2562 };
2563
2564 /**
2565 * Detach action actions.
2566 *
2567 * @chainable
2568 */
2569 OO.ui.Dialog.prototype.detachActions = function () {
2570 var i, len;
2571
2572 // Detach all actions that may have been previously attached
2573 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2574 this.attachedActions[ i ].$element.detach();
2575 }
2576 this.attachedActions = [];
2577 };
2578
2579 /**
2580 * Execute an action.
2581 *
2582 * @param {string} action Symbolic name of action to execute
2583 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2584 */
2585 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2586 this.pushPending();
2587 return this.getActionProcess( action ).execute()
2588 .always( this.popPending.bind( this ) );
2589 };
2590
2591 /**
2592 * Collection of windows.
2593 *
2594 * @class
2595 * @extends OO.ui.Element
2596 * @mixins OO.EventEmitter
2597 *
2598 * Managed windows are mutually exclusive. If a window is opened while there is a current window
2599 * already opening or opened, the current window will be closed without data. Empty closing data
2600 * should always result in the window being closed without causing constructive or destructive
2601 * action.
2602 *
2603 * As a window is opened and closed, it passes through several stages and the manager emits several
2604 * corresponding events.
2605 *
2606 * - {@link #openWindow} or {@link OO.ui.Window#open} methods are used to start opening
2607 * - {@link #event-opening} is emitted with `opening` promise
2608 * - {@link #getSetupDelay} is called the returned value is used to time a pause in execution
2609 * - {@link OO.ui.Window#getSetupProcess} method is called on the window and its result executed
2610 * - `setup` progress notification is emitted from opening promise
2611 * - {@link #getReadyDelay} is called the returned value is used to time a pause in execution
2612 * - {@link OO.ui.Window#getReadyProcess} method is called on the window and its result executed
2613 * - `ready` progress notification is emitted from opening promise
2614 * - `opening` promise is resolved with `opened` promise
2615 * - Window is now open
2616 *
2617 * - {@link #closeWindow} or {@link OO.ui.Window#close} methods are used to start closing
2618 * - `opened` promise is resolved with `closing` promise
2619 * - {@link #event-closing} is emitted with `closing` promise
2620 * - {@link #getHoldDelay} is called the returned value is used to time a pause in execution
2621 * - {@link OO.ui.Window#getHoldProcess} method is called on the window and its result executed
2622 * - `hold` progress notification is emitted from opening promise
2623 * - {@link #getTeardownDelay} is called the returned value is used to time a pause in execution
2624 * - {@link OO.ui.Window#getTeardownProcess} method is called on the window and its result executed
2625 * - `teardown` progress notification is emitted from opening promise
2626 * - Closing promise is resolved
2627 * - Window is now closed
2628 *
2629 * @constructor
2630 * @param {Object} [config] Configuration options
2631 * @cfg {boolean} [isolate] Configure managed windows to isolate their content using inline frames
2632 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2633 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2634 */
2635 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2636 // Configuration initialization
2637 config = config || {};
2638
2639 // Parent constructor
2640 OO.ui.WindowManager.super.call( this, config );
2641
2642 // Mixin constructors
2643 OO.EventEmitter.call( this );
2644
2645 // Properties
2646 this.factory = config.factory;
2647 this.modal = config.modal === undefined || !!config.modal;
2648 this.isolate = !!config.isolate;
2649 this.windows = {};
2650 this.opening = null;
2651 this.opened = null;
2652 this.closing = null;
2653 this.preparingToOpen = null;
2654 this.preparingToClose = null;
2655 this.size = null;
2656 this.currentWindow = null;
2657 this.$ariaHidden = null;
2658 this.requestedSize = null;
2659 this.onWindowResizeTimeout = null;
2660 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2661 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2662 this.onWindowMouseWheelHandler = this.onWindowMouseWheel.bind( this );
2663 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2664
2665 // Initialization
2666 this.$element
2667 .addClass( 'oo-ui-windowManager' )
2668 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2669 };
2670
2671 /* Setup */
2672
2673 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2674 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2675
2676 /* Events */
2677
2678 /**
2679 * Window is opening.
2680 *
2681 * Fired when the window begins to be opened.
2682 *
2683 * @event opening
2684 * @param {OO.ui.Window} win Window that's being opened
2685 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2686 * resolved the first argument will be a promise which will be resolved when the window begins
2687 * closing, the second argument will be the opening data; progress notifications will be fired on
2688 * the promise for `setup` and `ready` when those processes are completed respectively.
2689 * @param {Object} data Window opening data
2690 */
2691
2692 /**
2693 * Window is closing.
2694 *
2695 * Fired when the window begins to be closed.
2696 *
2697 * @event closing
2698 * @param {OO.ui.Window} win Window that's being closed
2699 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2700 * is resolved the first argument will be a the closing data; progress notifications will be fired
2701 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2702 * @param {Object} data Window closing data
2703 */
2704
2705 /**
2706 * Window was resized.
2707 *
2708 * @event resize
2709 * @param {OO.ui.Window} win Window that was resized
2710 */
2711
2712 /* Static Properties */
2713
2714 /**
2715 * Map of symbolic size names and CSS properties.
2716 *
2717 * @static
2718 * @inheritable
2719 * @property {Object}
2720 */
2721 OO.ui.WindowManager.static.sizes = {
2722 small: {
2723 width: 300
2724 },
2725 medium: {
2726 width: 500
2727 },
2728 large: {
2729 width: 700
2730 },
2731 larger: {
2732 width: 900
2733 },
2734 full: {
2735 // These can be non-numeric because they are never used in calculations
2736 width: '100%',
2737 height: '100%'
2738 }
2739 };
2740
2741 /**
2742 * Symbolic name of default size.
2743 *
2744 * Default size is used if the window's requested size is not recognized.
2745 *
2746 * @static
2747 * @inheritable
2748 * @property {string}
2749 */
2750 OO.ui.WindowManager.static.defaultSize = 'medium';
2751
2752 /* Methods */
2753
2754 /**
2755 * Handle window resize events.
2756 *
2757 * @param {jQuery.Event} e Window resize event
2758 */
2759 OO.ui.WindowManager.prototype.onWindowResize = function () {
2760 clearTimeout( this.onWindowResizeTimeout );
2761 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2762 };
2763
2764 /**
2765 * Handle window resize events.
2766 *
2767 * @param {jQuery.Event} e Window resize event
2768 */
2769 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2770 if ( this.currentWindow ) {
2771 this.updateWindowSize( this.currentWindow );
2772 }
2773 };
2774
2775 /**
2776 * Handle window mouse wheel events.
2777 *
2778 * @param {jQuery.Event} e Mouse wheel event
2779 */
2780 OO.ui.WindowManager.prototype.onWindowMouseWheel = function () {
2781 // Kill all events in the parent window if the child window is isolated
2782 return !this.shouldIsolate();
2783 };
2784
2785 /**
2786 * Handle document key down events.
2787 *
2788 * @param {jQuery.Event} e Key down event
2789 */
2790 OO.ui.WindowManager.prototype.onDocumentKeyDown = function ( e ) {
2791 switch ( e.which ) {
2792 case OO.ui.Keys.PAGEUP:
2793 case OO.ui.Keys.PAGEDOWN:
2794 case OO.ui.Keys.END:
2795 case OO.ui.Keys.HOME:
2796 case OO.ui.Keys.LEFT:
2797 case OO.ui.Keys.UP:
2798 case OO.ui.Keys.RIGHT:
2799 case OO.ui.Keys.DOWN:
2800 // Kill all events in the parent window if the child window is isolated
2801 return !this.shouldIsolate();
2802 }
2803 };
2804
2805 /**
2806 * Check if window is opening.
2807 *
2808 * @return {boolean} Window is opening
2809 */
2810 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2811 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2812 };
2813
2814 /**
2815 * Check if window is closing.
2816 *
2817 * @return {boolean} Window is closing
2818 */
2819 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2820 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2821 };
2822
2823 /**
2824 * Check if window is opened.
2825 *
2826 * @return {boolean} Window is opened
2827 */
2828 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2829 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2830 };
2831
2832 /**
2833 * Check if window contents should be isolated.
2834 *
2835 * Window content isolation is done using inline frames.
2836 *
2837 * @return {boolean} Window contents should be isolated
2838 */
2839 OO.ui.WindowManager.prototype.shouldIsolate = function () {
2840 return this.isolate;
2841 };
2842
2843 /**
2844 * Check if a window is being managed.
2845 *
2846 * @param {OO.ui.Window} win Window to check
2847 * @return {boolean} Window is being managed
2848 */
2849 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2850 var name;
2851
2852 for ( name in this.windows ) {
2853 if ( this.windows[ name ] === win ) {
2854 return true;
2855 }
2856 }
2857
2858 return false;
2859 };
2860
2861 /**
2862 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2863 *
2864 * @param {OO.ui.Window} win Window being opened
2865 * @param {Object} [data] Window opening data
2866 * @return {number} Milliseconds to wait
2867 */
2868 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2869 return 0;
2870 };
2871
2872 /**
2873 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2874 *
2875 * @param {OO.ui.Window} win Window being opened
2876 * @param {Object} [data] Window opening data
2877 * @return {number} Milliseconds to wait
2878 */
2879 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2880 return 0;
2881 };
2882
2883 /**
2884 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2885 *
2886 * @param {OO.ui.Window} win Window being closed
2887 * @param {Object} [data] Window closing data
2888 * @return {number} Milliseconds to wait
2889 */
2890 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2891 return 0;
2892 };
2893
2894 /**
2895 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2896 *
2897 * @param {OO.ui.Window} win Window being closed
2898 * @param {Object} [data] Window closing data
2899 * @return {number} Milliseconds to wait
2900 */
2901 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2902 return this.modal ? 250 : 0;
2903 };
2904
2905 /**
2906 * Get managed window by symbolic name.
2907 *
2908 * If window is not yet instantiated, it will be instantiated and added automatically.
2909 *
2910 * @param {string} name Symbolic window name
2911 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2912 * @throws {Error} If the symbolic name is unrecognized by the factory
2913 * @throws {Error} If the symbolic name unrecognized as a managed window
2914 */
2915 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2916 var deferred = $.Deferred(),
2917 win = this.windows[ name ];
2918
2919 if ( !( win instanceof OO.ui.Window ) ) {
2920 if ( this.factory ) {
2921 if ( !this.factory.lookup( name ) ) {
2922 deferred.reject( new OO.ui.Error(
2923 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2924 ) );
2925 } else {
2926 win = this.factory.create( name, this, { $: this.$ } );
2927 this.addWindows( [ win ] );
2928 deferred.resolve( win );
2929 }
2930 } else {
2931 deferred.reject( new OO.ui.Error(
2932 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2933 ) );
2934 }
2935 } else {
2936 deferred.resolve( win );
2937 }
2938
2939 return deferred.promise();
2940 };
2941
2942 /**
2943 * Get current window.
2944 *
2945 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2946 */
2947 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2948 return this.currentWindow;
2949 };
2950
2951 /**
2952 * Open a window.
2953 *
2954 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2955 * @param {Object} [data] Window opening data
2956 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2957 * for more details about the `opening` promise
2958 * @fires opening
2959 */
2960 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2961 var manager = this,
2962 preparing = [],
2963 opening = $.Deferred();
2964
2965 // Argument handling
2966 if ( typeof win === 'string' ) {
2967 return this.getWindow( win ).then( function ( win ) {
2968 return manager.openWindow( win, data );
2969 } );
2970 }
2971
2972 // Error handling
2973 if ( !this.hasWindow( win ) ) {
2974 opening.reject( new OO.ui.Error(
2975 'Cannot open window: window is not attached to manager'
2976 ) );
2977 } else if ( this.preparingToOpen || this.opening || this.opened ) {
2978 opening.reject( new OO.ui.Error(
2979 'Cannot open window: another window is opening or open'
2980 ) );
2981 }
2982
2983 // Window opening
2984 if ( opening.state() !== 'rejected' ) {
2985 if ( !win.getManager() ) {
2986 win.setManager( this );
2987 }
2988 preparing.push( win.load() );
2989
2990 if ( this.closing ) {
2991 // If a window is currently closing, wait for it to complete
2992 preparing.push( this.closing );
2993 }
2994
2995 this.preparingToOpen = $.when.apply( $, preparing );
2996 // Ensure handlers get called after preparingToOpen is set
2997 this.preparingToOpen.done( function () {
2998 if ( manager.modal ) {
2999 manager.toggleGlobalEvents( true );
3000 manager.toggleAriaIsolation( true );
3001 }
3002 manager.currentWindow = win;
3003 manager.opening = opening;
3004 manager.preparingToOpen = null;
3005 manager.emit( 'opening', win, opening, data );
3006 setTimeout( function () {
3007 win.setup( data ).then( function () {
3008 manager.updateWindowSize( win );
3009 manager.opening.notify( { state: 'setup' } );
3010 setTimeout( function () {
3011 win.ready( data ).then( function () {
3012 manager.opening.notify( { state: 'ready' } );
3013 manager.opening = null;
3014 manager.opened = $.Deferred();
3015 opening.resolve( manager.opened.promise(), data );
3016 } );
3017 }, manager.getReadyDelay() );
3018 } );
3019 }, manager.getSetupDelay() );
3020 } );
3021 }
3022
3023 return opening.promise();
3024 };
3025
3026 /**
3027 * Close a window.
3028 *
3029 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3030 * @param {Object} [data] Window closing data
3031 * @return {jQuery.Promise} Promise resolved when window is done closing; see {@link #event-closing}
3032 * for more details about the `closing` promise
3033 * @throws {Error} If no window by that name is being managed
3034 * @fires closing
3035 */
3036 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3037 var manager = this,
3038 preparing = [],
3039 closing = $.Deferred(),
3040 opened;
3041
3042 // Argument handling
3043 if ( typeof win === 'string' ) {
3044 win = this.windows[ win ];
3045 } else if ( !this.hasWindow( win ) ) {
3046 win = null;
3047 }
3048
3049 // Error handling
3050 if ( !win ) {
3051 closing.reject( new OO.ui.Error(
3052 'Cannot close window: window is not attached to manager'
3053 ) );
3054 } else if ( win !== this.currentWindow ) {
3055 closing.reject( new OO.ui.Error(
3056 'Cannot close window: window already closed with different data'
3057 ) );
3058 } else if ( this.preparingToClose || this.closing ) {
3059 closing.reject( new OO.ui.Error(
3060 'Cannot close window: window already closing with different data'
3061 ) );
3062 }
3063
3064 // Window closing
3065 if ( closing.state() !== 'rejected' ) {
3066 if ( this.opening ) {
3067 // If the window is currently opening, close it when it's done
3068 preparing.push( this.opening );
3069 }
3070
3071 this.preparingToClose = $.when.apply( $, preparing );
3072 // Ensure handlers get called after preparingToClose is set
3073 this.preparingToClose.done( function () {
3074 manager.closing = closing;
3075 manager.preparingToClose = null;
3076 manager.emit( 'closing', win, closing, data );
3077 opened = manager.opened;
3078 manager.opened = null;
3079 opened.resolve( closing.promise(), data );
3080 setTimeout( function () {
3081 win.hold( data ).then( function () {
3082 closing.notify( { state: 'hold' } );
3083 setTimeout( function () {
3084 win.teardown( data ).then( function () {
3085 closing.notify( { state: 'teardown' } );
3086 if ( manager.modal ) {
3087 manager.toggleGlobalEvents( false );
3088 manager.toggleAriaIsolation( false );
3089 }
3090 manager.closing = null;
3091 manager.currentWindow = null;
3092 closing.resolve( data );
3093 } );
3094 }, manager.getTeardownDelay() );
3095 } );
3096 }, manager.getHoldDelay() );
3097 } );
3098 }
3099
3100 return closing.promise();
3101 };
3102
3103 /**
3104 * Add windows.
3105 *
3106 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
3107 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
3108 * a statically configured symbolic name
3109 */
3110 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3111 var i, len, win, name, list;
3112
3113 if ( $.isArray( windows ) ) {
3114 // Convert to map of windows by looking up symbolic names from static configuration
3115 list = {};
3116 for ( i = 0, len = windows.length; i < len; i++ ) {
3117 name = windows[ i ].constructor.static.name;
3118 if ( typeof name !== 'string' ) {
3119 throw new Error( 'Cannot add window' );
3120 }
3121 list[ name ] = windows[ i ];
3122 }
3123 } else if ( $.isPlainObject( windows ) ) {
3124 list = windows;
3125 }
3126
3127 // Add windows
3128 for ( name in list ) {
3129 win = list[ name ];
3130 this.windows[ name ] = win;
3131 this.$element.append( win.$element );
3132 }
3133 };
3134
3135 /**
3136 * Remove windows.
3137 *
3138 * Windows will be closed before they are removed.
3139 *
3140 * @param {string[]} names Symbolic names of windows to remove
3141 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3142 * @throws {Error} If windows being removed are not being managed
3143 */
3144 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3145 var i, len, win, name, cleanupWindow,
3146 manager = this,
3147 promises = [],
3148 cleanup = function ( name, win ) {
3149 delete manager.windows[ name ];
3150 win.$element.detach();
3151 };
3152
3153 for ( i = 0, len = names.length; i < len; i++ ) {
3154 name = names[ i ];
3155 win = this.windows[ name ];
3156 if ( !win ) {
3157 throw new Error( 'Cannot remove window' );
3158 }
3159 cleanupWindow = cleanup.bind( null, name, win );
3160 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3161 }
3162
3163 return $.when.apply( $, promises );
3164 };
3165
3166 /**
3167 * Remove all windows.
3168 *
3169 * Windows will be closed before they are removed.
3170 *
3171 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3172 */
3173 OO.ui.WindowManager.prototype.clearWindows = function () {
3174 return this.removeWindows( Object.keys( this.windows ) );
3175 };
3176
3177 /**
3178 * Set dialog size.
3179 *
3180 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3181 *
3182 * @chainable
3183 */
3184 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3185 // Bypass for non-current, and thus invisible, windows
3186 if ( win !== this.currentWindow ) {
3187 return;
3188 }
3189
3190 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3191 sizes = this.constructor.static.sizes,
3192 size = win.getSize();
3193
3194 if ( !sizes[ size ] ) {
3195 size = this.constructor.static.defaultSize;
3196 }
3197 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3198 size = 'full';
3199 }
3200
3201 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3202 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3203 win.setDimensions( sizes[ size ] );
3204
3205 this.emit( 'resize', win );
3206
3207 return this;
3208 };
3209
3210 /**
3211 * Bind or unbind global events for scrolling.
3212 *
3213 * @param {boolean} [on] Bind global events
3214 * @chainable
3215 */
3216 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3217 on = on === undefined ? !!this.globalEvents : !!on;
3218
3219 if ( on ) {
3220 if ( !this.globalEvents ) {
3221 this.$( this.getElementDocument() ).on( {
3222 // Prevent scrolling by keys in top-level window
3223 keydown: this.onDocumentKeyDownHandler
3224 } );
3225 this.$( this.getElementWindow() ).on( {
3226 // Prevent scrolling by wheel in top-level window
3227 mousewheel: this.onWindowMouseWheelHandler,
3228 // Start listening for top-level window dimension changes
3229 'orientationchange resize': this.onWindowResizeHandler
3230 } );
3231 // Disable window scrolling in isolated windows
3232 if ( !this.shouldIsolate() ) {
3233 $( this.getElementDocument().body ).css( 'overflow', 'hidden' );
3234 }
3235 this.globalEvents = true;
3236 }
3237 } else if ( this.globalEvents ) {
3238 // Unbind global events
3239 this.$( this.getElementDocument() ).off( {
3240 // Allow scrolling by keys in top-level window
3241 keydown: this.onDocumentKeyDownHandler
3242 } );
3243 this.$( this.getElementWindow() ).off( {
3244 // Allow scrolling by wheel in top-level window
3245 mousewheel: this.onWindowMouseWheelHandler,
3246 // Stop listening for top-level window dimension changes
3247 'orientationchange resize': this.onWindowResizeHandler
3248 } );
3249 if ( !this.shouldIsolate() ) {
3250 $( this.getElementDocument().body ).css( 'overflow', '' );
3251 }
3252 this.globalEvents = false;
3253 }
3254
3255 return this;
3256 };
3257
3258 /**
3259 * Toggle screen reader visibility of content other than the window manager.
3260 *
3261 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3262 * @chainable
3263 */
3264 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3265 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3266
3267 if ( isolate ) {
3268 if ( !this.$ariaHidden ) {
3269 // Hide everything other than the window manager from screen readers
3270 this.$ariaHidden = $( 'body' )
3271 .children()
3272 .not( this.$element.parentsUntil( 'body' ).last() )
3273 .attr( 'aria-hidden', '' );
3274 }
3275 } else if ( this.$ariaHidden ) {
3276 // Restore screen reader visibility
3277 this.$ariaHidden.removeAttr( 'aria-hidden' );
3278 this.$ariaHidden = null;
3279 }
3280
3281 return this;
3282 };
3283
3284 /**
3285 * Destroy window manager.
3286 */
3287 OO.ui.WindowManager.prototype.destroy = function () {
3288 this.toggleGlobalEvents( false );
3289 this.toggleAriaIsolation( false );
3290 this.clearWindows();
3291 this.$element.remove();
3292 };
3293
3294 /**
3295 * @class
3296 *
3297 * @constructor
3298 * @param {string|jQuery} message Description of error
3299 * @param {Object} [config] Configuration options
3300 * @cfg {boolean} [recoverable=true] Error is recoverable
3301 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3302 */
3303 OO.ui.Error = function OoUiElement( message, config ) {
3304 // Configuration initialization
3305 config = config || {};
3306
3307 // Properties
3308 this.message = message instanceof jQuery ? message : String( message );
3309 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3310 this.warning = !!config.warning;
3311 };
3312
3313 /* Setup */
3314
3315 OO.initClass( OO.ui.Error );
3316
3317 /* Methods */
3318
3319 /**
3320 * Check if error can be recovered from.
3321 *
3322 * @return {boolean} Error is recoverable
3323 */
3324 OO.ui.Error.prototype.isRecoverable = function () {
3325 return this.recoverable;
3326 };
3327
3328 /**
3329 * Check if the error is a warning
3330 *
3331 * @return {boolean} Error is warning
3332 */
3333 OO.ui.Error.prototype.isWarning = function () {
3334 return this.warning;
3335 };
3336
3337 /**
3338 * Get error message as DOM nodes.
3339 *
3340 * @return {jQuery} Error message in DOM nodes
3341 */
3342 OO.ui.Error.prototype.getMessage = function () {
3343 return this.message instanceof jQuery ?
3344 this.message.clone() :
3345 $( '<div>' ).text( this.message ).contents();
3346 };
3347
3348 /**
3349 * Get error message as text.
3350 *
3351 * @return {string} Error message
3352 */
3353 OO.ui.Error.prototype.getMessageText = function () {
3354 return this.message instanceof jQuery ? this.message.text() : this.message;
3355 };
3356
3357 /**
3358 * A list of functions, called in sequence.
3359 *
3360 * If a function added to a process returns boolean false the process will stop; if it returns an
3361 * object with a `promise` method the process will use the promise to either continue to the next
3362 * step when the promise is resolved or stop when the promise is rejected.
3363 *
3364 * @class
3365 *
3366 * @constructor
3367 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3368 * call, see #createStep for more information
3369 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3370 * or a promise
3371 * @return {Object} Step object, with `callback` and `context` properties
3372 */
3373 OO.ui.Process = function ( step, context ) {
3374 // Properties
3375 this.steps = [];
3376
3377 // Initialization
3378 if ( step !== undefined ) {
3379 this.next( step, context );
3380 }
3381 };
3382
3383 /* Setup */
3384
3385 OO.initClass( OO.ui.Process );
3386
3387 /* Methods */
3388
3389 /**
3390 * Start the process.
3391 *
3392 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3393 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3394 * process, the remaining steps will not be taken
3395 */
3396 OO.ui.Process.prototype.execute = function () {
3397 var i, len, promise;
3398
3399 /**
3400 * Continue execution.
3401 *
3402 * @ignore
3403 * @param {Array} step A function and the context it should be called in
3404 * @return {Function} Function that continues the process
3405 */
3406 function proceed( step ) {
3407 return function () {
3408 // Execute step in the correct context
3409 var deferred,
3410 result = step.callback.call( step.context );
3411
3412 if ( result === false ) {
3413 // Use rejected promise for boolean false results
3414 return $.Deferred().reject( [] ).promise();
3415 }
3416 if ( typeof result === 'number' ) {
3417 if ( result < 0 ) {
3418 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3419 }
3420 // Use a delayed promise for numbers, expecting them to be in milliseconds
3421 deferred = $.Deferred();
3422 setTimeout( deferred.resolve, result );
3423 return deferred.promise();
3424 }
3425 if ( result instanceof OO.ui.Error ) {
3426 // Use rejected promise for error
3427 return $.Deferred().reject( [ result ] ).promise();
3428 }
3429 if ( $.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3430 // Use rejected promise for list of errors
3431 return $.Deferred().reject( result ).promise();
3432 }
3433 // Duck-type the object to see if it can produce a promise
3434 if ( result && $.isFunction( result.promise ) ) {
3435 // Use a promise generated from the result
3436 return result.promise();
3437 }
3438 // Use resolved promise for other results
3439 return $.Deferred().resolve().promise();
3440 };
3441 }
3442
3443 if ( this.steps.length ) {
3444 // Generate a chain reaction of promises
3445 promise = proceed( this.steps[ 0 ] )();
3446 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3447 promise = promise.then( proceed( this.steps[ i ] ) );
3448 }
3449 } else {
3450 promise = $.Deferred().resolve().promise();
3451 }
3452
3453 return promise;
3454 };
3455
3456 /**
3457 * Create a process step.
3458 *
3459 * @private
3460 * @param {number|jQuery.Promise|Function} step
3461 *
3462 * - Number of milliseconds to wait; or
3463 * - Promise to wait to be resolved; or
3464 * - Function to execute
3465 * - If it returns boolean false the process will stop
3466 * - If it returns an object with a `promise` method the process will use the promise to either
3467 * continue to the next step when the promise is resolved or stop when the promise is rejected
3468 * - If it returns a number, the process will wait for that number of milliseconds before
3469 * proceeding
3470 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3471 * or a promise
3472 * @return {Object} Step object, with `callback` and `context` properties
3473 */
3474 OO.ui.Process.prototype.createStep = function ( step, context ) {
3475 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3476 return {
3477 callback: function () {
3478 return step;
3479 },
3480 context: null
3481 };
3482 }
3483 if ( $.isFunction( step ) ) {
3484 return {
3485 callback: step,
3486 context: context
3487 };
3488 }
3489 throw new Error( 'Cannot create process step: number, promise or function expected' );
3490 };
3491
3492 /**
3493 * Add step to the beginning of the process.
3494 *
3495 * @inheritdoc #createStep
3496 * @return {OO.ui.Process} this
3497 * @chainable
3498 */
3499 OO.ui.Process.prototype.first = function ( step, context ) {
3500 this.steps.unshift( this.createStep( step, context ) );
3501 return this;
3502 };
3503
3504 /**
3505 * Add step to the end of the process.
3506 *
3507 * @inheritdoc #createStep
3508 * @return {OO.ui.Process} this
3509 * @chainable
3510 */
3511 OO.ui.Process.prototype.next = function ( step, context ) {
3512 this.steps.push( this.createStep( step, context ) );
3513 return this;
3514 };
3515
3516 /**
3517 * Factory for tools.
3518 *
3519 * @class
3520 * @extends OO.Factory
3521 * @constructor
3522 */
3523 OO.ui.ToolFactory = function OoUiToolFactory() {
3524 // Parent constructor
3525 OO.ui.ToolFactory.super.call( this );
3526 };
3527
3528 /* Setup */
3529
3530 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3531
3532 /* Methods */
3533
3534 /**
3535 * Get tools from the factory
3536 *
3537 * @param {Array} include Included tools
3538 * @param {Array} exclude Excluded tools
3539 * @param {Array} promote Promoted tools
3540 * @param {Array} demote Demoted tools
3541 * @return {string[]} List of tools
3542 */
3543 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3544 var i, len, included, promoted, demoted,
3545 auto = [],
3546 used = {};
3547
3548 // Collect included and not excluded tools
3549 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3550
3551 // Promotion
3552 promoted = this.extract( promote, used );
3553 demoted = this.extract( demote, used );
3554
3555 // Auto
3556 for ( i = 0, len = included.length; i < len; i++ ) {
3557 if ( !used[ included[ i ] ] ) {
3558 auto.push( included[ i ] );
3559 }
3560 }
3561
3562 return promoted.concat( auto ).concat( demoted );
3563 };
3564
3565 /**
3566 * Get a flat list of names from a list of names or groups.
3567 *
3568 * Tools can be specified in the following ways:
3569 *
3570 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3571 * - All tools in a group: `{ group: 'group-name' }`
3572 * - All tools: `'*'`
3573 *
3574 * @private
3575 * @param {Array|string} collection List of tools
3576 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3577 * names will be added as properties
3578 * @return {string[]} List of extracted names
3579 */
3580 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3581 var i, len, item, name, tool,
3582 names = [];
3583
3584 if ( collection === '*' ) {
3585 for ( name in this.registry ) {
3586 tool = this.registry[ name ];
3587 if (
3588 // Only add tools by group name when auto-add is enabled
3589 tool.static.autoAddToCatchall &&
3590 // Exclude already used tools
3591 ( !used || !used[ name ] )
3592 ) {
3593 names.push( name );
3594 if ( used ) {
3595 used[ name ] = true;
3596 }
3597 }
3598 }
3599 } else if ( $.isArray( collection ) ) {
3600 for ( i = 0, len = collection.length; i < len; i++ ) {
3601 item = collection[ i ];
3602 // Allow plain strings as shorthand for named tools
3603 if ( typeof item === 'string' ) {
3604 item = { name: item };
3605 }
3606 if ( OO.isPlainObject( item ) ) {
3607 if ( item.group ) {
3608 for ( name in this.registry ) {
3609 tool = this.registry[ name ];
3610 if (
3611 // Include tools with matching group
3612 tool.static.group === item.group &&
3613 // Only add tools by group name when auto-add is enabled
3614 tool.static.autoAddToGroup &&
3615 // Exclude already used tools
3616 ( !used || !used[ name ] )
3617 ) {
3618 names.push( name );
3619 if ( used ) {
3620 used[ name ] = true;
3621 }
3622 }
3623 }
3624 // Include tools with matching name and exclude already used tools
3625 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3626 names.push( item.name );
3627 if ( used ) {
3628 used[ item.name ] = true;
3629 }
3630 }
3631 }
3632 }
3633 }
3634 return names;
3635 };
3636
3637 /**
3638 * Factory for tool groups.
3639 *
3640 * @class
3641 * @extends OO.Factory
3642 * @constructor
3643 */
3644 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3645 // Parent constructor
3646 OO.Factory.call( this );
3647
3648 var i, l,
3649 defaultClasses = this.constructor.static.getDefaultClasses();
3650
3651 // Register default toolgroups
3652 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3653 this.register( defaultClasses[ i ] );
3654 }
3655 };
3656
3657 /* Setup */
3658
3659 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3660
3661 /* Static Methods */
3662
3663 /**
3664 * Get a default set of classes to be registered on construction
3665 *
3666 * @return {Function[]} Default classes
3667 */
3668 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3669 return [
3670 OO.ui.BarToolGroup,
3671 OO.ui.ListToolGroup,
3672 OO.ui.MenuToolGroup
3673 ];
3674 };
3675
3676 /**
3677 * Theme logic.
3678 *
3679 * @abstract
3680 * @class
3681 *
3682 * @constructor
3683 * @param {Object} [config] Configuration options
3684 */
3685 OO.ui.Theme = function OoUiTheme( config ) {
3686 // Configuration initialization
3687 config = config || {};
3688 };
3689
3690 /* Setup */
3691
3692 OO.initClass( OO.ui.Theme );
3693
3694 /* Methods */
3695
3696 /**
3697 * Get a list of classes to be applied to a widget.
3698 *
3699 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3700 * otherwise state transitions will not work properly.
3701 *
3702 * @param {OO.ui.Element} element Element for which to get classes
3703 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3704 */
3705 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3706 return { on: [], off: [] };
3707 };
3708
3709 /**
3710 * Update CSS classes provided by the theme.
3711 *
3712 * For elements with theme logic hooks, this should be called any time there's a state change.
3713 *
3714 * @param {OO.ui.Element} element Element for which to update classes
3715 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3716 */
3717 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3718 var classes = this.getElementClasses( element );
3719
3720 element.$element
3721 .removeClass( classes.off.join( ' ' ) )
3722 .addClass( classes.on.join( ' ' ) );
3723 };
3724
3725 /**
3726 * Element supporting "sequential focus navigation" using the 'tabindex' attribute.
3727 *
3728 * @abstract
3729 * @class
3730 *
3731 * @constructor
3732 * @param {Object} [config] Configuration options
3733 * @cfg {jQuery} [$tabIndexed] tabIndexed node, assigned to #$tabIndexed, omit to use #$element
3734 * @cfg {number|Function} [tabIndex=0] Tab index value. Use 0 to use default ordering, use -1 to
3735 * prevent tab focusing. (default: 0)
3736 */
3737 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3738 // Configuration initialization
3739 config = config || {};
3740
3741 // Properties
3742 this.$tabIndexed = null;
3743 this.tabIndex = null;
3744
3745 // Initialization
3746 this.setTabIndex( config.tabIndex || 0 );
3747 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3748 };
3749
3750 /* Setup */
3751
3752 OO.initClass( OO.ui.TabIndexedElement );
3753
3754 /* Methods */
3755
3756 /**
3757 * Set the element with 'tabindex' attribute.
3758 *
3759 * If an element is already set, it will be cleaned up before setting up the new element.
3760 *
3761 * @param {jQuery} $tabIndexed Element to set tab index on
3762 */
3763 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3764 if ( this.$tabIndexed ) {
3765 this.$tabIndexed.removeAttr( 'tabindex' );
3766 }
3767
3768 this.$tabIndexed = $tabIndexed;
3769 if ( this.tabIndex !== null ) {
3770 this.$tabIndexed.attr( 'tabindex', this.tabIndex );
3771 }
3772 };
3773
3774 /**
3775 * Set tab index value.
3776 *
3777 * @param {number|null} tabIndex Tab index value or null for no tabIndex
3778 * @chainable
3779 */
3780 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3781 tabIndex = typeof tabIndex === 'number' && tabIndex >= 0 ? tabIndex : null;
3782
3783 if ( this.tabIndex !== tabIndex ) {
3784 if ( this.$tabIndexed ) {
3785 if ( tabIndex !== null ) {
3786 this.$tabIndexed.attr( 'tabindex', tabIndex );
3787 } else {
3788 this.$tabIndexed.removeAttr( 'tabindex' );
3789 }
3790 }
3791 this.tabIndex = tabIndex;
3792 }
3793
3794 return this;
3795 };
3796
3797 /**
3798 * Get tab index value.
3799 *
3800 * @return {number} Tab index value
3801 */
3802 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3803 return this.tabIndex;
3804 };
3805
3806 /**
3807 * Element with a button.
3808 *
3809 * Buttons are used for controls which can be clicked. They can be configured to use tab indexing
3810 * and access keys for accessibility purposes.
3811 *
3812 * @abstract
3813 * @class
3814 *
3815 * @constructor
3816 * @param {Object} [config] Configuration options
3817 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3818 * @cfg {boolean} [framed=true] Render button with a frame
3819 * @cfg {string} [accessKey] Button's access key
3820 */
3821 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3822 // Configuration initialization
3823 config = config || {};
3824
3825 // Properties
3826 this.$button = config.$button || this.$( '<a>' );
3827 this.framed = null;
3828 this.accessKey = null;
3829 this.active = false;
3830 this.onMouseUpHandler = this.onMouseUp.bind( this );
3831 this.onMouseDownHandler = this.onMouseDown.bind( this );
3832
3833 // Initialization
3834 this.$element.addClass( 'oo-ui-buttonElement' );
3835 this.toggleFramed( config.framed === undefined || config.framed );
3836 this.setAccessKey( config.accessKey );
3837 this.setButtonElement( this.$button );
3838 };
3839
3840 /* Setup */
3841
3842 OO.initClass( OO.ui.ButtonElement );
3843
3844 /* Static Properties */
3845
3846 /**
3847 * Cancel mouse down events.
3848 *
3849 * @static
3850 * @inheritable
3851 * @property {boolean}
3852 */
3853 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
3854
3855 /* Methods */
3856
3857 /**
3858 * Set the button element.
3859 *
3860 * If an element is already set, it will be cleaned up before setting up the new element.
3861 *
3862 * @param {jQuery} $button Element to use as button
3863 */
3864 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
3865 if ( this.$button ) {
3866 this.$button
3867 .removeClass( 'oo-ui-buttonElement-button' )
3868 .removeAttr( 'role accesskey' )
3869 .off( 'mousedown', this.onMouseDownHandler );
3870 }
3871
3872 this.$button = $button
3873 .addClass( 'oo-ui-buttonElement-button' )
3874 .attr( { role: 'button', accesskey: this.accessKey } )
3875 .on( 'mousedown', this.onMouseDownHandler );
3876 };
3877
3878 /**
3879 * Handles mouse down events.
3880 *
3881 * @param {jQuery.Event} e Mouse down event
3882 */
3883 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
3884 if ( this.isDisabled() || e.which !== 1 ) {
3885 return false;
3886 }
3887 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
3888 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
3889 // reliably remove the pressed class
3890 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
3891 // Prevent change of focus unless specifically configured otherwise
3892 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3893 return false;
3894 }
3895 };
3896
3897 /**
3898 * Handles mouse up events.
3899 *
3900 * @param {jQuery.Event} e Mouse up event
3901 */
3902 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
3903 if ( this.isDisabled() || e.which !== 1 ) {
3904 return false;
3905 }
3906 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
3907 // Stop listening for mouseup, since we only needed this once
3908 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
3909 };
3910
3911 /**
3912 * Check if button has a frame.
3913 *
3914 * @return {boolean} Button is framed
3915 */
3916 OO.ui.ButtonElement.prototype.isFramed = function () {
3917 return this.framed;
3918 };
3919
3920 /**
3921 * Toggle frame.
3922 *
3923 * @param {boolean} [framed] Make button framed, omit to toggle
3924 * @chainable
3925 */
3926 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
3927 framed = framed === undefined ? !this.framed : !!framed;
3928 if ( framed !== this.framed ) {
3929 this.framed = framed;
3930 this.$element
3931 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
3932 .toggleClass( 'oo-ui-buttonElement-framed', framed );
3933 this.updateThemeClasses();
3934 }
3935
3936 return this;
3937 };
3938
3939 /**
3940 * Set access key.
3941 *
3942 * @param {string} accessKey Button's access key, use empty string to remove
3943 * @chainable
3944 */
3945 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
3946 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
3947
3948 if ( this.accessKey !== accessKey ) {
3949 if ( this.$button ) {
3950 if ( accessKey !== null ) {
3951 this.$button.attr( 'accesskey', accessKey );
3952 } else {
3953 this.$button.removeAttr( 'accesskey' );
3954 }
3955 }
3956 this.accessKey = accessKey;
3957 }
3958
3959 return this;
3960 };
3961
3962 /**
3963 * Set active state.
3964 *
3965 * @param {boolean} [value] Make button active
3966 * @chainable
3967 */
3968 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
3969 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
3970 return this;
3971 };
3972
3973 /**
3974 * Element containing a sequence of child elements.
3975 *
3976 * @abstract
3977 * @class
3978 *
3979 * @constructor
3980 * @param {Object} [config] Configuration options
3981 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
3982 */
3983 OO.ui.GroupElement = function OoUiGroupElement( config ) {
3984 // Configuration initialization
3985 config = config || {};
3986
3987 // Properties
3988 this.$group = null;
3989 this.items = [];
3990 this.aggregateItemEvents = {};
3991
3992 // Initialization
3993 this.setGroupElement( config.$group || this.$( '<div>' ) );
3994 };
3995
3996 /* Methods */
3997
3998 /**
3999 * Set the group element.
4000 *
4001 * If an element is already set, items will be moved to the new element.
4002 *
4003 * @param {jQuery} $group Element to use as group
4004 */
4005 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4006 var i, len;
4007
4008 this.$group = $group;
4009 for ( i = 0, len = this.items.length; i < len; i++ ) {
4010 this.$group.append( this.items[ i ].$element );
4011 }
4012 };
4013
4014 /**
4015 * Check if there are no items.
4016 *
4017 * @return {boolean} Group is empty
4018 */
4019 OO.ui.GroupElement.prototype.isEmpty = function () {
4020 return !this.items.length;
4021 };
4022
4023 /**
4024 * Get items.
4025 *
4026 * @return {OO.ui.Element[]} Items
4027 */
4028 OO.ui.GroupElement.prototype.getItems = function () {
4029 return this.items.slice( 0 );
4030 };
4031
4032 /**
4033 * Get an item by its data.
4034 *
4035 * Data is compared by a hash of its value. Only the first item with matching data will be returned.
4036 *
4037 * @param {Object} data Item data to search for
4038 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4039 */
4040 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4041 var i, len, item,
4042 hash = OO.getHash( data );
4043
4044 for ( i = 0, len = this.items.length; i < len; i++ ) {
4045 item = this.items[ i ];
4046 if ( hash === OO.getHash( item.getData() ) ) {
4047 return item;
4048 }
4049 }
4050
4051 return null;
4052 };
4053
4054 /**
4055 * Get items by their data.
4056 *
4057 * Data is compared by a hash of its value. All items with matching data will be returned.
4058 *
4059 * @param {Object} data Item data to search for
4060 * @return {OO.ui.Element[]} Items with equivalent data
4061 */
4062 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4063 var i, len, item,
4064 hash = OO.getHash( data ),
4065 items = [];
4066
4067 for ( i = 0, len = this.items.length; i < len; i++ ) {
4068 item = this.items[ i ];
4069 if ( hash === OO.getHash( item.getData() ) ) {
4070 items.push( item );
4071 }
4072 }
4073
4074 return items;
4075 };
4076
4077 /**
4078 * Add an aggregate item event.
4079 *
4080 * Aggregated events are listened to on each item and then emitted by the group under a new name,
4081 * and with an additional leading parameter containing the item that emitted the original event.
4082 * Other arguments that were emitted from the original event are passed through.
4083 *
4084 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
4085 * event, use null value to remove aggregation
4086 * @throws {Error} If aggregation already exists
4087 */
4088 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4089 var i, len, item, add, remove, itemEvent, groupEvent;
4090
4091 for ( itemEvent in events ) {
4092 groupEvent = events[ itemEvent ];
4093
4094 // Remove existing aggregated event
4095 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4096 // Don't allow duplicate aggregations
4097 if ( groupEvent ) {
4098 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4099 }
4100 // Remove event aggregation from existing items
4101 for ( i = 0, len = this.items.length; i < len; i++ ) {
4102 item = this.items[ i ];
4103 if ( item.connect && item.disconnect ) {
4104 remove = {};
4105 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4106 item.disconnect( this, remove );
4107 }
4108 }
4109 // Prevent future items from aggregating event
4110 delete this.aggregateItemEvents[ itemEvent ];
4111 }
4112
4113 // Add new aggregate event
4114 if ( groupEvent ) {
4115 // Make future items aggregate event
4116 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4117 // Add event aggregation to existing items
4118 for ( i = 0, len = this.items.length; i < len; i++ ) {
4119 item = this.items[ i ];
4120 if ( item.connect && item.disconnect ) {
4121 add = {};
4122 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4123 item.connect( this, add );
4124 }
4125 }
4126 }
4127 }
4128 };
4129
4130 /**
4131 * Add items.
4132 *
4133 * Adding an existing item will move it.
4134 *
4135 * @param {OO.ui.Element[]} items Items
4136 * @param {number} [index] Index to insert items at
4137 * @chainable
4138 */
4139 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4140 var i, len, item, event, events, currentIndex,
4141 itemElements = [];
4142
4143 for ( i = 0, len = items.length; i < len; i++ ) {
4144 item = items[ i ];
4145
4146 // Check if item exists then remove it first, effectively "moving" it
4147 currentIndex = $.inArray( item, this.items );
4148 if ( currentIndex >= 0 ) {
4149 this.removeItems( [ item ] );
4150 // Adjust index to compensate for removal
4151 if ( currentIndex < index ) {
4152 index--;
4153 }
4154 }
4155 // Add the item
4156 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4157 events = {};
4158 for ( event in this.aggregateItemEvents ) {
4159 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4160 }
4161 item.connect( this, events );
4162 }
4163 item.setElementGroup( this );
4164 itemElements.push( item.$element.get( 0 ) );
4165 }
4166
4167 if ( index === undefined || index < 0 || index >= this.items.length ) {
4168 this.$group.append( itemElements );
4169 this.items.push.apply( this.items, items );
4170 } else if ( index === 0 ) {
4171 this.$group.prepend( itemElements );
4172 this.items.unshift.apply( this.items, items );
4173 } else {
4174 this.items[ index ].$element.before( itemElements );
4175 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4176 }
4177
4178 return this;
4179 };
4180
4181 /**
4182 * Remove items.
4183 *
4184 * Items will be detached, not removed, so they can be used later.
4185 *
4186 * @param {OO.ui.Element[]} items Items to remove
4187 * @chainable
4188 */
4189 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4190 var i, len, item, index, remove, itemEvent;
4191
4192 // Remove specific items
4193 for ( i = 0, len = items.length; i < len; i++ ) {
4194 item = items[ i ];
4195 index = $.inArray( item, this.items );
4196 if ( index !== -1 ) {
4197 if (
4198 item.connect && item.disconnect &&
4199 !$.isEmptyObject( this.aggregateItemEvents )
4200 ) {
4201 remove = {};
4202 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4203 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4204 }
4205 item.disconnect( this, remove );
4206 }
4207 item.setElementGroup( null );
4208 this.items.splice( index, 1 );
4209 item.$element.detach();
4210 }
4211 }
4212
4213 return this;
4214 };
4215
4216 /**
4217 * Clear all items.
4218 *
4219 * Items will be detached, not removed, so they can be used later.
4220 *
4221 * @chainable
4222 */
4223 OO.ui.GroupElement.prototype.clearItems = function () {
4224 var i, len, item, remove, itemEvent;
4225
4226 // Remove all items
4227 for ( i = 0, len = this.items.length; i < len; i++ ) {
4228 item = this.items[ i ];
4229 if (
4230 item.connect && item.disconnect &&
4231 !$.isEmptyObject( this.aggregateItemEvents )
4232 ) {
4233 remove = {};
4234 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4235 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4236 }
4237 item.disconnect( this, remove );
4238 }
4239 item.setElementGroup( null );
4240 item.$element.detach();
4241 }
4242
4243 this.items = [];
4244 return this;
4245 };
4246
4247 /**
4248 * A mixin for an element that can be dragged and dropped.
4249 * Use in conjunction with DragGroupWidget
4250 *
4251 * @abstract
4252 * @class
4253 *
4254 * @constructor
4255 */
4256 OO.ui.DraggableElement = function OoUiDraggableElement() {
4257 // Properties
4258 this.index = null;
4259
4260 // Initialize and events
4261 this.$element
4262 .attr( 'draggable', true )
4263 .addClass( 'oo-ui-draggableElement' )
4264 .on( {
4265 dragstart: this.onDragStart.bind( this ),
4266 dragover: this.onDragOver.bind( this ),
4267 dragend: this.onDragEnd.bind( this ),
4268 drop: this.onDrop.bind( this )
4269 } );
4270 };
4271
4272 /* Events */
4273
4274 /**
4275 * @event dragstart
4276 * @param {OO.ui.DraggableElement} item Dragging item
4277 */
4278
4279 /**
4280 * @event dragend
4281 */
4282
4283 /**
4284 * @event drop
4285 */
4286
4287 /* Methods */
4288
4289 /**
4290 * Respond to dragstart event.
4291 * @param {jQuery.Event} event jQuery event
4292 * @fires dragstart
4293 */
4294 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4295 var dataTransfer = e.originalEvent.dataTransfer;
4296 // Define drop effect
4297 dataTransfer.dropEffect = 'none';
4298 dataTransfer.effectAllowed = 'move';
4299 // We must set up a dataTransfer data property or Firefox seems to
4300 // ignore the fact the element is draggable.
4301 try {
4302 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4303 } catch ( err ) {
4304 // The above is only for firefox. No need to set a catch clause
4305 // if it fails, move on.
4306 }
4307 // Add dragging class
4308 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4309 // Emit event
4310 this.emit( 'dragstart', this );
4311 return true;
4312 };
4313
4314 /**
4315 * Respond to dragend event.
4316 * @fires dragend
4317 */
4318 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4319 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4320 this.emit( 'dragend' );
4321 };
4322
4323 /**
4324 * Handle drop event.
4325 * @param {jQuery.Event} event jQuery event
4326 * @fires drop
4327 */
4328 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4329 e.preventDefault();
4330 this.emit( 'drop', e );
4331 };
4332
4333 /**
4334 * In order for drag/drop to work, the dragover event must
4335 * return false and stop propogation.
4336 */
4337 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4338 e.preventDefault();
4339 };
4340
4341 /**
4342 * Set item index.
4343 * Store it in the DOM so we can access from the widget drag event
4344 * @param {number} Item index
4345 */
4346 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4347 if ( this.index !== index ) {
4348 this.index = index;
4349 this.$element.data( 'index', index );
4350 }
4351 };
4352
4353 /**
4354 * Get item index
4355 * @return {number} Item index
4356 */
4357 OO.ui.DraggableElement.prototype.getIndex = function () {
4358 return this.index;
4359 };
4360
4361 /**
4362 * Element containing a sequence of child elements that can be dragged
4363 * and dropped.
4364 *
4365 * @abstract
4366 * @class
4367 *
4368 * @constructor
4369 * @param {Object} [config] Configuration options
4370 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
4371 * @cfg {string} [orientation] Item orientation, 'horizontal' or 'vertical'. Defaults to 'vertical'
4372 */
4373 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4374 // Configuration initialization
4375 config = config || {};
4376
4377 // Parent constructor
4378 OO.ui.GroupElement.call( this, config );
4379
4380 // Properties
4381 this.orientation = config.orientation || 'vertical';
4382 this.dragItem = null;
4383 this.itemDragOver = null;
4384 this.itemKeys = {};
4385 this.sideInsertion = '';
4386
4387 // Events
4388 this.aggregate( {
4389 dragstart: 'itemDragStart',
4390 dragend: 'itemDragEnd',
4391 drop: 'itemDrop'
4392 } );
4393 this.connect( this, {
4394 itemDragStart: 'onItemDragStart',
4395 itemDrop: 'onItemDrop',
4396 itemDragEnd: 'onItemDragEnd'
4397 } );
4398 this.$element.on( {
4399 dragover: $.proxy( this.onDragOver, this ),
4400 dragleave: $.proxy( this.onDragLeave, this )
4401 } );
4402
4403 // Initialize
4404 if ( $.isArray( config.items ) ) {
4405 this.addItems( config.items );
4406 }
4407 this.$placeholder = $( '<div>' )
4408 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4409 this.$element
4410 .addClass( 'oo-ui-draggableGroupElement' )
4411 .append( this.$status )
4412 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4413 .prepend( this.$placeholder );
4414 };
4415
4416 /* Setup */
4417 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4418
4419 /* Events */
4420
4421 /**
4422 * @event reorder
4423 * @param {OO.ui.DraggableElement} item Reordered item
4424 * @param {number} [newIndex] New index for the item
4425 */
4426
4427 /* Methods */
4428
4429 /**
4430 * Respond to item drag start event
4431 * @param {OO.ui.DraggableElement} item Dragged item
4432 */
4433 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4434 var i, len;
4435
4436 // Map the index of each object
4437 for ( i = 0, len = this.items.length; i < len; i++ ) {
4438 this.items[ i ].setIndex( i );
4439 }
4440
4441 if ( this.orientation === 'horizontal' ) {
4442 // Set the height of the indicator
4443 this.$placeholder.css( {
4444 height: item.$element.outerHeight(),
4445 width: 2
4446 } );
4447 } else {
4448 // Set the width of the indicator
4449 this.$placeholder.css( {
4450 height: 2,
4451 width: item.$element.outerWidth()
4452 } );
4453 }
4454 this.setDragItem( item );
4455 };
4456
4457 /**
4458 * Respond to item drag end event
4459 */
4460 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4461 this.unsetDragItem();
4462 return false;
4463 };
4464
4465 /**
4466 * Handle drop event and switch the order of the items accordingly
4467 * @param {OO.ui.DraggableElement} item Dropped item
4468 * @fires reorder
4469 */
4470 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4471 var toIndex = item.getIndex();
4472 // Check if the dropped item is from the current group
4473 // TODO: Figure out a way to configure a list of legally droppable
4474 // elements even if they are not yet in the list
4475 if ( this.getDragItem() ) {
4476 // If the insertion point is 'after', the insertion index
4477 // is shifted to the right (or to the left in RTL, hence 'after')
4478 if ( this.sideInsertion === 'after' ) {
4479 toIndex++;
4480 }
4481 // Emit change event
4482 this.emit( 'reorder', this.getDragItem(), toIndex );
4483 }
4484 // Return false to prevent propogation
4485 return false;
4486 };
4487
4488 /**
4489 * Handle dragleave event.
4490 */
4491 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4492 // This means the item was dragged outside the widget
4493 this.$placeholder
4494 .css( 'left', 0 )
4495 .hide();
4496 };
4497
4498 /**
4499 * Respond to dragover event
4500 * @param {jQuery.Event} event Event details
4501 */
4502 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4503 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4504 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4505 clientX = e.originalEvent.clientX,
4506 clientY = e.originalEvent.clientY;
4507
4508 // Get the OptionWidget item we are dragging over
4509 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4510 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4511 if ( $optionWidget[ 0 ] ) {
4512 itemOffset = $optionWidget.offset();
4513 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4514 itemPosition = $optionWidget.position();
4515 itemIndex = $optionWidget.data( 'index' );
4516 }
4517
4518 if (
4519 itemOffset &&
4520 this.isDragging() &&
4521 itemIndex !== this.getDragItem().getIndex()
4522 ) {
4523 if ( this.orientation === 'horizontal' ) {
4524 // Calculate where the mouse is relative to the item width
4525 itemSize = itemBoundingRect.width;
4526 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4527 dragPosition = clientX;
4528 // Which side of the item we hover over will dictate
4529 // where the placeholder will appear, on the left or
4530 // on the right
4531 cssOutput = {
4532 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4533 top: itemPosition.top
4534 };
4535 } else {
4536 // Calculate where the mouse is relative to the item height
4537 itemSize = itemBoundingRect.height;
4538 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4539 dragPosition = clientY;
4540 // Which side of the item we hover over will dictate
4541 // where the placeholder will appear, on the top or
4542 // on the bottom
4543 cssOutput = {
4544 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4545 left: itemPosition.left
4546 };
4547 }
4548 // Store whether we are before or after an item to rearrange
4549 // For horizontal layout, we need to account for RTL, as this is flipped
4550 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4551 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4552 } else {
4553 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4554 }
4555 // Add drop indicator between objects
4556 if ( this.sideInsertion ) {
4557 this.$placeholder
4558 .css( cssOutput )
4559 .show();
4560 } else {
4561 this.$placeholder
4562 .css( {
4563 left: 0,
4564 top: 0
4565 } )
4566 .hide();
4567 }
4568 } else {
4569 // This means the item was dragged outside the widget
4570 this.$placeholder
4571 .css( 'left', 0 )
4572 .hide();
4573 }
4574 // Prevent default
4575 e.preventDefault();
4576 };
4577
4578 /**
4579 * Set a dragged item
4580 * @param {OO.ui.DraggableElement} item Dragged item
4581 */
4582 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4583 this.dragItem = item;
4584 };
4585
4586 /**
4587 * Unset the current dragged item
4588 */
4589 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4590 this.dragItem = null;
4591 this.itemDragOver = null;
4592 this.$placeholder.hide();
4593 this.sideInsertion = '';
4594 };
4595
4596 /**
4597 * Get the current dragged item
4598 * @return {OO.ui.DraggableElement|null} item Dragged item or null if no item is dragged
4599 */
4600 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4601 return this.dragItem;
4602 };
4603
4604 /**
4605 * Check if there's an item being dragged.
4606 * @return {Boolean} Item is being dragged
4607 */
4608 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4609 return this.getDragItem() !== null;
4610 };
4611
4612 /**
4613 * Element containing an icon.
4614 *
4615 * Icons are graphics, about the size of normal text. They can be used to aid the user in locating
4616 * a control or convey information in a more space efficient way. Icons should rarely be used
4617 * without labels; such as in a toolbar where space is at a premium or within a context where the
4618 * meaning is very clear to the user.
4619 *
4620 * @abstract
4621 * @class
4622 *
4623 * @constructor
4624 * @param {Object} [config] Configuration options
4625 * @cfg {jQuery} [$icon] Icon node, assigned to #$icon, omit to use a generated `<span>`
4626 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
4627 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4628 * language
4629 * @cfg {string} [iconTitle] Icon title text or a function that returns text
4630 */
4631 OO.ui.IconElement = function OoUiIconElement( config ) {
4632 // Configuration initialization
4633 config = config || {};
4634
4635 // Properties
4636 this.$icon = null;
4637 this.icon = null;
4638 this.iconTitle = null;
4639
4640 // Initialization
4641 this.setIcon( config.icon || this.constructor.static.icon );
4642 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4643 this.setIconElement( config.$icon || this.$( '<span>' ) );
4644 };
4645
4646 /* Setup */
4647
4648 OO.initClass( OO.ui.IconElement );
4649
4650 /* Static Properties */
4651
4652 /**
4653 * Icon.
4654 *
4655 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
4656 *
4657 * For i18n purposes, this property can be an object containing a `default` icon name property and
4658 * additional icon names keyed by language code.
4659 *
4660 * Example of i18n icon definition:
4661 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4662 *
4663 * @static
4664 * @inheritable
4665 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
4666 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4667 * language
4668 */
4669 OO.ui.IconElement.static.icon = null;
4670
4671 /**
4672 * Icon title.
4673 *
4674 * @static
4675 * @inheritable
4676 * @property {string|Function|null} Icon title text, a function that returns text or null for no
4677 * icon title
4678 */
4679 OO.ui.IconElement.static.iconTitle = null;
4680
4681 /* Methods */
4682
4683 /**
4684 * Set the icon element.
4685 *
4686 * If an element is already set, it will be cleaned up before setting up the new element.
4687 *
4688 * @param {jQuery} $icon Element to use as icon
4689 */
4690 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
4691 if ( this.$icon ) {
4692 this.$icon
4693 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
4694 .removeAttr( 'title' );
4695 }
4696
4697 this.$icon = $icon
4698 .addClass( 'oo-ui-iconElement-icon' )
4699 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
4700 if ( this.iconTitle !== null ) {
4701 this.$icon.attr( 'title', this.iconTitle );
4702 }
4703 };
4704
4705 /**
4706 * Set icon name.
4707 *
4708 * @param {Object|string|null} icon Symbolic icon name, or map of icon names keyed by language ID;
4709 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4710 * language, use null to remove icon
4711 * @chainable
4712 */
4713 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
4714 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
4715 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
4716
4717 if ( this.icon !== icon ) {
4718 if ( this.$icon ) {
4719 if ( this.icon !== null ) {
4720 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
4721 }
4722 if ( icon !== null ) {
4723 this.$icon.addClass( 'oo-ui-icon-' + icon );
4724 }
4725 }
4726 this.icon = icon;
4727 }
4728
4729 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
4730 this.updateThemeClasses();
4731
4732 return this;
4733 };
4734
4735 /**
4736 * Set icon title.
4737 *
4738 * @param {string|Function|null} icon Icon title text, a function that returns text or null
4739 * for no icon title
4740 * @chainable
4741 */
4742 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
4743 iconTitle = typeof iconTitle === 'function' ||
4744 ( typeof iconTitle === 'string' && iconTitle.length ) ?
4745 OO.ui.resolveMsg( iconTitle ) : null;
4746
4747 if ( this.iconTitle !== iconTitle ) {
4748 this.iconTitle = iconTitle;
4749 if ( this.$icon ) {
4750 if ( this.iconTitle !== null ) {
4751 this.$icon.attr( 'title', iconTitle );
4752 } else {
4753 this.$icon.removeAttr( 'title' );
4754 }
4755 }
4756 }
4757
4758 return this;
4759 };
4760
4761 /**
4762 * Get icon name.
4763 *
4764 * @return {string} Icon name
4765 */
4766 OO.ui.IconElement.prototype.getIcon = function () {
4767 return this.icon;
4768 };
4769
4770 /**
4771 * Get icon title.
4772 *
4773 * @return {string} Icon title text
4774 */
4775 OO.ui.IconElement.prototype.getIconTitle = function () {
4776 return this.iconTitle;
4777 };
4778
4779 /**
4780 * Element containing an indicator.
4781 *
4782 * Indicators are graphics, smaller than normal text. They can be used to describe unique status or
4783 * behavior. Indicators should only be used in exceptional cases; such as a button that opens a menu
4784 * instead of performing an action directly, or an item in a list which has errors that need to be
4785 * resolved.
4786 *
4787 * @abstract
4788 * @class
4789 *
4790 * @constructor
4791 * @param {Object} [config] Configuration options
4792 * @cfg {jQuery} [$indicator] Indicator node, assigned to #$indicator, omit to use a generated
4793 * `<span>`
4794 * @cfg {string} [indicator] Symbolic indicator name
4795 * @cfg {string} [indicatorTitle] Indicator title text or a function that returns text
4796 */
4797 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
4798 // Configuration initialization
4799 config = config || {};
4800
4801 // Properties
4802 this.$indicator = null;
4803 this.indicator = null;
4804 this.indicatorTitle = null;
4805
4806 // Initialization
4807 this.setIndicator( config.indicator || this.constructor.static.indicator );
4808 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4809 this.setIndicatorElement( config.$indicator || this.$( '<span>' ) );
4810 };
4811
4812 /* Setup */
4813
4814 OO.initClass( OO.ui.IndicatorElement );
4815
4816 /* Static Properties */
4817
4818 /**
4819 * indicator.
4820 *
4821 * @static
4822 * @inheritable
4823 * @property {string|null} Symbolic indicator name
4824 */
4825 OO.ui.IndicatorElement.static.indicator = null;
4826
4827 /**
4828 * Indicator title.
4829 *
4830 * @static
4831 * @inheritable
4832 * @property {string|Function|null} Indicator title text, a function that returns text or null for no
4833 * indicator title
4834 */
4835 OO.ui.IndicatorElement.static.indicatorTitle = null;
4836
4837 /* Methods */
4838
4839 /**
4840 * Set the indicator element.
4841 *
4842 * If an element is already set, it will be cleaned up before setting up the new element.
4843 *
4844 * @param {jQuery} $indicator Element to use as indicator
4845 */
4846 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
4847 if ( this.$indicator ) {
4848 this.$indicator
4849 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
4850 .removeAttr( 'title' );
4851 }
4852
4853 this.$indicator = $indicator
4854 .addClass( 'oo-ui-indicatorElement-indicator' )
4855 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
4856 if ( this.indicatorTitle !== null ) {
4857 this.$indicator.attr( 'title', this.indicatorTitle );
4858 }
4859 };
4860
4861 /**
4862 * Set indicator name.
4863 *
4864 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4865 * @chainable
4866 */
4867 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
4868 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
4869
4870 if ( this.indicator !== indicator ) {
4871 if ( this.$indicator ) {
4872 if ( this.indicator !== null ) {
4873 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4874 }
4875 if ( indicator !== null ) {
4876 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4877 }
4878 }
4879 this.indicator = indicator;
4880 }
4881
4882 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
4883 this.updateThemeClasses();
4884
4885 return this;
4886 };
4887
4888 /**
4889 * Set indicator title.
4890 *
4891 * @param {string|Function|null} indicator Indicator title text, a function that returns text or
4892 * null for no indicator title
4893 * @chainable
4894 */
4895 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4896 indicatorTitle = typeof indicatorTitle === 'function' ||
4897 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
4898 OO.ui.resolveMsg( indicatorTitle ) : null;
4899
4900 if ( this.indicatorTitle !== indicatorTitle ) {
4901 this.indicatorTitle = indicatorTitle;
4902 if ( this.$indicator ) {
4903 if ( this.indicatorTitle !== null ) {
4904 this.$indicator.attr( 'title', indicatorTitle );
4905 } else {
4906 this.$indicator.removeAttr( 'title' );
4907 }
4908 }
4909 }
4910
4911 return this;
4912 };
4913
4914 /**
4915 * Get indicator name.
4916 *
4917 * @return {string} Symbolic name of indicator
4918 */
4919 OO.ui.IndicatorElement.prototype.getIndicator = function () {
4920 return this.indicator;
4921 };
4922
4923 /**
4924 * Get indicator title.
4925 *
4926 * @return {string} Indicator title text
4927 */
4928 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
4929 return this.indicatorTitle;
4930 };
4931
4932 /**
4933 * Element containing a label.
4934 *
4935 * @abstract
4936 * @class
4937 *
4938 * @constructor
4939 * @param {Object} [config] Configuration options
4940 * @cfg {jQuery} [$label] Label node, assigned to #$label, omit to use a generated `<span>`
4941 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
4942 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
4943 */
4944 OO.ui.LabelElement = function OoUiLabelElement( config ) {
4945 // Configuration initialization
4946 config = config || {};
4947
4948 // Properties
4949 this.$label = null;
4950 this.label = null;
4951 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
4952
4953 // Initialization
4954 this.setLabel( config.label || this.constructor.static.label );
4955 this.setLabelElement( config.$label || this.$( '<span>' ) );
4956 };
4957
4958 /* Setup */
4959
4960 OO.initClass( OO.ui.LabelElement );
4961
4962 /* Events */
4963
4964 /**
4965 * @event labelChange
4966 * @param {string} value
4967 */
4968
4969 /* Static Properties */
4970
4971 /**
4972 * Label.
4973 *
4974 * @static
4975 * @inheritable
4976 * @property {string|Function|null} Label text; a function that returns nodes or text; or null for
4977 * no label
4978 */
4979 OO.ui.LabelElement.static.label = null;
4980
4981 /* Methods */
4982
4983 /**
4984 * Set the label element.
4985 *
4986 * If an element is already set, it will be cleaned up before setting up the new element.
4987 *
4988 * @param {jQuery} $label Element to use as label
4989 */
4990 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
4991 if ( this.$label ) {
4992 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
4993 }
4994
4995 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
4996 this.setLabelContent( this.label );
4997 };
4998
4999 /**
5000 * Set the label.
5001 *
5002 * An empty string will result in the label being hidden. A string containing only whitespace will
5003 * be converted to a single `&nbsp;`.
5004 *
5005 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5006 * text; or null for no label
5007 * @chainable
5008 */
5009 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5010 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5011 label = ( typeof label === 'string' && label.length ) || label instanceof jQuery ? label : null;
5012
5013 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5014
5015 if ( this.label !== label ) {
5016 if ( this.$label ) {
5017 this.setLabelContent( label );
5018 }
5019 this.label = label;
5020 this.emit( 'labelChange' );
5021 }
5022
5023 return this;
5024 };
5025
5026 /**
5027 * Get the label.
5028 *
5029 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5030 * text; or null for no label
5031 */
5032 OO.ui.LabelElement.prototype.getLabel = function () {
5033 return this.label;
5034 };
5035
5036 /**
5037 * Fit the label.
5038 *
5039 * @chainable
5040 */
5041 OO.ui.LabelElement.prototype.fitLabel = function () {
5042 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5043 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5044 }
5045
5046 return this;
5047 };
5048
5049 /**
5050 * Set the content of the label.
5051 *
5052 * Do not call this method until after the label element has been set by #setLabelElement.
5053 *
5054 * @private
5055 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5056 * text; or null for no label
5057 */
5058 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5059 if ( typeof label === 'string' ) {
5060 if ( label.match( /^\s*$/ ) ) {
5061 // Convert whitespace only string to a single non-breaking space
5062 this.$label.html( '&nbsp;' );
5063 } else {
5064 this.$label.text( label );
5065 }
5066 } else if ( label instanceof jQuery ) {
5067 this.$label.empty().append( label );
5068 } else {
5069 this.$label.empty();
5070 }
5071 };
5072
5073 /**
5074 * Mixin that adds a menu showing suggested values for a OO.ui.TextInputWidget.
5075 *
5076 * Subclasses that set the value of #lookupInput from #onLookupMenuItemChoose should
5077 * be aware that this will cause new suggestions to be looked up for the new value. If this is
5078 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
5079 *
5080 * @class
5081 * @abstract
5082 *
5083 * @constructor
5084 * @param {Object} [config] Configuration options
5085 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
5086 * @cfg {jQuery} [$container=this.$element] Element to render menu under
5087 */
5088 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5089 // Configuration initialization
5090 config = config || {};
5091
5092 // Properties
5093 this.$overlay = config.$overlay || this.$element;
5094 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5095 $: OO.ui.Element.static.getJQuery( this.$overlay ),
5096 $container: config.$container
5097 } );
5098 this.lookupCache = {};
5099 this.lookupQuery = null;
5100 this.lookupRequest = null;
5101 this.lookupsDisabled = false;
5102 this.lookupInputFocused = false;
5103
5104 // Events
5105 this.$input.on( {
5106 focus: this.onLookupInputFocus.bind( this ),
5107 blur: this.onLookupInputBlur.bind( this ),
5108 mousedown: this.onLookupInputMouseDown.bind( this )
5109 } );
5110 this.connect( this, { change: 'onLookupInputChange' } );
5111 this.lookupMenu.connect( this, {
5112 toggle: 'onLookupMenuToggle',
5113 choose: 'onLookupMenuItemChoose'
5114 } );
5115
5116 // Initialization
5117 this.$element.addClass( 'oo-ui-lookupElement' );
5118 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5119 this.$overlay.append( this.lookupMenu.$element );
5120 };
5121
5122 /* Methods */
5123
5124 /**
5125 * Handle input focus event.
5126 *
5127 * @param {jQuery.Event} e Input focus event
5128 */
5129 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5130 this.lookupInputFocused = true;
5131 this.populateLookupMenu();
5132 };
5133
5134 /**
5135 * Handle input blur event.
5136 *
5137 * @param {jQuery.Event} e Input blur event
5138 */
5139 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5140 this.closeLookupMenu();
5141 this.lookupInputFocused = false;
5142 };
5143
5144 /**
5145 * Handle input mouse down event.
5146 *
5147 * @param {jQuery.Event} e Input mouse down event
5148 */
5149 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5150 // Only open the menu if the input was already focused.
5151 // This way we allow the user to open the menu again after closing it with Esc
5152 // by clicking in the input. Opening (and populating) the menu when initially
5153 // clicking into the input is handled by the focus handler.
5154 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5155 this.populateLookupMenu();
5156 }
5157 };
5158
5159 /**
5160 * Handle input change event.
5161 *
5162 * @param {string} value New input value
5163 */
5164 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5165 if ( this.lookupInputFocused ) {
5166 this.populateLookupMenu();
5167 }
5168 };
5169
5170 /**
5171 * Handle the lookup menu being shown/hidden.
5172 *
5173 * @param {boolean} visible Whether the lookup menu is now visible.
5174 */
5175 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5176 if ( !visible ) {
5177 // When the menu is hidden, abort any active request and clear the menu.
5178 // This has to be done here in addition to closeLookupMenu(), because
5179 // MenuSelectWidget will close itself when the user presses Esc.
5180 this.abortLookupRequest();
5181 this.lookupMenu.clearItems();
5182 }
5183 };
5184
5185 /**
5186 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5187 *
5188 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5189 */
5190 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5191 if ( item ) {
5192 this.setValue( item.getData() );
5193 }
5194 };
5195
5196 /**
5197 * Get lookup menu.
5198 *
5199 * @return {OO.ui.TextInputMenuSelectWidget}
5200 */
5201 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5202 return this.lookupMenu;
5203 };
5204
5205 /**
5206 * Disable or re-enable lookups.
5207 *
5208 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5209 *
5210 * @param {boolean} disabled Disable lookups
5211 */
5212 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5213 this.lookupsDisabled = !!disabled;
5214 };
5215
5216 /**
5217 * Open the menu. If there are no entries in the menu, this does nothing.
5218 *
5219 * @chainable
5220 */
5221 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5222 if ( !this.lookupMenu.isEmpty() ) {
5223 this.lookupMenu.toggle( true );
5224 }
5225 return this;
5226 };
5227
5228 /**
5229 * Close the menu, empty it, and abort any pending request.
5230 *
5231 * @chainable
5232 */
5233 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5234 this.lookupMenu.toggle( false );
5235 this.abortLookupRequest();
5236 this.lookupMenu.clearItems();
5237 return this;
5238 };
5239
5240 /**
5241 * Request menu items based on the input's current value, and when they arrive,
5242 * populate the menu with these items and show the menu.
5243 *
5244 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5245 *
5246 * @chainable
5247 */
5248 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5249 var widget = this,
5250 value = this.getValue();
5251
5252 if ( this.lookupsDisabled ) {
5253 return;
5254 }
5255
5256 // If the input is empty, clear the menu
5257 if ( value === '' ) {
5258 this.closeLookupMenu();
5259 // Skip population if there is already a request pending for the current value
5260 } else if ( value !== this.lookupQuery ) {
5261 this.getLookupMenuItems()
5262 .done( function ( items ) {
5263 widget.lookupMenu.clearItems();
5264 if ( items.length ) {
5265 widget.lookupMenu
5266 .addItems( items )
5267 .toggle( true );
5268 widget.initializeLookupMenuSelection();
5269 } else {
5270 widget.lookupMenu.toggle( false );
5271 }
5272 } )
5273 .fail( function () {
5274 widget.lookupMenu.clearItems();
5275 } );
5276 }
5277
5278 return this;
5279 };
5280
5281 /**
5282 * Select and highlight the first selectable item in the menu.
5283 *
5284 * @chainable
5285 */
5286 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5287 if ( !this.lookupMenu.getSelectedItem() ) {
5288 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5289 }
5290 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5291 };
5292
5293 /**
5294 * Get lookup menu items for the current query.
5295 *
5296 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5297 * the done event. If the request was aborted to make way for a subsequent request, this promise
5298 * will not be rejected: it will remain pending forever.
5299 */
5300 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5301 var widget = this,
5302 value = this.getValue(),
5303 deferred = $.Deferred(),
5304 ourRequest;
5305
5306 this.abortLookupRequest();
5307 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5308 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5309 } else {
5310 this.pushPending();
5311 this.lookupQuery = value;
5312 ourRequest = this.lookupRequest = this.getLookupRequest();
5313 ourRequest
5314 .always( function () {
5315 // We need to pop pending even if this is an old request, otherwise
5316 // the widget will remain pending forever.
5317 // TODO: this assumes that an aborted request will fail or succeed soon after
5318 // being aborted, or at least eventually. It would be nice if we could popPending()
5319 // at abort time, but only if we knew that we hadn't already called popPending()
5320 // for that request.
5321 widget.popPending();
5322 } )
5323 .done( function ( data ) {
5324 // If this is an old request (and aborting it somehow caused it to still succeed),
5325 // ignore its success completely
5326 if ( ourRequest === widget.lookupRequest ) {
5327 widget.lookupQuery = null;
5328 widget.lookupRequest = null;
5329 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( data );
5330 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5331 }
5332 } )
5333 .fail( function () {
5334 // If this is an old request (or a request failing because it's being aborted),
5335 // ignore its failure completely
5336 if ( ourRequest === widget.lookupRequest ) {
5337 widget.lookupQuery = null;
5338 widget.lookupRequest = null;
5339 deferred.reject();
5340 }
5341 } );
5342 }
5343 return deferred.promise();
5344 };
5345
5346 /**
5347 * Abort the currently pending lookup request, if any.
5348 */
5349 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5350 var oldRequest = this.lookupRequest;
5351 if ( oldRequest ) {
5352 // First unset this.lookupRequest to the fail handler will notice
5353 // that the request is no longer current
5354 this.lookupRequest = null;
5355 this.lookupQuery = null;
5356 oldRequest.abort();
5357 }
5358 };
5359
5360 /**
5361 * Get a new request object of the current lookup query value.
5362 *
5363 * @abstract
5364 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5365 */
5366 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5367 // Stub, implemented in subclass
5368 return null;
5369 };
5370
5371 /**
5372 * Pre-process data returned by the request from #getLookupRequest.
5373 *
5374 * The return value of this function will be cached, and any further queries for the given value
5375 * will use the cache rather than doing API requests.
5376 *
5377 * @abstract
5378 * @param {Mixed} data Response from server
5379 * @return {Mixed} Cached result data
5380 */
5381 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5382 // Stub, implemented in subclass
5383 return [];
5384 };
5385
5386 /**
5387 * Get a list of menu option widgets from the (possibly cached) data returned by
5388 * #getLookupCacheDataFromResponse.
5389 *
5390 * @abstract
5391 * @param {Mixed} data Cached result data, usually an array
5392 * @return {OO.ui.MenuOptionWidget[]} Menu items
5393 */
5394 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5395 // Stub, implemented in subclass
5396 return [];
5397 };
5398
5399 /**
5400 * Element containing an OO.ui.PopupWidget object.
5401 *
5402 * @abstract
5403 * @class
5404 *
5405 * @constructor
5406 * @param {Object} [config] Configuration options
5407 * @cfg {Object} [popup] Configuration to pass to popup
5408 * @cfg {boolean} [autoClose=true] Popup auto-closes when it loses focus
5409 */
5410 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5411 // Configuration initialization
5412 config = config || {};
5413
5414 // Properties
5415 this.popup = new OO.ui.PopupWidget( $.extend(
5416 { autoClose: true },
5417 config.popup,
5418 { $: this.$, $autoCloseIgnore: this.$element }
5419 ) );
5420 };
5421
5422 /* Methods */
5423
5424 /**
5425 * Get popup.
5426 *
5427 * @return {OO.ui.PopupWidget} Popup widget
5428 */
5429 OO.ui.PopupElement.prototype.getPopup = function () {
5430 return this.popup;
5431 };
5432
5433 /**
5434 * Element with named flags that can be added, removed, listed and checked.
5435 *
5436 * A flag, when set, adds a CSS class on the `$element` by combining `oo-ui-flaggedElement-` with
5437 * the flag name. Flags are primarily useful for styling.
5438 *
5439 * @abstract
5440 * @class
5441 *
5442 * @constructor
5443 * @param {Object} [config] Configuration options
5444 * @cfg {string|string[]} [flags] Flags describing importance and functionality, e.g. 'primary',
5445 * 'safe', 'progressive', 'destructive' or 'constructive'
5446 * @cfg {jQuery} [$flagged] Flagged node, assigned to #$flagged, omit to use #$element
5447 */
5448 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5449 // Configuration initialization
5450 config = config || {};
5451
5452 // Properties
5453 this.flags = {};
5454 this.$flagged = null;
5455
5456 // Initialization
5457 this.setFlags( config.flags );
5458 this.setFlaggedElement( config.$flagged || this.$element );
5459 };
5460
5461 /* Events */
5462
5463 /**
5464 * @event flag
5465 * @param {Object.<string,boolean>} changes Object keyed by flag name containing boolean
5466 * added/removed properties
5467 */
5468
5469 /* Methods */
5470
5471 /**
5472 * Set the flagged element.
5473 *
5474 * If an element is already set, it will be cleaned up before setting up the new element.
5475 *
5476 * @param {jQuery} $flagged Element to add flags to
5477 */
5478 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5479 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5480 return 'oo-ui-flaggedElement-' + flag;
5481 } ).join( ' ' );
5482
5483 if ( this.$flagged ) {
5484 this.$flagged.removeClass( classNames );
5485 }
5486
5487 this.$flagged = $flagged.addClass( classNames );
5488 };
5489
5490 /**
5491 * Check if a flag is set.
5492 *
5493 * @param {string} flag Name of flag
5494 * @return {boolean} Has flag
5495 */
5496 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5497 return flag in this.flags;
5498 };
5499
5500 /**
5501 * Get the names of all flags set.
5502 *
5503 * @return {string[]} Flag names
5504 */
5505 OO.ui.FlaggedElement.prototype.getFlags = function () {
5506 return Object.keys( this.flags );
5507 };
5508
5509 /**
5510 * Clear all flags.
5511 *
5512 * @chainable
5513 * @fires flag
5514 */
5515 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5516 var flag, className,
5517 changes = {},
5518 remove = [],
5519 classPrefix = 'oo-ui-flaggedElement-';
5520
5521 for ( flag in this.flags ) {
5522 className = classPrefix + flag;
5523 changes[ flag ] = false;
5524 delete this.flags[ flag ];
5525 remove.push( className );
5526 }
5527
5528 if ( this.$flagged ) {
5529 this.$flagged.removeClass( remove.join( ' ' ) );
5530 }
5531
5532 this.updateThemeClasses();
5533 this.emit( 'flag', changes );
5534
5535 return this;
5536 };
5537
5538 /**
5539 * Add one or more flags.
5540 *
5541 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
5542 * keyed by flag name containing boolean set/remove instructions.
5543 * @chainable
5544 * @fires flag
5545 */
5546 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5547 var i, len, flag, className,
5548 changes = {},
5549 add = [],
5550 remove = [],
5551 classPrefix = 'oo-ui-flaggedElement-';
5552
5553 if ( typeof flags === 'string' ) {
5554 className = classPrefix + flags;
5555 // Set
5556 if ( !this.flags[ flags ] ) {
5557 this.flags[ flags ] = true;
5558 add.push( className );
5559 }
5560 } else if ( $.isArray( flags ) ) {
5561 for ( i = 0, len = flags.length; i < len; i++ ) {
5562 flag = flags[ i ];
5563 className = classPrefix + flag;
5564 // Set
5565 if ( !this.flags[ flag ] ) {
5566 changes[ flag ] = true;
5567 this.flags[ flag ] = true;
5568 add.push( className );
5569 }
5570 }
5571 } else if ( OO.isPlainObject( flags ) ) {
5572 for ( flag in flags ) {
5573 className = classPrefix + flag;
5574 if ( flags[ flag ] ) {
5575 // Set
5576 if ( !this.flags[ flag ] ) {
5577 changes[ flag ] = true;
5578 this.flags[ flag ] = true;
5579 add.push( className );
5580 }
5581 } else {
5582 // Remove
5583 if ( this.flags[ flag ] ) {
5584 changes[ flag ] = false;
5585 delete this.flags[ flag ];
5586 remove.push( className );
5587 }
5588 }
5589 }
5590 }
5591
5592 if ( this.$flagged ) {
5593 this.$flagged
5594 .addClass( add.join( ' ' ) )
5595 .removeClass( remove.join( ' ' ) );
5596 }
5597
5598 this.updateThemeClasses();
5599 this.emit( 'flag', changes );
5600
5601 return this;
5602 };
5603
5604 /**
5605 * Element with a title.
5606 *
5607 * Titles are rendered by the browser and are made visible when hovering the element. Titles are
5608 * not visible on touch devices.
5609 *
5610 * @abstract
5611 * @class
5612 *
5613 * @constructor
5614 * @param {Object} [config] Configuration options
5615 * @cfg {jQuery} [$titled] Titled node, assigned to #$titled, omit to use #$element
5616 * @cfg {string|Function} [title] Title text or a function that returns text. If not provided, the
5617 * static property 'title' is used.
5618 */
5619 OO.ui.TitledElement = function OoUiTitledElement( config ) {
5620 // Configuration initialization
5621 config = config || {};
5622
5623 // Properties
5624 this.$titled = null;
5625 this.title = null;
5626
5627 // Initialization
5628 this.setTitle( config.title || this.constructor.static.title );
5629 this.setTitledElement( config.$titled || this.$element );
5630 };
5631
5632 /* Setup */
5633
5634 OO.initClass( OO.ui.TitledElement );
5635
5636 /* Static Properties */
5637
5638 /**
5639 * Title.
5640 *
5641 * @static
5642 * @inheritable
5643 * @property {string|Function} Title text or a function that returns text
5644 */
5645 OO.ui.TitledElement.static.title = null;
5646
5647 /* Methods */
5648
5649 /**
5650 * Set the titled element.
5651 *
5652 * If an element is already set, it will be cleaned up before setting up the new element.
5653 *
5654 * @param {jQuery} $titled Element to set title on
5655 */
5656 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
5657 if ( this.$titled ) {
5658 this.$titled.removeAttr( 'title' );
5659 }
5660
5661 this.$titled = $titled;
5662 if ( this.title ) {
5663 this.$titled.attr( 'title', this.title );
5664 }
5665 };
5666
5667 /**
5668 * Set title.
5669 *
5670 * @param {string|Function|null} title Title text, a function that returns text or null for no title
5671 * @chainable
5672 */
5673 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
5674 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
5675
5676 if ( this.title !== title ) {
5677 if ( this.$titled ) {
5678 if ( title !== null ) {
5679 this.$titled.attr( 'title', title );
5680 } else {
5681 this.$titled.removeAttr( 'title' );
5682 }
5683 }
5684 this.title = title;
5685 }
5686
5687 return this;
5688 };
5689
5690 /**
5691 * Get title.
5692 *
5693 * @return {string} Title string
5694 */
5695 OO.ui.TitledElement.prototype.getTitle = function () {
5696 return this.title;
5697 };
5698
5699 /**
5700 * Element that can be automatically clipped to visible boundaries.
5701 *
5702 * Whenever the element's natural height changes, you have to call
5703 * #clip to make sure it's still clipping correctly.
5704 *
5705 * @abstract
5706 * @class
5707 *
5708 * @constructor
5709 * @param {Object} [config] Configuration options
5710 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
5711 */
5712 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
5713 // Configuration initialization
5714 config = config || {};
5715
5716 // Properties
5717 this.$clippable = null;
5718 this.clipping = false;
5719 this.clippedHorizontally = false;
5720 this.clippedVertically = false;
5721 this.$clippableContainer = null;
5722 this.$clippableScroller = null;
5723 this.$clippableWindow = null;
5724 this.idealWidth = null;
5725 this.idealHeight = null;
5726 this.onClippableContainerScrollHandler = this.clip.bind( this );
5727 this.onClippableWindowResizeHandler = this.clip.bind( this );
5728
5729 // Initialization
5730 this.setClippableElement( config.$clippable || this.$element );
5731 };
5732
5733 /* Methods */
5734
5735 /**
5736 * Set clippable element.
5737 *
5738 * If an element is already set, it will be cleaned up before setting up the new element.
5739 *
5740 * @param {jQuery} $clippable Element to make clippable
5741 */
5742 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
5743 if ( this.$clippable ) {
5744 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
5745 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
5746 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5747 }
5748
5749 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
5750 this.clip();
5751 };
5752
5753 /**
5754 * Toggle clipping.
5755 *
5756 * Do not turn clipping on until after the element is attached to the DOM and visible.
5757 *
5758 * @param {boolean} [clipping] Enable clipping, omit to toggle
5759 * @chainable
5760 */
5761 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
5762 clipping = clipping === undefined ? !this.clipping : !!clipping;
5763
5764 if ( this.clipping !== clipping ) {
5765 this.clipping = clipping;
5766 if ( clipping ) {
5767 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
5768 // If the clippable container is the root, we have to listen to scroll events and check
5769 // jQuery.scrollTop on the window because of browser inconsistencies
5770 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
5771 this.$( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
5772 this.$clippableContainer;
5773 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
5774 this.$clippableWindow = this.$( this.getElementWindow() )
5775 .on( 'resize', this.onClippableWindowResizeHandler );
5776 // Initial clip after visible
5777 this.clip();
5778 } else {
5779 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
5780 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5781
5782 this.$clippableContainer = null;
5783 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
5784 this.$clippableScroller = null;
5785 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
5786 this.$clippableWindow = null;
5787 }
5788 }
5789
5790 return this;
5791 };
5792
5793 /**
5794 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
5795 *
5796 * @return {boolean} Element will be clipped to the visible area
5797 */
5798 OO.ui.ClippableElement.prototype.isClipping = function () {
5799 return this.clipping;
5800 };
5801
5802 /**
5803 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
5804 *
5805 * @return {boolean} Part of the element is being clipped
5806 */
5807 OO.ui.ClippableElement.prototype.isClipped = function () {
5808 return this.clippedHorizontally || this.clippedVertically;
5809 };
5810
5811 /**
5812 * Check if the right of the element is being clipped by the nearest scrollable container.
5813 *
5814 * @return {boolean} Part of the element is being clipped
5815 */
5816 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
5817 return this.clippedHorizontally;
5818 };
5819
5820 /**
5821 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5822 *
5823 * @return {boolean} Part of the element is being clipped
5824 */
5825 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
5826 return this.clippedVertically;
5827 };
5828
5829 /**
5830 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
5831 *
5832 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5833 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5834 */
5835 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
5836 this.idealWidth = width;
5837 this.idealHeight = height;
5838
5839 if ( !this.clipping ) {
5840 // Update dimensions
5841 this.$clippable.css( { width: width, height: height } );
5842 }
5843 // While clipping, idealWidth and idealHeight are not considered
5844 };
5845
5846 /**
5847 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
5848 * the element's natural height changes.
5849 *
5850 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5851 * overlapped by, the visible area of the nearest scrollable container.
5852 *
5853 * @chainable
5854 */
5855 OO.ui.ClippableElement.prototype.clip = function () {
5856 if ( !this.clipping ) {
5857 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
5858 return this;
5859 }
5860
5861 var buffer = 7, // Chosen by fair dice roll
5862 cOffset = this.$clippable.offset(),
5863 $container = this.$clippableContainer.is( 'html, body' ) ?
5864 this.$clippableWindow : this.$clippableContainer,
5865 ccOffset = $container.offset() || { top: 0, left: 0 },
5866 ccHeight = $container.innerHeight() - buffer,
5867 ccWidth = $container.innerWidth() - buffer,
5868 cHeight = this.$clippable.outerHeight() + buffer,
5869 cWidth = this.$clippable.outerWidth() + buffer,
5870 scrollTop = this.$clippableScroller.scrollTop(),
5871 scrollLeft = this.$clippableScroller.scrollLeft(),
5872 desiredWidth = cOffset.left < 0 ?
5873 cWidth + cOffset.left :
5874 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
5875 desiredHeight = cOffset.top < 0 ?
5876 cHeight + cOffset.top :
5877 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
5878 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
5879 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
5880 clipWidth = desiredWidth < naturalWidth,
5881 clipHeight = desiredHeight < naturalHeight;
5882
5883 if ( clipWidth ) {
5884 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
5885 } else {
5886 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
5887 }
5888 if ( clipHeight ) {
5889 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
5890 } else {
5891 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
5892 }
5893
5894 // If we stopped clipping in at least one of the dimensions
5895 if ( !clipWidth || !clipHeight ) {
5896 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5897 }
5898
5899 this.clippedHorizontally = clipWidth;
5900 this.clippedVertically = clipHeight;
5901
5902 return this;
5903 };
5904
5905 /**
5906 * Generic toolbar tool.
5907 *
5908 * @abstract
5909 * @class
5910 * @extends OO.ui.Widget
5911 * @mixins OO.ui.IconElement
5912 * @mixins OO.ui.FlaggedElement
5913 *
5914 * @constructor
5915 * @param {OO.ui.ToolGroup} toolGroup
5916 * @param {Object} [config] Configuration options
5917 * @cfg {string|Function} [title] Title text or a function that returns text
5918 */
5919 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
5920 // Configuration initialization
5921 config = config || {};
5922
5923 // Parent constructor
5924 OO.ui.Tool.super.call( this, config );
5925
5926 // Mixin constructors
5927 OO.ui.IconElement.call( this, config );
5928 OO.ui.FlaggedElement.call( this, config );
5929
5930 // Properties
5931 this.toolGroup = toolGroup;
5932 this.toolbar = this.toolGroup.getToolbar();
5933 this.active = false;
5934 this.$title = this.$( '<span>' );
5935 this.$accel = this.$( '<span>' );
5936 this.$link = this.$( '<a>' );
5937 this.title = null;
5938
5939 // Events
5940 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
5941
5942 // Initialization
5943 this.$title.addClass( 'oo-ui-tool-title' );
5944 this.$accel
5945 .addClass( 'oo-ui-tool-accel' )
5946 .prop( {
5947 // This may need to be changed if the key names are ever localized,
5948 // but for now they are essentially written in English
5949 dir: 'ltr',
5950 lang: 'en'
5951 } );
5952 this.$link
5953 .addClass( 'oo-ui-tool-link' )
5954 .append( this.$icon, this.$title, this.$accel )
5955 .prop( 'tabIndex', 0 )
5956 .attr( 'role', 'button' );
5957 this.$element
5958 .data( 'oo-ui-tool', this )
5959 .addClass(
5960 'oo-ui-tool ' + 'oo-ui-tool-name-' +
5961 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
5962 )
5963 .append( this.$link );
5964 this.setTitle( config.title || this.constructor.static.title );
5965 };
5966
5967 /* Setup */
5968
5969 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
5970 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
5971 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
5972
5973 /* Events */
5974
5975 /**
5976 * @event select
5977 */
5978
5979 /* Static Properties */
5980
5981 /**
5982 * @static
5983 * @inheritdoc
5984 */
5985 OO.ui.Tool.static.tagName = 'span';
5986
5987 /**
5988 * Symbolic name of tool.
5989 *
5990 * @abstract
5991 * @static
5992 * @inheritable
5993 * @property {string}
5994 */
5995 OO.ui.Tool.static.name = '';
5996
5997 /**
5998 * Tool group.
5999 *
6000 * @abstract
6001 * @static
6002 * @inheritable
6003 * @property {string}
6004 */
6005 OO.ui.Tool.static.group = '';
6006
6007 /**
6008 * Tool title.
6009 *
6010 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6011 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6012 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6013 * appended to the title if the tool is part of a bar tool group.
6014 *
6015 * @abstract
6016 * @static
6017 * @inheritable
6018 * @property {string|Function} Title text or a function that returns text
6019 */
6020 OO.ui.Tool.static.title = '';
6021
6022 /**
6023 * Tool can be automatically added to catch-all groups.
6024 *
6025 * @static
6026 * @inheritable
6027 * @property {boolean}
6028 */
6029 OO.ui.Tool.static.autoAddToCatchall = true;
6030
6031 /**
6032 * Tool can be automatically added to named groups.
6033 *
6034 * @static
6035 * @property {boolean}
6036 * @inheritable
6037 */
6038 OO.ui.Tool.static.autoAddToGroup = true;
6039
6040 /**
6041 * Check if this tool is compatible with given data.
6042 *
6043 * @static
6044 * @inheritable
6045 * @param {Mixed} data Data to check
6046 * @return {boolean} Tool can be used with data
6047 */
6048 OO.ui.Tool.static.isCompatibleWith = function () {
6049 return false;
6050 };
6051
6052 /* Methods */
6053
6054 /**
6055 * Handle the toolbar state being updated.
6056 *
6057 * This is an abstract method that must be overridden in a concrete subclass.
6058 *
6059 * @abstract
6060 */
6061 OO.ui.Tool.prototype.onUpdateState = function () {
6062 throw new Error(
6063 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6064 );
6065 };
6066
6067 /**
6068 * Handle the tool being selected.
6069 *
6070 * This is an abstract method that must be overridden in a concrete subclass.
6071 *
6072 * @abstract
6073 */
6074 OO.ui.Tool.prototype.onSelect = function () {
6075 throw new Error(
6076 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6077 );
6078 };
6079
6080 /**
6081 * Check if the button is active.
6082 *
6083 * @return {boolean} Button is active
6084 */
6085 OO.ui.Tool.prototype.isActive = function () {
6086 return this.active;
6087 };
6088
6089 /**
6090 * Make the button appear active or inactive.
6091 *
6092 * @param {boolean} state Make button appear active
6093 */
6094 OO.ui.Tool.prototype.setActive = function ( state ) {
6095 this.active = !!state;
6096 if ( this.active ) {
6097 this.$element.addClass( 'oo-ui-tool-active' );
6098 } else {
6099 this.$element.removeClass( 'oo-ui-tool-active' );
6100 }
6101 };
6102
6103 /**
6104 * Get the tool title.
6105 *
6106 * @param {string|Function} title Title text or a function that returns text
6107 * @chainable
6108 */
6109 OO.ui.Tool.prototype.setTitle = function ( title ) {
6110 this.title = OO.ui.resolveMsg( title );
6111 this.updateTitle();
6112 return this;
6113 };
6114
6115 /**
6116 * Get the tool title.
6117 *
6118 * @return {string} Title text
6119 */
6120 OO.ui.Tool.prototype.getTitle = function () {
6121 return this.title;
6122 };
6123
6124 /**
6125 * Get the tool's symbolic name.
6126 *
6127 * @return {string} Symbolic name of tool
6128 */
6129 OO.ui.Tool.prototype.getName = function () {
6130 return this.constructor.static.name;
6131 };
6132
6133 /**
6134 * Update the title.
6135 */
6136 OO.ui.Tool.prototype.updateTitle = function () {
6137 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6138 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6139 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6140 tooltipParts = [];
6141
6142 this.$title.text( this.title );
6143 this.$accel.text( accel );
6144
6145 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6146 tooltipParts.push( this.title );
6147 }
6148 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6149 tooltipParts.push( accel );
6150 }
6151 if ( tooltipParts.length ) {
6152 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6153 } else {
6154 this.$link.removeAttr( 'title' );
6155 }
6156 };
6157
6158 /**
6159 * Destroy tool.
6160 */
6161 OO.ui.Tool.prototype.destroy = function () {
6162 this.toolbar.disconnect( this );
6163 this.$element.remove();
6164 };
6165
6166 /**
6167 * Collection of tool groups.
6168 *
6169 * @class
6170 * @extends OO.ui.Element
6171 * @mixins OO.EventEmitter
6172 * @mixins OO.ui.GroupElement
6173 *
6174 * @constructor
6175 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6176 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6177 * @param {Object} [config] Configuration options
6178 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6179 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6180 */
6181 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6182 // Configuration initialization
6183 config = config || {};
6184
6185 // Parent constructor
6186 OO.ui.Toolbar.super.call( this, config );
6187
6188 // Mixin constructors
6189 OO.EventEmitter.call( this );
6190 OO.ui.GroupElement.call( this, config );
6191
6192 // Properties
6193 this.toolFactory = toolFactory;
6194 this.toolGroupFactory = toolGroupFactory;
6195 this.groups = [];
6196 this.tools = {};
6197 this.$bar = this.$( '<div>' );
6198 this.$actions = this.$( '<div>' );
6199 this.initialized = false;
6200
6201 // Events
6202 this.$element
6203 .add( this.$bar ).add( this.$group ).add( this.$actions )
6204 .on( 'mousedown touchstart', this.onPointerDown.bind( this ) );
6205
6206 // Initialization
6207 this.$group.addClass( 'oo-ui-toolbar-tools' );
6208 if ( config.actions ) {
6209 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6210 }
6211 this.$bar
6212 .addClass( 'oo-ui-toolbar-bar' )
6213 .append( this.$group, '<div style="clear:both"></div>' );
6214 if ( config.shadow ) {
6215 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6216 }
6217 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6218 };
6219
6220 /* Setup */
6221
6222 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6223 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6224 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6225
6226 /* Methods */
6227
6228 /**
6229 * Get the tool factory.
6230 *
6231 * @return {OO.ui.ToolFactory} Tool factory
6232 */
6233 OO.ui.Toolbar.prototype.getToolFactory = function () {
6234 return this.toolFactory;
6235 };
6236
6237 /**
6238 * Get the tool group factory.
6239 *
6240 * @return {OO.Factory} Tool group factory
6241 */
6242 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6243 return this.toolGroupFactory;
6244 };
6245
6246 /**
6247 * Handles mouse down events.
6248 *
6249 * @param {jQuery.Event} e Mouse down event
6250 */
6251 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6252 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
6253 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6254 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6255 return false;
6256 }
6257 };
6258
6259 /**
6260 * Sets up handles and preloads required information for the toolbar to work.
6261 * This must be called after it is attached to a visible document and before doing anything else.
6262 */
6263 OO.ui.Toolbar.prototype.initialize = function () {
6264 this.initialized = true;
6265 };
6266
6267 /**
6268 * Setup toolbar.
6269 *
6270 * Tools can be specified in the following ways:
6271 *
6272 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6273 * - All tools in a group: `{ group: 'group-name' }`
6274 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6275 *
6276 * @param {Object.<string,Array>} groups List of tool group configurations
6277 * @param {Array|string} [groups.include] Tools to include
6278 * @param {Array|string} [groups.exclude] Tools to exclude
6279 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6280 * @param {Array|string} [groups.demote] Tools to demote to the end
6281 */
6282 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6283 var i, len, type, group,
6284 items = [],
6285 defaultType = 'bar';
6286
6287 // Cleanup previous groups
6288 this.reset();
6289
6290 // Build out new groups
6291 for ( i = 0, len = groups.length; i < len; i++ ) {
6292 group = groups[ i ];
6293 if ( group.include === '*' ) {
6294 // Apply defaults to catch-all groups
6295 if ( group.type === undefined ) {
6296 group.type = 'list';
6297 }
6298 if ( group.label === undefined ) {
6299 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6300 }
6301 }
6302 // Check type has been registered
6303 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6304 items.push(
6305 this.getToolGroupFactory().create( type, this, $.extend( { $: this.$ }, group ) )
6306 );
6307 }
6308 this.addItems( items );
6309 };
6310
6311 /**
6312 * Remove all tools and groups from the toolbar.
6313 */
6314 OO.ui.Toolbar.prototype.reset = function () {
6315 var i, len;
6316
6317 this.groups = [];
6318 this.tools = {};
6319 for ( i = 0, len = this.items.length; i < len; i++ ) {
6320 this.items[ i ].destroy();
6321 }
6322 this.clearItems();
6323 };
6324
6325 /**
6326 * Destroys toolbar, removing event handlers and DOM elements.
6327 *
6328 * Call this whenever you are done using a toolbar.
6329 */
6330 OO.ui.Toolbar.prototype.destroy = function () {
6331 this.reset();
6332 this.$element.remove();
6333 };
6334
6335 /**
6336 * Check if tool has not been used yet.
6337 *
6338 * @param {string} name Symbolic name of tool
6339 * @return {boolean} Tool is available
6340 */
6341 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6342 return !this.tools[ name ];
6343 };
6344
6345 /**
6346 * Prevent tool from being used again.
6347 *
6348 * @param {OO.ui.Tool} tool Tool to reserve
6349 */
6350 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6351 this.tools[ tool.getName() ] = tool;
6352 };
6353
6354 /**
6355 * Allow tool to be used again.
6356 *
6357 * @param {OO.ui.Tool} tool Tool to release
6358 */
6359 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6360 delete this.tools[ tool.getName() ];
6361 };
6362
6363 /**
6364 * Get accelerator label for tool.
6365 *
6366 * This is a stub that should be overridden to provide access to accelerator information.
6367 *
6368 * @param {string} name Symbolic name of tool
6369 * @return {string|undefined} Tool accelerator label if available
6370 */
6371 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6372 return undefined;
6373 };
6374
6375 /**
6376 * Collection of tools.
6377 *
6378 * Tools can be specified in the following ways:
6379 *
6380 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6381 * - All tools in a group: `{ group: 'group-name' }`
6382 * - All tools: `'*'`
6383 *
6384 * @abstract
6385 * @class
6386 * @extends OO.ui.Widget
6387 * @mixins OO.ui.GroupElement
6388 *
6389 * @constructor
6390 * @param {OO.ui.Toolbar} toolbar
6391 * @param {Object} [config] Configuration options
6392 * @cfg {Array|string} [include=[]] List of tools to include
6393 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6394 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6395 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6396 */
6397 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6398 // Configuration initialization
6399 config = config || {};
6400
6401 // Parent constructor
6402 OO.ui.ToolGroup.super.call( this, config );
6403
6404 // Mixin constructors
6405 OO.ui.GroupElement.call( this, config );
6406
6407 // Properties
6408 this.toolbar = toolbar;
6409 this.tools = {};
6410 this.pressed = null;
6411 this.autoDisabled = false;
6412 this.include = config.include || [];
6413 this.exclude = config.exclude || [];
6414 this.promote = config.promote || [];
6415 this.demote = config.demote || [];
6416 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6417
6418 // Events
6419 this.$element.on( {
6420 'mousedown touchstart': this.onPointerDown.bind( this ),
6421 'mouseup touchend': this.onPointerUp.bind( this ),
6422 mouseover: this.onMouseOver.bind( this ),
6423 mouseout: this.onMouseOut.bind( this )
6424 } );
6425 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6426 this.aggregate( { disable: 'itemDisable' } );
6427 this.connect( this, { itemDisable: 'updateDisabled' } );
6428
6429 // Initialization
6430 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6431 this.$element
6432 .addClass( 'oo-ui-toolGroup' )
6433 .append( this.$group );
6434 this.populate();
6435 };
6436
6437 /* Setup */
6438
6439 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6440 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6441
6442 /* Events */
6443
6444 /**
6445 * @event update
6446 */
6447
6448 /* Static Properties */
6449
6450 /**
6451 * Show labels in tooltips.
6452 *
6453 * @static
6454 * @inheritable
6455 * @property {boolean}
6456 */
6457 OO.ui.ToolGroup.static.titleTooltips = false;
6458
6459 /**
6460 * Show acceleration labels in tooltips.
6461 *
6462 * @static
6463 * @inheritable
6464 * @property {boolean}
6465 */
6466 OO.ui.ToolGroup.static.accelTooltips = false;
6467
6468 /**
6469 * Automatically disable the toolgroup when all tools are disabled
6470 *
6471 * @static
6472 * @inheritable
6473 * @property {boolean}
6474 */
6475 OO.ui.ToolGroup.static.autoDisable = true;
6476
6477 /* Methods */
6478
6479 /**
6480 * @inheritdoc
6481 */
6482 OO.ui.ToolGroup.prototype.isDisabled = function () {
6483 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6484 };
6485
6486 /**
6487 * @inheritdoc
6488 */
6489 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6490 var i, item, allDisabled = true;
6491
6492 if ( this.constructor.static.autoDisable ) {
6493 for ( i = this.items.length - 1; i >= 0; i-- ) {
6494 item = this.items[ i ];
6495 if ( !item.isDisabled() ) {
6496 allDisabled = false;
6497 break;
6498 }
6499 }
6500 this.autoDisabled = allDisabled;
6501 }
6502 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6503 };
6504
6505 /**
6506 * Handle mouse down events.
6507 *
6508 * @param {jQuery.Event} e Mouse down event
6509 */
6510 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6511 // e.which is 0 for touch events, 1 for left mouse button
6512 if ( !this.isDisabled() && e.which <= 1 ) {
6513 this.pressed = this.getTargetTool( e );
6514 if ( this.pressed ) {
6515 this.pressed.setActive( true );
6516 this.getElementDocument().addEventListener(
6517 'mouseup', this.onCapturedMouseUpHandler, true
6518 );
6519 }
6520 }
6521 return false;
6522 };
6523
6524 /**
6525 * Handle captured mouse up events.
6526 *
6527 * @param {Event} e Mouse up event
6528 */
6529 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6530 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
6531 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6532 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6533 this.onPointerUp( e );
6534 };
6535
6536 /**
6537 * Handle mouse up events.
6538 *
6539 * @param {jQuery.Event} e Mouse up event
6540 */
6541 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
6542 var tool = this.getTargetTool( e );
6543
6544 // e.which is 0 for touch events, 1 for left mouse button
6545 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === tool ) {
6546 this.pressed.onSelect();
6547 }
6548
6549 this.pressed = null;
6550 return false;
6551 };
6552
6553 /**
6554 * Handle mouse over events.
6555 *
6556 * @param {jQuery.Event} e Mouse over event
6557 */
6558 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
6559 var tool = this.getTargetTool( e );
6560
6561 if ( this.pressed && this.pressed === tool ) {
6562 this.pressed.setActive( true );
6563 }
6564 };
6565
6566 /**
6567 * Handle mouse out events.
6568 *
6569 * @param {jQuery.Event} e Mouse out event
6570 */
6571 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
6572 var tool = this.getTargetTool( e );
6573
6574 if ( this.pressed && this.pressed === tool ) {
6575 this.pressed.setActive( false );
6576 }
6577 };
6578
6579 /**
6580 * Get the closest tool to a jQuery.Event.
6581 *
6582 * Only tool links are considered, which prevents other elements in the tool such as popups from
6583 * triggering tool group interactions.
6584 *
6585 * @private
6586 * @param {jQuery.Event} e
6587 * @return {OO.ui.Tool|null} Tool, `null` if none was found
6588 */
6589 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
6590 var tool,
6591 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
6592
6593 if ( $item.length ) {
6594 tool = $item.parent().data( 'oo-ui-tool' );
6595 }
6596
6597 return tool && !tool.isDisabled() ? tool : null;
6598 };
6599
6600 /**
6601 * Handle tool registry register events.
6602 *
6603 * If a tool is registered after the group is created, we must repopulate the list to account for:
6604 *
6605 * - a tool being added that may be included
6606 * - a tool already included being overridden
6607 *
6608 * @param {string} name Symbolic name of tool
6609 */
6610 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
6611 this.populate();
6612 };
6613
6614 /**
6615 * Get the toolbar this group is in.
6616 *
6617 * @return {OO.ui.Toolbar} Toolbar of group
6618 */
6619 OO.ui.ToolGroup.prototype.getToolbar = function () {
6620 return this.toolbar;
6621 };
6622
6623 /**
6624 * Add and remove tools based on configuration.
6625 */
6626 OO.ui.ToolGroup.prototype.populate = function () {
6627 var i, len, name, tool,
6628 toolFactory = this.toolbar.getToolFactory(),
6629 names = {},
6630 add = [],
6631 remove = [],
6632 list = this.toolbar.getToolFactory().getTools(
6633 this.include, this.exclude, this.promote, this.demote
6634 );
6635
6636 // Build a list of needed tools
6637 for ( i = 0, len = list.length; i < len; i++ ) {
6638 name = list[ i ];
6639 if (
6640 // Tool exists
6641 toolFactory.lookup( name ) &&
6642 // Tool is available or is already in this group
6643 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
6644 ) {
6645 tool = this.tools[ name ];
6646 if ( !tool ) {
6647 // Auto-initialize tools on first use
6648 this.tools[ name ] = tool = toolFactory.create( name, this );
6649 tool.updateTitle();
6650 }
6651 this.toolbar.reserveTool( tool );
6652 add.push( tool );
6653 names[ name ] = true;
6654 }
6655 }
6656 // Remove tools that are no longer needed
6657 for ( name in this.tools ) {
6658 if ( !names[ name ] ) {
6659 this.tools[ name ].destroy();
6660 this.toolbar.releaseTool( this.tools[ name ] );
6661 remove.push( this.tools[ name ] );
6662 delete this.tools[ name ];
6663 }
6664 }
6665 if ( remove.length ) {
6666 this.removeItems( remove );
6667 }
6668 // Update emptiness state
6669 if ( add.length ) {
6670 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
6671 } else {
6672 this.$element.addClass( 'oo-ui-toolGroup-empty' );
6673 }
6674 // Re-add tools (moving existing ones to new locations)
6675 this.addItems( add );
6676 // Disabled state may depend on items
6677 this.updateDisabled();
6678 };
6679
6680 /**
6681 * Destroy tool group.
6682 */
6683 OO.ui.ToolGroup.prototype.destroy = function () {
6684 var name;
6685
6686 this.clearItems();
6687 this.toolbar.getToolFactory().disconnect( this );
6688 for ( name in this.tools ) {
6689 this.toolbar.releaseTool( this.tools[ name ] );
6690 this.tools[ name ].disconnect( this ).destroy();
6691 delete this.tools[ name ];
6692 }
6693 this.$element.remove();
6694 };
6695
6696 /**
6697 * Dialog for showing a message.
6698 *
6699 * User interface:
6700 * - Registers two actions by default (safe and primary).
6701 * - Renders action widgets in the footer.
6702 *
6703 * @class
6704 * @extends OO.ui.Dialog
6705 *
6706 * @constructor
6707 * @param {Object} [config] Configuration options
6708 */
6709 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
6710 // Parent constructor
6711 OO.ui.MessageDialog.super.call( this, config );
6712
6713 // Properties
6714 this.verticalActionLayout = null;
6715
6716 // Initialization
6717 this.$element.addClass( 'oo-ui-messageDialog' );
6718 };
6719
6720 /* Inheritance */
6721
6722 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
6723
6724 /* Static Properties */
6725
6726 OO.ui.MessageDialog.static.name = 'message';
6727
6728 OO.ui.MessageDialog.static.size = 'small';
6729
6730 OO.ui.MessageDialog.static.verbose = false;
6731
6732 /**
6733 * Dialog title.
6734 *
6735 * A confirmation dialog's title should describe what the progressive action will do. An alert
6736 * dialog's title should describe what event occurred.
6737 *
6738 * @static
6739 * inheritable
6740 * @property {jQuery|string|Function|null}
6741 */
6742 OO.ui.MessageDialog.static.title = null;
6743
6744 /**
6745 * A confirmation dialog's message should describe the consequences of the progressive action. An
6746 * alert dialog's message should describe why the event occurred.
6747 *
6748 * @static
6749 * inheritable
6750 * @property {jQuery|string|Function|null}
6751 */
6752 OO.ui.MessageDialog.static.message = null;
6753
6754 OO.ui.MessageDialog.static.actions = [
6755 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
6756 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
6757 ];
6758
6759 /* Methods */
6760
6761 /**
6762 * @inheritdoc
6763 */
6764 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
6765 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
6766
6767 // Events
6768 this.manager.connect( this, {
6769 resize: 'onResize'
6770 } );
6771
6772 return this;
6773 };
6774
6775 /**
6776 * @inheritdoc
6777 */
6778 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
6779 this.fitActions();
6780 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
6781 };
6782
6783 /**
6784 * Handle window resized events.
6785 */
6786 OO.ui.MessageDialog.prototype.onResize = function () {
6787 var dialog = this;
6788 dialog.fitActions();
6789 // Wait for CSS transition to finish and do it again :(
6790 setTimeout( function () {
6791 dialog.fitActions();
6792 }, 300 );
6793 };
6794
6795 /**
6796 * Toggle action layout between vertical and horizontal.
6797 *
6798 * @param {boolean} [value] Layout actions vertically, omit to toggle
6799 * @chainable
6800 */
6801 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
6802 value = value === undefined ? !this.verticalActionLayout : !!value;
6803
6804 if ( value !== this.verticalActionLayout ) {
6805 this.verticalActionLayout = value;
6806 this.$actions
6807 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
6808 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
6809 }
6810
6811 return this;
6812 };
6813
6814 /**
6815 * @inheritdoc
6816 */
6817 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
6818 if ( action ) {
6819 return new OO.ui.Process( function () {
6820 this.close( { action: action } );
6821 }, this );
6822 }
6823 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
6824 };
6825
6826 /**
6827 * @inheritdoc
6828 *
6829 * @param {Object} [data] Dialog opening data
6830 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
6831 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
6832 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
6833 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
6834 * action item
6835 */
6836 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
6837 data = data || {};
6838
6839 // Parent method
6840 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
6841 .next( function () {
6842 this.title.setLabel(
6843 data.title !== undefined ? data.title : this.constructor.static.title
6844 );
6845 this.message.setLabel(
6846 data.message !== undefined ? data.message : this.constructor.static.message
6847 );
6848 this.message.$element.toggleClass(
6849 'oo-ui-messageDialog-message-verbose',
6850 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
6851 );
6852 }, this );
6853 };
6854
6855 /**
6856 * @inheritdoc
6857 */
6858 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
6859 var bodyHeight, oldOverflow,
6860 $scrollable = this.container.$element;
6861
6862 oldOverflow = $scrollable[ 0 ].style.overflow;
6863 $scrollable[ 0 ].style.overflow = 'hidden';
6864
6865 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
6866
6867 bodyHeight = this.text.$element.outerHeight( true );
6868 $scrollable[ 0 ].style.overflow = oldOverflow;
6869
6870 return bodyHeight;
6871 };
6872
6873 /**
6874 * @inheritdoc
6875 */
6876 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
6877 var $scrollable = this.container.$element;
6878 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
6879
6880 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
6881 // Need to do it after transition completes (250ms), add 50ms just in case.
6882 setTimeout( function () {
6883 var oldOverflow = $scrollable[ 0 ].style.overflow;
6884 $scrollable[ 0 ].style.overflow = 'hidden';
6885
6886 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
6887
6888 $scrollable[ 0 ].style.overflow = oldOverflow;
6889 }, 300 );
6890
6891 return this;
6892 };
6893
6894 /**
6895 * @inheritdoc
6896 */
6897 OO.ui.MessageDialog.prototype.initialize = function () {
6898 // Parent method
6899 OO.ui.MessageDialog.super.prototype.initialize.call( this );
6900
6901 // Properties
6902 this.$actions = this.$( '<div>' );
6903 this.container = new OO.ui.PanelLayout( {
6904 $: this.$, scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
6905 } );
6906 this.text = new OO.ui.PanelLayout( {
6907 $: this.$, padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
6908 } );
6909 this.message = new OO.ui.LabelWidget( {
6910 $: this.$, classes: [ 'oo-ui-messageDialog-message' ]
6911 } );
6912
6913 // Initialization
6914 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
6915 this.$content.addClass( 'oo-ui-messageDialog-content' );
6916 this.container.$element.append( this.text.$element );
6917 this.text.$element.append( this.title.$element, this.message.$element );
6918 this.$body.append( this.container.$element );
6919 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
6920 this.$foot.append( this.$actions );
6921 };
6922
6923 /**
6924 * @inheritdoc
6925 */
6926 OO.ui.MessageDialog.prototype.attachActions = function () {
6927 var i, len, other, special, others;
6928
6929 // Parent method
6930 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
6931
6932 special = this.actions.getSpecial();
6933 others = this.actions.getOthers();
6934 if ( special.safe ) {
6935 this.$actions.append( special.safe.$element );
6936 special.safe.toggleFramed( false );
6937 }
6938 if ( others.length ) {
6939 for ( i = 0, len = others.length; i < len; i++ ) {
6940 other = others[ i ];
6941 this.$actions.append( other.$element );
6942 other.toggleFramed( false );
6943 }
6944 }
6945 if ( special.primary ) {
6946 this.$actions.append( special.primary.$element );
6947 special.primary.toggleFramed( false );
6948 }
6949
6950 if ( !this.isOpening() ) {
6951 // If the dialog is currently opening, this will be called automatically soon.
6952 // This also calls #fitActions.
6953 this.updateSize();
6954 }
6955 };
6956
6957 /**
6958 * Fit action actions into columns or rows.
6959 *
6960 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
6961 */
6962 OO.ui.MessageDialog.prototype.fitActions = function () {
6963 var i, len, action,
6964 previous = this.verticalActionLayout,
6965 actions = this.actions.get();
6966
6967 // Detect clipping
6968 this.toggleVerticalActionLayout( false );
6969 for ( i = 0, len = actions.length; i < len; i++ ) {
6970 action = actions[ i ];
6971 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
6972 this.toggleVerticalActionLayout( true );
6973 break;
6974 }
6975 }
6976
6977 if ( this.verticalActionLayout !== previous ) {
6978 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
6979 // We changed the layout, window height might need to be updated.
6980 this.updateSize();
6981 }
6982 };
6983
6984 /**
6985 * Navigation dialog window.
6986 *
6987 * Logic:
6988 * - Show and hide errors.
6989 * - Retry an action.
6990 *
6991 * User interface:
6992 * - Renders header with dialog title and one action widget on either side
6993 * (a 'safe' button on the left, and a 'primary' button on the right, both of
6994 * which close the dialog).
6995 * - Displays any action widgets in the footer (none by default).
6996 * - Ability to dismiss errors.
6997 *
6998 * Subclass responsibilities:
6999 * - Register a 'safe' action.
7000 * - Register a 'primary' action.
7001 * - Add content to the dialog.
7002 *
7003 * @abstract
7004 * @class
7005 * @extends OO.ui.Dialog
7006 *
7007 * @constructor
7008 * @param {Object} [config] Configuration options
7009 */
7010 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7011 // Parent constructor
7012 OO.ui.ProcessDialog.super.call( this, config );
7013
7014 // Initialization
7015 this.$element.addClass( 'oo-ui-processDialog' );
7016 };
7017
7018 /* Setup */
7019
7020 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7021
7022 /* Methods */
7023
7024 /**
7025 * Handle dismiss button click events.
7026 *
7027 * Hides errors.
7028 */
7029 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7030 this.hideErrors();
7031 };
7032
7033 /**
7034 * Handle retry button click events.
7035 *
7036 * Hides errors and then tries again.
7037 */
7038 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7039 this.hideErrors();
7040 this.executeAction( this.currentAction.getAction() );
7041 };
7042
7043 /**
7044 * @inheritdoc
7045 */
7046 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7047 if ( this.actions.isSpecial( action ) ) {
7048 this.fitLabel();
7049 }
7050 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7051 };
7052
7053 /**
7054 * @inheritdoc
7055 */
7056 OO.ui.ProcessDialog.prototype.initialize = function () {
7057 // Parent method
7058 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7059
7060 // Properties
7061 this.$navigation = this.$( '<div>' );
7062 this.$location = this.$( '<div>' );
7063 this.$safeActions = this.$( '<div>' );
7064 this.$primaryActions = this.$( '<div>' );
7065 this.$otherActions = this.$( '<div>' );
7066 this.dismissButton = new OO.ui.ButtonWidget( {
7067 $: this.$,
7068 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7069 } );
7070 this.retryButton = new OO.ui.ButtonWidget( { $: this.$ } );
7071 this.$errors = this.$( '<div>' );
7072 this.$errorsTitle = this.$( '<div>' );
7073
7074 // Events
7075 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7076 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7077
7078 // Initialization
7079 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7080 this.$location
7081 .append( this.title.$element )
7082 .addClass( 'oo-ui-processDialog-location' );
7083 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7084 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7085 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7086 this.$errorsTitle
7087 .addClass( 'oo-ui-processDialog-errors-title' )
7088 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7089 this.$errors
7090 .addClass( 'oo-ui-processDialog-errors' )
7091 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7092 this.$content
7093 .addClass( 'oo-ui-processDialog-content' )
7094 .append( this.$errors );
7095 this.$navigation
7096 .addClass( 'oo-ui-processDialog-navigation' )
7097 .append( this.$safeActions, this.$location, this.$primaryActions );
7098 this.$head.append( this.$navigation );
7099 this.$foot.append( this.$otherActions );
7100 };
7101
7102 /**
7103 * @inheritdoc
7104 */
7105 OO.ui.ProcessDialog.prototype.attachActions = function () {
7106 var i, len, other, special, others;
7107
7108 // Parent method
7109 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7110
7111 special = this.actions.getSpecial();
7112 others = this.actions.getOthers();
7113 if ( special.primary ) {
7114 this.$primaryActions.append( special.primary.$element );
7115 special.primary.toggleFramed( true );
7116 }
7117 if ( others.length ) {
7118 for ( i = 0, len = others.length; i < len; i++ ) {
7119 other = others[ i ];
7120 this.$otherActions.append( other.$element );
7121 other.toggleFramed( true );
7122 }
7123 }
7124 if ( special.safe ) {
7125 this.$safeActions.append( special.safe.$element );
7126 special.safe.toggleFramed( true );
7127 }
7128
7129 this.fitLabel();
7130 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7131 };
7132
7133 /**
7134 * @inheritdoc
7135 */
7136 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7137 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7138 .fail( this.showErrors.bind( this ) );
7139 };
7140
7141 /**
7142 * Fit label between actions.
7143 *
7144 * @chainable
7145 */
7146 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7147 var width = Math.max(
7148 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7149 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7150 );
7151 this.$location.css( { paddingLeft: width, paddingRight: width } );
7152
7153 return this;
7154 };
7155
7156 /**
7157 * Handle errors that occurred during accept or reject processes.
7158 *
7159 * @param {OO.ui.Error[]} errors Errors to be handled
7160 */
7161 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7162 var i, len, $item,
7163 items = [],
7164 recoverable = true,
7165 warning = false;
7166
7167 for ( i = 0, len = errors.length; i < len; i++ ) {
7168 if ( !errors[ i ].isRecoverable() ) {
7169 recoverable = false;
7170 }
7171 if ( errors[ i ].isWarning() ) {
7172 warning = true;
7173 }
7174 $item = this.$( '<div>' )
7175 .addClass( 'oo-ui-processDialog-error' )
7176 .append( errors[ i ].getMessage() );
7177 items.push( $item[ 0 ] );
7178 }
7179 this.$errorItems = this.$( items );
7180 if ( recoverable ) {
7181 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
7182 } else {
7183 this.currentAction.setDisabled( true );
7184 }
7185 if ( warning ) {
7186 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7187 } else {
7188 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7189 }
7190 this.retryButton.toggle( recoverable );
7191 this.$errorsTitle.after( this.$errorItems );
7192 this.$errors.show().scrollTop( 0 );
7193 };
7194
7195 /**
7196 * Hide errors.
7197 */
7198 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7199 this.$errors.hide();
7200 this.$errorItems.remove();
7201 this.$errorItems = null;
7202 };
7203
7204 /**
7205 * Layout made of a field and optional label.
7206 *
7207 * Available label alignment modes include:
7208 * - left: Label is before the field and aligned away from it, best for when the user will be
7209 * scanning for a specific label in a form with many fields
7210 * - right: Label is before the field and aligned toward it, best for forms the user is very
7211 * familiar with and will tab through field checking quickly to verify which field they are in
7212 * - top: Label is before the field and above it, best for when the user will need to fill out all
7213 * fields from top to bottom in a form with few fields
7214 * - inline: Label is after the field and aligned toward it, best for small boolean fields like
7215 * checkboxes or radio buttons
7216 *
7217 * @class
7218 * @extends OO.ui.Layout
7219 * @mixins OO.ui.LabelElement
7220 *
7221 * @constructor
7222 * @param {OO.ui.Widget} fieldWidget Field widget
7223 * @param {Object} [config] Configuration options
7224 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7225 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7226 */
7227 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7228 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7229
7230 // Configuration initialization
7231 config = $.extend( { align: 'left' }, config );
7232
7233 // Properties (must be set before parent constructor, which calls #getTagName)
7234 this.fieldWidget = fieldWidget;
7235
7236 // Parent constructor
7237 OO.ui.FieldLayout.super.call( this, config );
7238
7239 // Mixin constructors
7240 OO.ui.LabelElement.call( this, config );
7241
7242 // Properties
7243 this.$field = this.$( '<div>' );
7244 this.$body = this.$( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7245 this.align = null;
7246 if ( config.help ) {
7247 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7248 $: this.$,
7249 classes: [ 'oo-ui-fieldLayout-help' ],
7250 framed: false,
7251 icon: 'info'
7252 } );
7253
7254 this.popupButtonWidget.getPopup().$body.append(
7255 this.$( '<div>' )
7256 .text( config.help )
7257 .addClass( 'oo-ui-fieldLayout-help-content' )
7258 );
7259 this.$help = this.popupButtonWidget.$element;
7260 } else {
7261 this.$help = this.$( [] );
7262 }
7263
7264 // Events
7265 if ( hasInputWidget ) {
7266 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7267 }
7268 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7269
7270 // Initialization
7271 this.$element
7272 .addClass( 'oo-ui-fieldLayout' )
7273 .append( this.$help, this.$body );
7274 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7275 this.$field
7276 .addClass( 'oo-ui-fieldLayout-field' )
7277 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7278 .append( this.fieldWidget.$element );
7279
7280 this.setAlignment( config.align );
7281 };
7282
7283 /* Setup */
7284
7285 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7286 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7287
7288 /* Methods */
7289
7290 /**
7291 * Handle field disable events.
7292 *
7293 * @param {boolean} value Field is disabled
7294 */
7295 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7296 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7297 };
7298
7299 /**
7300 * Handle label mouse click events.
7301 *
7302 * @param {jQuery.Event} e Mouse click event
7303 */
7304 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7305 this.fieldWidget.simulateLabelClick();
7306 return false;
7307 };
7308
7309 /**
7310 * Get the field.
7311 *
7312 * @return {OO.ui.Widget} Field widget
7313 */
7314 OO.ui.FieldLayout.prototype.getField = function () {
7315 return this.fieldWidget;
7316 };
7317
7318 /**
7319 * Set the field alignment mode.
7320 *
7321 * @private
7322 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7323 * @chainable
7324 */
7325 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7326 if ( value !== this.align ) {
7327 // Default to 'left'
7328 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7329 value = 'left';
7330 }
7331 // Reorder elements
7332 if ( value === 'inline' ) {
7333 this.$body.append( this.$field, this.$label );
7334 } else {
7335 this.$body.append( this.$label, this.$field );
7336 }
7337 // Set classes. The following classes can be used here:
7338 // * oo-ui-fieldLayout-align-left
7339 // * oo-ui-fieldLayout-align-right
7340 // * oo-ui-fieldLayout-align-top
7341 // * oo-ui-fieldLayout-align-inline
7342 if ( this.align ) {
7343 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7344 }
7345 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7346 this.align = value;
7347 }
7348
7349 return this;
7350 };
7351
7352 /**
7353 * Layout made of a field, a button, and an optional label.
7354 *
7355 * @class
7356 * @extends OO.ui.FieldLayout
7357 *
7358 * @constructor
7359 * @param {OO.ui.Widget} fieldWidget Field widget
7360 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7361 * @param {Object} [config] Configuration options
7362 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7363 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7364 */
7365 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
7366 // Configuration initialization
7367 config = $.extend( { align: 'left' }, config );
7368
7369 // Properties (must be set before parent constructor, which calls #getTagName)
7370 this.fieldWidget = fieldWidget;
7371 this.buttonWidget = buttonWidget;
7372
7373 // Parent constructor
7374 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
7375
7376 // Mixin constructors
7377 OO.ui.LabelElement.call( this, config );
7378
7379 // Properties
7380 this.$button = this.$( '<div>' )
7381 .addClass( 'oo-ui-actionFieldLayout-button' )
7382 .append( this.buttonWidget.$element );
7383
7384 this.$input = this.$( '<div>' )
7385 .addClass( 'oo-ui-actionFieldLayout-input' )
7386 .append( this.fieldWidget.$element );
7387
7388 this.$field
7389 .addClass( 'oo-ui-actionFieldLayout' )
7390 .append( this.$input, this.$button );
7391 };
7392
7393 /* Setup */
7394
7395 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
7396
7397 /**
7398 * Layout made of a fieldset and optional legend.
7399 *
7400 * Just add OO.ui.FieldLayout items.
7401 *
7402 * @class
7403 * @extends OO.ui.Layout
7404 * @mixins OO.ui.IconElement
7405 * @mixins OO.ui.LabelElement
7406 * @mixins OO.ui.GroupElement
7407 *
7408 * @constructor
7409 * @param {Object} [config] Configuration options
7410 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7411 */
7412 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
7413 // Configuration initialization
7414 config = config || {};
7415
7416 // Parent constructor
7417 OO.ui.FieldsetLayout.super.call( this, config );
7418
7419 // Mixin constructors
7420 OO.ui.IconElement.call( this, config );
7421 OO.ui.LabelElement.call( this, config );
7422 OO.ui.GroupElement.call( this, config );
7423
7424 if ( config.help ) {
7425 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7426 $: this.$,
7427 classes: [ 'oo-ui-fieldsetLayout-help' ],
7428 framed: false,
7429 icon: 'info'
7430 } );
7431
7432 this.popupButtonWidget.getPopup().$body.append(
7433 this.$( '<div>' )
7434 .text( config.help )
7435 .addClass( 'oo-ui-fieldsetLayout-help-content' )
7436 );
7437 this.$help = this.popupButtonWidget.$element;
7438 } else {
7439 this.$help = this.$( [] );
7440 }
7441
7442 // Initialization
7443 this.$element
7444 .addClass( 'oo-ui-fieldsetLayout' )
7445 .prepend( this.$help, this.$icon, this.$label, this.$group );
7446 if ( $.isArray( config.items ) ) {
7447 this.addItems( config.items );
7448 }
7449 };
7450
7451 /* Setup */
7452
7453 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
7454 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
7455 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
7456 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
7457
7458 /**
7459 * Layout with an HTML form.
7460 *
7461 * @class
7462 * @extends OO.ui.Layout
7463 *
7464 * @constructor
7465 * @param {Object} [config] Configuration options
7466 * @cfg {string} [method] HTML form `method` attribute
7467 * @cfg {string} [action] HTML form `action` attribute
7468 * @cfg {string} [enctype] HTML form `enctype` attribute
7469 */
7470 OO.ui.FormLayout = function OoUiFormLayout( config ) {
7471 // Configuration initialization
7472 config = config || {};
7473
7474 // Parent constructor
7475 OO.ui.FormLayout.super.call( this, config );
7476
7477 // Events
7478 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
7479
7480 // Initialization
7481 this.$element
7482 .addClass( 'oo-ui-formLayout' )
7483 .attr( {
7484 method: config.method,
7485 action: config.action,
7486 enctype: config.enctype
7487 } );
7488 };
7489
7490 /* Setup */
7491
7492 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
7493
7494 /* Events */
7495
7496 /**
7497 * @event submit
7498 */
7499
7500 /* Static Properties */
7501
7502 OO.ui.FormLayout.static.tagName = 'form';
7503
7504 /* Methods */
7505
7506 /**
7507 * Handle form submit events.
7508 *
7509 * @param {jQuery.Event} e Submit event
7510 * @fires submit
7511 */
7512 OO.ui.FormLayout.prototype.onFormSubmit = function () {
7513 this.emit( 'submit' );
7514 return false;
7515 };
7516
7517 /**
7518 * Layout made of proportionally sized columns and rows.
7519 *
7520 * @class
7521 * @extends OO.ui.Layout
7522 *
7523 * @constructor
7524 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
7525 * @param {Object} [config] Configuration options
7526 * @cfg {number[]} [widths] Widths of columns as ratios
7527 * @cfg {number[]} [heights] Heights of rows as ratios
7528 */
7529 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
7530 var i, len, widths;
7531
7532 // Configuration initialization
7533 config = config || {};
7534
7535 // Parent constructor
7536 OO.ui.GridLayout.super.call( this, config );
7537
7538 // Properties
7539 this.panels = [];
7540 this.widths = [];
7541 this.heights = [];
7542
7543 // Initialization
7544 this.$element.addClass( 'oo-ui-gridLayout' );
7545 for ( i = 0, len = panels.length; i < len; i++ ) {
7546 this.panels.push( panels[ i ] );
7547 this.$element.append( panels[ i ].$element );
7548 }
7549 if ( config.widths || config.heights ) {
7550 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
7551 } else {
7552 // Arrange in columns by default
7553 widths = this.panels.map( function () { return 1; } );
7554 this.layout( widths, [ 1 ] );
7555 }
7556 };
7557
7558 /* Setup */
7559
7560 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
7561
7562 /* Events */
7563
7564 /**
7565 * @event layout
7566 */
7567
7568 /**
7569 * @event update
7570 */
7571
7572 /* Methods */
7573
7574 /**
7575 * Set grid dimensions.
7576 *
7577 * @param {number[]} widths Widths of columns as ratios
7578 * @param {number[]} heights Heights of rows as ratios
7579 * @fires layout
7580 * @throws {Error} If grid is not large enough to fit all panels
7581 */
7582 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
7583 var x, y,
7584 xd = 0,
7585 yd = 0,
7586 cols = widths.length,
7587 rows = heights.length;
7588
7589 // Verify grid is big enough to fit panels
7590 if ( cols * rows < this.panels.length ) {
7591 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
7592 }
7593
7594 // Sum up denominators
7595 for ( x = 0; x < cols; x++ ) {
7596 xd += widths[ x ];
7597 }
7598 for ( y = 0; y < rows; y++ ) {
7599 yd += heights[ y ];
7600 }
7601 // Store factors
7602 this.widths = [];
7603 this.heights = [];
7604 for ( x = 0; x < cols; x++ ) {
7605 this.widths[ x ] = widths[ x ] / xd;
7606 }
7607 for ( y = 0; y < rows; y++ ) {
7608 this.heights[ y ] = heights[ y ] / yd;
7609 }
7610 // Synchronize view
7611 this.update();
7612 this.emit( 'layout' );
7613 };
7614
7615 /**
7616 * Update panel positions and sizes.
7617 *
7618 * @fires update
7619 */
7620 OO.ui.GridLayout.prototype.update = function () {
7621 var x, y, panel, width, height, dimensions,
7622 i = 0,
7623 top = 0,
7624 left = 0,
7625 cols = this.widths.length,
7626 rows = this.heights.length;
7627
7628 for ( y = 0; y < rows; y++ ) {
7629 height = this.heights[ y ];
7630 for ( x = 0; x < cols; x++ ) {
7631 width = this.widths[ x ];
7632 panel = this.panels[ i ];
7633 dimensions = {
7634 width: ( width * 100 ) + '%',
7635 height: ( height * 100 ) + '%',
7636 top: ( top * 100 ) + '%'
7637 };
7638 // If RTL, reverse:
7639 if ( OO.ui.Element.static.getDir( this.$.context ) === 'rtl' ) {
7640 dimensions.right = ( left * 100 ) + '%';
7641 } else {
7642 dimensions.left = ( left * 100 ) + '%';
7643 }
7644 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
7645 if ( width === 0 || height === 0 ) {
7646 dimensions.visibility = 'hidden';
7647 } else {
7648 dimensions.visibility = '';
7649 }
7650 panel.$element.css( dimensions );
7651 i++;
7652 left += width;
7653 }
7654 top += height;
7655 left = 0;
7656 }
7657
7658 this.emit( 'update' );
7659 };
7660
7661 /**
7662 * Get a panel at a given position.
7663 *
7664 * The x and y position is affected by the current grid layout.
7665 *
7666 * @param {number} x Horizontal position
7667 * @param {number} y Vertical position
7668 * @return {OO.ui.PanelLayout} The panel at the given position
7669 */
7670 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
7671 return this.panels[ ( x * this.widths.length ) + y ];
7672 };
7673
7674 /**
7675 * Layout with a content and menu area.
7676 *
7677 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
7678 * all remaining space.
7679 *
7680 * @class
7681 * @extends OO.ui.Layout
7682 *
7683 * @constructor
7684 * @param {Object} [config] Configuration options
7685 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
7686 * @cfg {boolean} [showMenu=true] Show menu
7687 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
7688 * @cfg {boolean} [collapse] Collapse the menu out of view
7689 */
7690 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
7691 var positions = this.constructor.static.menuPositions;
7692
7693 // Configuration initialization
7694 config = config || {};
7695
7696 // Parent constructor
7697 OO.ui.MenuLayout.super.call( this, config );
7698
7699 // Properties
7700 this.showMenu = config.showMenu !== false;
7701 this.menuSize = config.menuSize || '18em';
7702 this.menuPosition = positions[ config.menuPosition ] || positions.before;
7703
7704 /**
7705 * Menu DOM node
7706 *
7707 * @property {jQuery}
7708 */
7709 this.$menu = this.$( '<div>' );
7710 /**
7711 * Content DOM node
7712 *
7713 * @property {jQuery}
7714 */
7715 this.$content = this.$( '<div>' );
7716
7717 // Events
7718 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
7719
7720 // Initialization
7721 this.toggleMenu( this.showMenu );
7722 this.$menu
7723 .addClass( 'oo-ui-menuLayout-menu' )
7724 .css( this.menuPosition.sizeProperty, this.menuSize );
7725 this.$content.addClass( 'oo-ui-menuLayout-content' );
7726 this.$element
7727 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
7728 .append( this.$content, this.$menu );
7729 };
7730
7731 /* Setup */
7732
7733 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
7734
7735 /* Static Properties */
7736
7737 OO.ui.MenuLayout.static.menuPositions = {
7738 top: {
7739 sizeProperty: 'height',
7740 positionProperty: 'top',
7741 className: 'oo-ui-menuLayout-top'
7742 },
7743 after: {
7744 sizeProperty: 'width',
7745 positionProperty: 'right',
7746 rtlPositionProperty: 'left',
7747 className: 'oo-ui-menuLayout-after'
7748 },
7749 bottom: {
7750 sizeProperty: 'height',
7751 positionProperty: 'bottom',
7752 className: 'oo-ui-menuLayout-bottom'
7753 },
7754 before: {
7755 sizeProperty: 'width',
7756 positionProperty: 'left',
7757 rtlPositionProperty: 'right',
7758 className: 'oo-ui-menuLayout-before'
7759 }
7760 };
7761
7762 /* Methods */
7763
7764 /**
7765 * Handle DOM attachment events
7766 */
7767 OO.ui.MenuLayout.prototype.onElementAttach = function () {
7768 // getPositionProperty won't know about directionality until the layout is attached
7769 if ( this.showMenu ) {
7770 this.$content.css( this.getPositionProperty(), this.menuSize );
7771 }
7772 };
7773
7774 /**
7775 * Toggle menu.
7776 *
7777 * @param {boolean} showMenu Show menu, omit to toggle
7778 * @chainable
7779 */
7780 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
7781 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
7782
7783 if ( this.showMenu !== showMenu ) {
7784 this.showMenu = showMenu;
7785 this.updateSizes();
7786 }
7787
7788 return this;
7789 };
7790
7791 /**
7792 * Check if menu is visible
7793 *
7794 * @return {boolean} Menu is visible
7795 */
7796 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
7797 return this.showMenu;
7798 };
7799
7800 /**
7801 * Set menu size.
7802 *
7803 * @param {number|string} size Size of menu in pixels or any CSS unit
7804 * @chainable
7805 */
7806 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
7807 this.menuSize = size;
7808 this.updateSizes();
7809
7810 return this;
7811 };
7812
7813 /**
7814 * Update menu and content CSS based on current menu size and visibility
7815 */
7816 OO.ui.MenuLayout.prototype.updateSizes = function () {
7817 if ( this.showMenu ) {
7818 this.$menu
7819 .css( this.menuPosition.sizeProperty, this.menuSize )
7820 .css( 'overflow', '' );
7821 this.$content.css( this.getPositionProperty(), this.menuSize );
7822 } else {
7823 this.$menu
7824 .css( this.menuPosition.sizeProperty, 0 )
7825 .css( 'overflow', 'hidden' );
7826 this.$content.css( this.getPositionProperty(), 0 );
7827 }
7828 };
7829
7830 /**
7831 * Get menu size.
7832 *
7833 * @return {number|string} Menu size
7834 */
7835 OO.ui.MenuLayout.prototype.getMenuSize = function () {
7836 return this.menuSize;
7837 };
7838
7839 /**
7840 * Set menu position.
7841 *
7842 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
7843 * @throws {Error} If position value is not supported
7844 * @chainable
7845 */
7846 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
7847 var positionProperty, positions = this.constructor.static.menuPositions;
7848
7849 if ( !positions[ position ] ) {
7850 throw new Error( 'Cannot set position; unsupported position value: ' + position );
7851 }
7852
7853 positionProperty = this.getPositionProperty();
7854 this.$menu.css( this.menuPosition.sizeProperty, '' );
7855 this.$content.css( positionProperty, '' );
7856 this.$element.removeClass( this.menuPosition.className );
7857
7858 this.menuPosition = positions[ position ];
7859
7860 this.updateSizes();
7861 this.$element.addClass( this.menuPosition.className );
7862
7863 return this;
7864 };
7865
7866 /**
7867 * Get menu position.
7868 *
7869 * @return {string} Menu position
7870 */
7871 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
7872 return this.menuPosition;
7873 };
7874
7875 /**
7876 * Get the menu position property.
7877 *
7878 * @return {string} Menu position CSS property
7879 */
7880 OO.ui.MenuLayout.prototype.getPositionProperty = function () {
7881 if ( this.menuPosition.rtlPositionProperty && this.$element.css( 'direction' ) === 'rtl' ) {
7882 return this.menuPosition.rtlPositionProperty;
7883 } else {
7884 return this.menuPosition.positionProperty;
7885 }
7886 };
7887
7888 /**
7889 * Layout containing a series of pages.
7890 *
7891 * @class
7892 * @extends OO.ui.MenuLayout
7893 *
7894 * @constructor
7895 * @param {Object} [config] Configuration options
7896 * @cfg {boolean} [continuous=false] Show all pages, one after another
7897 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
7898 * @cfg {boolean} [outlined=false] Show an outline
7899 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
7900 */
7901 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
7902 // Configuration initialization
7903 config = config || {};
7904
7905 // Parent constructor
7906 OO.ui.BookletLayout.super.call( this, config );
7907
7908 // Properties
7909 this.currentPageName = null;
7910 this.pages = {};
7911 this.ignoreFocus = false;
7912 this.stackLayout = new OO.ui.StackLayout( { $: this.$, continuous: !!config.continuous } );
7913 this.$content.append( this.stackLayout.$element );
7914 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
7915 this.outlineVisible = false;
7916 this.outlined = !!config.outlined;
7917 if ( this.outlined ) {
7918 this.editable = !!config.editable;
7919 this.outlineControlsWidget = null;
7920 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget( { $: this.$ } );
7921 this.outlinePanel = new OO.ui.PanelLayout( { $: this.$, scrollable: true } );
7922 this.$menu.append( this.outlinePanel.$element );
7923 this.outlineVisible = true;
7924 if ( this.editable ) {
7925 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
7926 this.outlineSelectWidget, { $: this.$ }
7927 );
7928 }
7929 }
7930 this.toggleMenu( this.outlined );
7931
7932 // Events
7933 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
7934 if ( this.outlined ) {
7935 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
7936 }
7937 if ( this.autoFocus ) {
7938 // Event 'focus' does not bubble, but 'focusin' does
7939 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
7940 }
7941
7942 // Initialization
7943 this.$element.addClass( 'oo-ui-bookletLayout' );
7944 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
7945 if ( this.outlined ) {
7946 this.outlinePanel.$element
7947 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
7948 .append( this.outlineSelectWidget.$element );
7949 if ( this.editable ) {
7950 this.outlinePanel.$element
7951 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
7952 .append( this.outlineControlsWidget.$element );
7953 }
7954 }
7955 };
7956
7957 /* Setup */
7958
7959 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
7960
7961 /* Events */
7962
7963 /**
7964 * @event set
7965 * @param {OO.ui.PageLayout} page Current page
7966 */
7967
7968 /**
7969 * @event add
7970 * @param {OO.ui.PageLayout[]} page Added pages
7971 * @param {number} index Index pages were added at
7972 */
7973
7974 /**
7975 * @event remove
7976 * @param {OO.ui.PageLayout[]} pages Removed pages
7977 */
7978
7979 /* Methods */
7980
7981 /**
7982 * Handle stack layout focus.
7983 *
7984 * @param {jQuery.Event} e Focusin event
7985 */
7986 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
7987 var name, $target;
7988
7989 // Find the page that an element was focused within
7990 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
7991 for ( name in this.pages ) {
7992 // Check for page match, exclude current page to find only page changes
7993 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
7994 this.setPage( name );
7995 break;
7996 }
7997 }
7998 };
7999
8000 /**
8001 * Handle stack layout set events.
8002 *
8003 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8004 */
8005 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8006 var layout = this;
8007 if ( page ) {
8008 page.scrollElementIntoView( { complete: function () {
8009 if ( layout.autoFocus ) {
8010 layout.focus();
8011 }
8012 } } );
8013 }
8014 };
8015
8016 /**
8017 * Focus the first input in the current page.
8018 *
8019 * If no page is selected, the first selectable page will be selected.
8020 * If the focus is already in an element on the current page, nothing will happen.
8021 */
8022 OO.ui.BookletLayout.prototype.focus = function () {
8023 var $input, page = this.stackLayout.getCurrentItem();
8024 if ( !page && this.outlined ) {
8025 this.selectFirstSelectablePage();
8026 page = this.stackLayout.getCurrentItem();
8027 }
8028 if ( !page ) {
8029 return;
8030 }
8031 // Only change the focus if is not already in the current page
8032 if ( !page.$element.find( ':focus' ).length ) {
8033 $input = page.$element.find( ':input:first' );
8034 if ( $input.length ) {
8035 $input[ 0 ].focus();
8036 }
8037 }
8038 };
8039
8040 /**
8041 * Handle outline widget select events.
8042 *
8043 * @param {OO.ui.OptionWidget|null} item Selected item
8044 */
8045 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8046 if ( item ) {
8047 this.setPage( item.getData() );
8048 }
8049 };
8050
8051 /**
8052 * Check if booklet has an outline.
8053 *
8054 * @return {boolean}
8055 */
8056 OO.ui.BookletLayout.prototype.isOutlined = function () {
8057 return this.outlined;
8058 };
8059
8060 /**
8061 * Check if booklet has editing controls.
8062 *
8063 * @return {boolean}
8064 */
8065 OO.ui.BookletLayout.prototype.isEditable = function () {
8066 return this.editable;
8067 };
8068
8069 /**
8070 * Check if booklet has a visible outline.
8071 *
8072 * @return {boolean}
8073 */
8074 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8075 return this.outlined && this.outlineVisible;
8076 };
8077
8078 /**
8079 * Hide or show the outline.
8080 *
8081 * @param {boolean} [show] Show outline, omit to invert current state
8082 * @chainable
8083 */
8084 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8085 if ( this.outlined ) {
8086 show = show === undefined ? !this.outlineVisible : !!show;
8087 this.outlineVisible = show;
8088 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
8089 }
8090
8091 return this;
8092 };
8093
8094 /**
8095 * Get the outline widget.
8096 *
8097 * @param {OO.ui.PageLayout} page Page to be selected
8098 * @return {OO.ui.PageLayout|null} Closest page to another
8099 */
8100 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8101 var next, prev, level,
8102 pages = this.stackLayout.getItems(),
8103 index = $.inArray( page, pages );
8104
8105 if ( index !== -1 ) {
8106 next = pages[ index + 1 ];
8107 prev = pages[ index - 1 ];
8108 // Prefer adjacent pages at the same level
8109 if ( this.outlined ) {
8110 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8111 if (
8112 prev &&
8113 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8114 ) {
8115 return prev;
8116 }
8117 if (
8118 next &&
8119 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8120 ) {
8121 return next;
8122 }
8123 }
8124 }
8125 return prev || next || null;
8126 };
8127
8128 /**
8129 * Get the outline widget.
8130 *
8131 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
8132 */
8133 OO.ui.BookletLayout.prototype.getOutline = function () {
8134 return this.outlineSelectWidget;
8135 };
8136
8137 /**
8138 * Get the outline controls widget. If the outline is not editable, null is returned.
8139 *
8140 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8141 */
8142 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8143 return this.outlineControlsWidget;
8144 };
8145
8146 /**
8147 * Get a page by name.
8148 *
8149 * @param {string} name Symbolic name of page
8150 * @return {OO.ui.PageLayout|undefined} Page, if found
8151 */
8152 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8153 return this.pages[ name ];
8154 };
8155
8156 /**
8157 * Get the current page
8158 *
8159 * @return {OO.ui.PageLayout|undefined} Current page, if found
8160 */
8161 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8162 var name = this.getCurrentPageName();
8163 return name ? this.getPage( name ) : undefined;
8164 };
8165
8166 /**
8167 * Get the current page name.
8168 *
8169 * @return {string|null} Current page name
8170 */
8171 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8172 return this.currentPageName;
8173 };
8174
8175 /**
8176 * Add a page to the layout.
8177 *
8178 * When pages are added with the same names as existing pages, the existing pages will be
8179 * automatically removed before the new pages are added.
8180 *
8181 * @param {OO.ui.PageLayout[]} pages Pages to add
8182 * @param {number} index Index to insert pages after
8183 * @fires add
8184 * @chainable
8185 */
8186 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8187 var i, len, name, page, item, currentIndex,
8188 stackLayoutPages = this.stackLayout.getItems(),
8189 remove = [],
8190 items = [];
8191
8192 // Remove pages with same names
8193 for ( i = 0, len = pages.length; i < len; i++ ) {
8194 page = pages[ i ];
8195 name = page.getName();
8196
8197 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8198 // Correct the insertion index
8199 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8200 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8201 index--;
8202 }
8203 remove.push( this.pages[ name ] );
8204 }
8205 }
8206 if ( remove.length ) {
8207 this.removePages( remove );
8208 }
8209
8210 // Add new pages
8211 for ( i = 0, len = pages.length; i < len; i++ ) {
8212 page = pages[ i ];
8213 name = page.getName();
8214 this.pages[ page.getName() ] = page;
8215 if ( this.outlined ) {
8216 item = new OO.ui.OutlineOptionWidget( { $: this.$, data: name } );
8217 page.setOutlineItem( item );
8218 items.push( item );
8219 }
8220 }
8221
8222 if ( this.outlined && items.length ) {
8223 this.outlineSelectWidget.addItems( items, index );
8224 this.selectFirstSelectablePage();
8225 }
8226 this.stackLayout.addItems( pages, index );
8227 this.emit( 'add', pages, index );
8228
8229 return this;
8230 };
8231
8232 /**
8233 * Remove a page from the layout.
8234 *
8235 * @fires remove
8236 * @chainable
8237 */
8238 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
8239 var i, len, name, page,
8240 items = [];
8241
8242 for ( i = 0, len = pages.length; i < len; i++ ) {
8243 page = pages[ i ];
8244 name = page.getName();
8245 delete this.pages[ name ];
8246 if ( this.outlined ) {
8247 items.push( this.outlineSelectWidget.getItemFromData( name ) );
8248 page.setOutlineItem( null );
8249 }
8250 }
8251 if ( this.outlined && items.length ) {
8252 this.outlineSelectWidget.removeItems( items );
8253 this.selectFirstSelectablePage();
8254 }
8255 this.stackLayout.removeItems( pages );
8256 this.emit( 'remove', pages );
8257
8258 return this;
8259 };
8260
8261 /**
8262 * Clear all pages from the layout.
8263 *
8264 * @fires remove
8265 * @chainable
8266 */
8267 OO.ui.BookletLayout.prototype.clearPages = function () {
8268 var i, len,
8269 pages = this.stackLayout.getItems();
8270
8271 this.pages = {};
8272 this.currentPageName = null;
8273 if ( this.outlined ) {
8274 this.outlineSelectWidget.clearItems();
8275 for ( i = 0, len = pages.length; i < len; i++ ) {
8276 pages[ i ].setOutlineItem( null );
8277 }
8278 }
8279 this.stackLayout.clearItems();
8280
8281 this.emit( 'remove', pages );
8282
8283 return this;
8284 };
8285
8286 /**
8287 * Set the current page by name.
8288 *
8289 * @fires set
8290 * @param {string} name Symbolic name of page
8291 */
8292 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
8293 var selectedItem,
8294 $focused,
8295 page = this.pages[ name ];
8296
8297 if ( name !== this.currentPageName ) {
8298 if ( this.outlined ) {
8299 selectedItem = this.outlineSelectWidget.getSelectedItem();
8300 if ( selectedItem && selectedItem.getData() !== name ) {
8301 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
8302 }
8303 }
8304 if ( page ) {
8305 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
8306 this.pages[ this.currentPageName ].setActive( false );
8307 // Blur anything focused if the next page doesn't have anything focusable - this
8308 // is not needed if the next page has something focusable because once it is focused
8309 // this blur happens automatically
8310 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
8311 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
8312 if ( $focused.length ) {
8313 $focused[ 0 ].blur();
8314 }
8315 }
8316 }
8317 this.currentPageName = name;
8318 this.stackLayout.setItem( page );
8319 page.setActive( true );
8320 this.emit( 'set', page );
8321 }
8322 }
8323 };
8324
8325 /**
8326 * Select the first selectable page.
8327 *
8328 * @chainable
8329 */
8330 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
8331 if ( !this.outlineSelectWidget.getSelectedItem() ) {
8332 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
8333 }
8334
8335 return this;
8336 };
8337
8338 /**
8339 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
8340 *
8341 * @class
8342 * @extends OO.ui.Layout
8343 *
8344 * @constructor
8345 * @param {Object} [config] Configuration options
8346 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8347 * @cfg {boolean} [padded=false] Pad the content from the edges
8348 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
8349 */
8350 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8351 // Configuration initialization
8352 config = $.extend( {
8353 scrollable: false,
8354 padded: false,
8355 expanded: true
8356 }, config );
8357
8358 // Parent constructor
8359 OO.ui.PanelLayout.super.call( this, config );
8360
8361 // Initialization
8362 this.$element.addClass( 'oo-ui-panelLayout' );
8363 if ( config.scrollable ) {
8364 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8365 }
8366 if ( config.padded ) {
8367 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8368 }
8369 if ( config.expanded ) {
8370 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8371 }
8372 };
8373
8374 /* Setup */
8375
8376 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8377
8378 /**
8379 * Page within an booklet layout.
8380 *
8381 * @class
8382 * @extends OO.ui.PanelLayout
8383 *
8384 * @constructor
8385 * @param {string} name Unique symbolic name of page
8386 * @param {Object} [config] Configuration options
8387 */
8388 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8389 // Configuration initialization
8390 config = $.extend( { scrollable: true }, config );
8391
8392 // Parent constructor
8393 OO.ui.PageLayout.super.call( this, config );
8394
8395 // Properties
8396 this.name = name;
8397 this.outlineItem = null;
8398 this.active = false;
8399
8400 // Initialization
8401 this.$element.addClass( 'oo-ui-pageLayout' );
8402 };
8403
8404 /* Setup */
8405
8406 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
8407
8408 /* Events */
8409
8410 /**
8411 * @event active
8412 * @param {boolean} active Page is active
8413 */
8414
8415 /* Methods */
8416
8417 /**
8418 * Get page name.
8419 *
8420 * @return {string} Symbolic name of page
8421 */
8422 OO.ui.PageLayout.prototype.getName = function () {
8423 return this.name;
8424 };
8425
8426 /**
8427 * Check if page is active.
8428 *
8429 * @return {boolean} Page is active
8430 */
8431 OO.ui.PageLayout.prototype.isActive = function () {
8432 return this.active;
8433 };
8434
8435 /**
8436 * Get outline item.
8437 *
8438 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8439 */
8440 OO.ui.PageLayout.prototype.getOutlineItem = function () {
8441 return this.outlineItem;
8442 };
8443
8444 /**
8445 * Set outline item.
8446 *
8447 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8448 * outline item as desired; this method is called for setting (with an object) and unsetting
8449 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8450 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8451 *
8452 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8453 * @chainable
8454 */
8455 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
8456 this.outlineItem = outlineItem || null;
8457 if ( outlineItem ) {
8458 this.setupOutlineItem();
8459 }
8460 return this;
8461 };
8462
8463 /**
8464 * Setup outline item.
8465 *
8466 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8467 *
8468 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8469 * @chainable
8470 */
8471 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
8472 return this;
8473 };
8474
8475 /**
8476 * Set page active state.
8477 *
8478 * @param {boolean} Page is active
8479 * @fires active
8480 */
8481 OO.ui.PageLayout.prototype.setActive = function ( active ) {
8482 active = !!active;
8483
8484 if ( active !== this.active ) {
8485 this.active = active;
8486 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
8487 this.emit( 'active', this.active );
8488 }
8489 };
8490
8491 /**
8492 * Layout containing a series of mutually exclusive pages.
8493 *
8494 * @class
8495 * @extends OO.ui.PanelLayout
8496 * @mixins OO.ui.GroupElement
8497 *
8498 * @constructor
8499 * @param {Object} [config] Configuration options
8500 * @cfg {boolean} [continuous=false] Show all pages, one after another
8501 * @cfg {OO.ui.Layout[]} [items] Layouts to add
8502 */
8503 OO.ui.StackLayout = function OoUiStackLayout( config ) {
8504 // Configuration initialization
8505 config = $.extend( { scrollable: true }, config );
8506
8507 // Parent constructor
8508 OO.ui.StackLayout.super.call( this, config );
8509
8510 // Mixin constructors
8511 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8512
8513 // Properties
8514 this.currentItem = null;
8515 this.continuous = !!config.continuous;
8516
8517 // Initialization
8518 this.$element.addClass( 'oo-ui-stackLayout' );
8519 if ( this.continuous ) {
8520 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
8521 }
8522 if ( $.isArray( config.items ) ) {
8523 this.addItems( config.items );
8524 }
8525 };
8526
8527 /* Setup */
8528
8529 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
8530 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
8531
8532 /* Events */
8533
8534 /**
8535 * @event set
8536 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
8537 */
8538
8539 /* Methods */
8540
8541 /**
8542 * Get the current item.
8543 *
8544 * @return {OO.ui.Layout|null}
8545 */
8546 OO.ui.StackLayout.prototype.getCurrentItem = function () {
8547 return this.currentItem;
8548 };
8549
8550 /**
8551 * Unset the current item.
8552 *
8553 * @private
8554 * @param {OO.ui.StackLayout} layout
8555 * @fires set
8556 */
8557 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
8558 var prevItem = this.currentItem;
8559 if ( prevItem === null ) {
8560 return;
8561 }
8562
8563 this.currentItem = null;
8564 this.emit( 'set', null );
8565 };
8566
8567 /**
8568 * Add items.
8569 *
8570 * Adding an existing item (by value) will move it.
8571 *
8572 * @param {OO.ui.Layout[]} items Items to add
8573 * @param {number} [index] Index to insert items after
8574 * @chainable
8575 */
8576 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
8577 // Mixin method
8578 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
8579
8580 if ( !this.currentItem && items.length ) {
8581 this.setItem( items[ 0 ] );
8582 }
8583
8584 return this;
8585 };
8586
8587 /**
8588 * Remove items.
8589 *
8590 * Items will be detached, not removed, so they can be used later.
8591 *
8592 * @param {OO.ui.Layout[]} items Items to remove
8593 * @chainable
8594 * @fires set
8595 */
8596 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
8597 // Mixin method
8598 OO.ui.GroupElement.prototype.removeItems.call( this, items );
8599
8600 if ( $.inArray( this.currentItem, items ) !== -1 ) {
8601 if ( this.items.length ) {
8602 this.setItem( this.items[ 0 ] );
8603 } else {
8604 this.unsetCurrentItem();
8605 }
8606 }
8607
8608 return this;
8609 };
8610
8611 /**
8612 * Clear all items.
8613 *
8614 * Items will be detached, not removed, so they can be used later.
8615 *
8616 * @chainable
8617 * @fires set
8618 */
8619 OO.ui.StackLayout.prototype.clearItems = function () {
8620 this.unsetCurrentItem();
8621 OO.ui.GroupElement.prototype.clearItems.call( this );
8622
8623 return this;
8624 };
8625
8626 /**
8627 * Show item.
8628 *
8629 * Any currently shown item will be hidden.
8630 *
8631 * FIXME: If the passed item to show has not been added in the items list, then
8632 * this method drops it and unsets the current item.
8633 *
8634 * @param {OO.ui.Layout} item Item to show
8635 * @chainable
8636 * @fires set
8637 */
8638 OO.ui.StackLayout.prototype.setItem = function ( item ) {
8639 var i, len;
8640
8641 if ( item !== this.currentItem ) {
8642 if ( !this.continuous ) {
8643 for ( i = 0, len = this.items.length; i < len; i++ ) {
8644 this.items[ i ].$element.css( 'display', '' );
8645 }
8646 }
8647 if ( $.inArray( item, this.items ) !== -1 ) {
8648 if ( !this.continuous ) {
8649 item.$element.css( 'display', 'block' );
8650 }
8651 this.currentItem = item;
8652 this.emit( 'set', item );
8653 } else {
8654 this.unsetCurrentItem();
8655 }
8656 }
8657
8658 return this;
8659 };
8660
8661 /**
8662 * Horizontal bar layout of tools as icon buttons.
8663 *
8664 * @class
8665 * @extends OO.ui.ToolGroup
8666 *
8667 * @constructor
8668 * @param {OO.ui.Toolbar} toolbar
8669 * @param {Object} [config] Configuration options
8670 */
8671 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
8672 // Parent constructor
8673 OO.ui.BarToolGroup.super.call( this, toolbar, config );
8674
8675 // Initialization
8676 this.$element.addClass( 'oo-ui-barToolGroup' );
8677 };
8678
8679 /* Setup */
8680
8681 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
8682
8683 /* Static Properties */
8684
8685 OO.ui.BarToolGroup.static.titleTooltips = true;
8686
8687 OO.ui.BarToolGroup.static.accelTooltips = true;
8688
8689 OO.ui.BarToolGroup.static.name = 'bar';
8690
8691 /**
8692 * Popup list of tools with an icon and optional label.
8693 *
8694 * @abstract
8695 * @class
8696 * @extends OO.ui.ToolGroup
8697 * @mixins OO.ui.IconElement
8698 * @mixins OO.ui.IndicatorElement
8699 * @mixins OO.ui.LabelElement
8700 * @mixins OO.ui.TitledElement
8701 * @mixins OO.ui.ClippableElement
8702 *
8703 * @constructor
8704 * @param {OO.ui.Toolbar} toolbar
8705 * @param {Object} [config] Configuration options
8706 * @cfg {string} [header] Text to display at the top of the pop-up
8707 */
8708 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
8709 // Configuration initialization
8710 config = config || {};
8711
8712 // Parent constructor
8713 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
8714
8715 // Mixin constructors
8716 OO.ui.IconElement.call( this, config );
8717 OO.ui.IndicatorElement.call( this, config );
8718 OO.ui.LabelElement.call( this, config );
8719 OO.ui.TitledElement.call( this, config );
8720 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
8721
8722 // Properties
8723 this.active = false;
8724 this.dragging = false;
8725 this.onBlurHandler = this.onBlur.bind( this );
8726 this.$handle = this.$( '<span>' );
8727
8728 // Events
8729 this.$handle.on( {
8730 'mousedown touchstart': this.onHandlePointerDown.bind( this ),
8731 'mouseup touchend': this.onHandlePointerUp.bind( this )
8732 } );
8733
8734 // Initialization
8735 this.$handle
8736 .addClass( 'oo-ui-popupToolGroup-handle' )
8737 .append( this.$icon, this.$label, this.$indicator );
8738 // If the pop-up should have a header, add it to the top of the toolGroup.
8739 // Note: If this feature is useful for other widgets, we could abstract it into an
8740 // OO.ui.HeaderedElement mixin constructor.
8741 if ( config.header !== undefined ) {
8742 this.$group
8743 .prepend( this.$( '<span>' )
8744 .addClass( 'oo-ui-popupToolGroup-header' )
8745 .text( config.header )
8746 );
8747 }
8748 this.$element
8749 .addClass( 'oo-ui-popupToolGroup' )
8750 .prepend( this.$handle );
8751 };
8752
8753 /* Setup */
8754
8755 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
8756 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
8757 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
8758 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
8759 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
8760 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
8761
8762 /* Static Properties */
8763
8764 /* Methods */
8765
8766 /**
8767 * @inheritdoc
8768 */
8769 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
8770 // Parent method
8771 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
8772
8773 if ( this.isDisabled() && this.isElementAttached() ) {
8774 this.setActive( false );
8775 }
8776 };
8777
8778 /**
8779 * Handle focus being lost.
8780 *
8781 * The event is actually generated from a mouseup, so it is not a normal blur event object.
8782 *
8783 * @param {jQuery.Event} e Mouse up event
8784 */
8785 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
8786 // Only deactivate when clicking outside the dropdown element
8787 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
8788 this.setActive( false );
8789 }
8790 };
8791
8792 /**
8793 * @inheritdoc
8794 */
8795 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
8796 // e.which is 0 for touch events, 1 for left mouse button
8797 // Only close toolgroup when a tool was actually selected
8798 // FIXME: this duplicates logic from the parent class
8799 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
8800 this.setActive( false );
8801 }
8802 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
8803 };
8804
8805 /**
8806 * Handle mouse up events.
8807 *
8808 * @param {jQuery.Event} e Mouse up event
8809 */
8810 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
8811 return false;
8812 };
8813
8814 /**
8815 * Handle mouse down events.
8816 *
8817 * @param {jQuery.Event} e Mouse down event
8818 */
8819 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
8820 // e.which is 0 for touch events, 1 for left mouse button
8821 if ( !this.isDisabled() && e.which <= 1 ) {
8822 this.setActive( !this.active );
8823 }
8824 return false;
8825 };
8826
8827 /**
8828 * Switch into active mode.
8829 *
8830 * When active, mouseup events anywhere in the document will trigger deactivation.
8831 */
8832 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
8833 value = !!value;
8834 if ( this.active !== value ) {
8835 this.active = value;
8836 if ( value ) {
8837 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
8838
8839 // Try anchoring the popup to the left first
8840 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
8841 this.toggleClipping( true );
8842 if ( this.isClippedHorizontally() ) {
8843 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
8844 this.toggleClipping( false );
8845 this.$element
8846 .removeClass( 'oo-ui-popupToolGroup-left' )
8847 .addClass( 'oo-ui-popupToolGroup-right' );
8848 this.toggleClipping( true );
8849 }
8850 } else {
8851 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
8852 this.$element.removeClass(
8853 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
8854 );
8855 this.toggleClipping( false );
8856 }
8857 }
8858 };
8859
8860 /**
8861 * Drop down list layout of tools as labeled icon buttons.
8862 *
8863 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
8864 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
8865 * may want to use the 'promote' and 'demote' configuration options to achieve this.
8866 *
8867 * @class
8868 * @extends OO.ui.PopupToolGroup
8869 *
8870 * @constructor
8871 * @param {OO.ui.Toolbar} toolbar
8872 * @param {Object} [config] Configuration options
8873 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
8874 * shown.
8875 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
8876 * allowed to be collapsed.
8877 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
8878 */
8879 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
8880 // Configuration initialization
8881 config = config || {};
8882
8883 // Properties (must be set before parent constructor, which calls #populate)
8884 this.allowCollapse = config.allowCollapse;
8885 this.forceExpand = config.forceExpand;
8886 this.expanded = config.expanded !== undefined ? config.expanded : false;
8887 this.collapsibleTools = [];
8888
8889 // Parent constructor
8890 OO.ui.ListToolGroup.super.call( this, toolbar, config );
8891
8892 // Initialization
8893 this.$element.addClass( 'oo-ui-listToolGroup' );
8894 };
8895
8896 /* Setup */
8897
8898 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
8899
8900 /* Static Properties */
8901
8902 OO.ui.ListToolGroup.static.accelTooltips = true;
8903
8904 OO.ui.ListToolGroup.static.name = 'list';
8905
8906 /* Methods */
8907
8908 /**
8909 * @inheritdoc
8910 */
8911 OO.ui.ListToolGroup.prototype.populate = function () {
8912 var i, len, allowCollapse = [];
8913
8914 OO.ui.ListToolGroup.super.prototype.populate.call( this );
8915
8916 // Update the list of collapsible tools
8917 if ( this.allowCollapse !== undefined ) {
8918 allowCollapse = this.allowCollapse;
8919 } else if ( this.forceExpand !== undefined ) {
8920 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
8921 }
8922
8923 this.collapsibleTools = [];
8924 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
8925 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
8926 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
8927 }
8928 }
8929
8930 // Keep at the end, even when tools are added
8931 this.$group.append( this.getExpandCollapseTool().$element );
8932
8933 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
8934
8935 // Calling jQuery's .hide() and then .show() on a detached element caches the default value of its
8936 // 'display' attribute and restores it, and the tool uses a <span> and can be hidden and re-shown.
8937 // Is this a jQuery bug? http://jsfiddle.net/gtj4hu3h/
8938 if ( this.getExpandCollapseTool().$element.css( 'display' ) === 'inline' ) {
8939 this.getExpandCollapseTool().$element.css( 'display', 'block' );
8940 }
8941
8942 this.updateCollapsibleState();
8943 };
8944
8945 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
8946 if ( this.expandCollapseTool === undefined ) {
8947 var ExpandCollapseTool = function () {
8948 ExpandCollapseTool.super.apply( this, arguments );
8949 };
8950
8951 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
8952
8953 ExpandCollapseTool.prototype.onSelect = function () {
8954 this.toolGroup.expanded = !this.toolGroup.expanded;
8955 this.toolGroup.updateCollapsibleState();
8956 this.setActive( false );
8957 };
8958 ExpandCollapseTool.prototype.onUpdateState = function () {
8959 // Do nothing. Tool interface requires an implementation of this function.
8960 };
8961
8962 ExpandCollapseTool.static.name = 'more-fewer';
8963
8964 this.expandCollapseTool = new ExpandCollapseTool( this );
8965 }
8966 return this.expandCollapseTool;
8967 };
8968
8969 /**
8970 * @inheritdoc
8971 */
8972 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
8973 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
8974
8975 // Do not close the popup when the user wants to show more/fewer tools
8976 if ( this.$( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
8977 // Prevent the popup list from being hidden
8978 this.setActive( true );
8979 }
8980
8981 return ret;
8982 };
8983
8984 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
8985 var i, len;
8986
8987 this.getExpandCollapseTool()
8988 .setIcon( this.expanded ? 'collapse' : 'expand' )
8989 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
8990
8991 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
8992 this.collapsibleTools[ i ].toggle( this.expanded );
8993 }
8994 };
8995
8996 /**
8997 * Drop down menu layout of tools as selectable menu items.
8998 *
8999 * @class
9000 * @extends OO.ui.PopupToolGroup
9001 *
9002 * @constructor
9003 * @param {OO.ui.Toolbar} toolbar
9004 * @param {Object} [config] Configuration options
9005 */
9006 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9007 // Configuration initialization
9008 config = config || {};
9009
9010 // Parent constructor
9011 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9012
9013 // Events
9014 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9015
9016 // Initialization
9017 this.$element.addClass( 'oo-ui-menuToolGroup' );
9018 };
9019
9020 /* Setup */
9021
9022 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9023
9024 /* Static Properties */
9025
9026 OO.ui.MenuToolGroup.static.accelTooltips = true;
9027
9028 OO.ui.MenuToolGroup.static.name = 'menu';
9029
9030 /* Methods */
9031
9032 /**
9033 * Handle the toolbar state being updated.
9034 *
9035 * When the state changes, the title of each active item in the menu will be joined together and
9036 * used as a label for the group. The label will be empty if none of the items are active.
9037 */
9038 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9039 var name,
9040 labelTexts = [];
9041
9042 for ( name in this.tools ) {
9043 if ( this.tools[ name ].isActive() ) {
9044 labelTexts.push( this.tools[ name ].getTitle() );
9045 }
9046 }
9047
9048 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9049 };
9050
9051 /**
9052 * Tool that shows a popup when selected.
9053 *
9054 * @abstract
9055 * @class
9056 * @extends OO.ui.Tool
9057 * @mixins OO.ui.PopupElement
9058 *
9059 * @constructor
9060 * @param {OO.ui.Toolbar} toolbar
9061 * @param {Object} [config] Configuration options
9062 */
9063 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
9064 // Parent constructor
9065 OO.ui.PopupTool.super.call( this, toolbar, config );
9066
9067 // Mixin constructors
9068 OO.ui.PopupElement.call( this, config );
9069
9070 // Initialization
9071 this.$element
9072 .addClass( 'oo-ui-popupTool' )
9073 .append( this.popup.$element );
9074 };
9075
9076 /* Setup */
9077
9078 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9079 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9080
9081 /* Methods */
9082
9083 /**
9084 * Handle the tool being selected.
9085 *
9086 * @inheritdoc
9087 */
9088 OO.ui.PopupTool.prototype.onSelect = function () {
9089 if ( !this.isDisabled() ) {
9090 this.popup.toggle();
9091 }
9092 this.setActive( false );
9093 return false;
9094 };
9095
9096 /**
9097 * Handle the toolbar state being updated.
9098 *
9099 * @inheritdoc
9100 */
9101 OO.ui.PopupTool.prototype.onUpdateState = function () {
9102 this.setActive( false );
9103 };
9104
9105 /**
9106 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9107 *
9108 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9109 *
9110 * @abstract
9111 * @class
9112 * @extends OO.ui.GroupElement
9113 *
9114 * @constructor
9115 * @param {Object} [config] Configuration options
9116 */
9117 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9118 // Parent constructor
9119 OO.ui.GroupWidget.super.call( this, config );
9120 };
9121
9122 /* Setup */
9123
9124 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9125
9126 /* Methods */
9127
9128 /**
9129 * Set the disabled state of the widget.
9130 *
9131 * This will also update the disabled state of child widgets.
9132 *
9133 * @param {boolean} disabled Disable widget
9134 * @chainable
9135 */
9136 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9137 var i, len;
9138
9139 // Parent method
9140 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9141 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9142
9143 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9144 if ( this.items ) {
9145 for ( i = 0, len = this.items.length; i < len; i++ ) {
9146 this.items[ i ].updateDisabled();
9147 }
9148 }
9149
9150 return this;
9151 };
9152
9153 /**
9154 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9155 *
9156 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9157 * allows bidirectional communication.
9158 *
9159 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9160 *
9161 * @abstract
9162 * @class
9163 *
9164 * @constructor
9165 */
9166 OO.ui.ItemWidget = function OoUiItemWidget() {
9167 //
9168 };
9169
9170 /* Methods */
9171
9172 /**
9173 * Check if widget is disabled.
9174 *
9175 * Checks parent if present, making disabled state inheritable.
9176 *
9177 * @return {boolean} Widget is disabled
9178 */
9179 OO.ui.ItemWidget.prototype.isDisabled = function () {
9180 return this.disabled ||
9181 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9182 };
9183
9184 /**
9185 * Set group element is in.
9186 *
9187 * @param {OO.ui.GroupElement|null} group Group element, null if none
9188 * @chainable
9189 */
9190 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
9191 // Parent method
9192 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9193 OO.ui.Element.prototype.setElementGroup.call( this, group );
9194
9195 // Initialize item disabled states
9196 this.updateDisabled();
9197
9198 return this;
9199 };
9200
9201 /**
9202 * Mixin that adds a menu showing suggested values for a text input.
9203 *
9204 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
9205 *
9206 * Subclasses that set the value of #lookupInput from their `choose` or `select` handler should
9207 * be aware that this will cause new suggestions to be looked up for the new value. If this is
9208 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
9209 *
9210 * @class
9211 * @abstract
9212 * @deprecated Use LookupElement instead.
9213 *
9214 * @constructor
9215 * @param {OO.ui.TextInputWidget} input Input widget
9216 * @param {Object} [config] Configuration options
9217 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
9218 * @cfg {jQuery} [$container=input.$element] Element to render menu under
9219 */
9220 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
9221 // Configuration initialization
9222 config = config || {};
9223
9224 // Properties
9225 this.lookupInput = input;
9226 this.$overlay = config.$overlay || this.$element;
9227 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
9228 $: OO.ui.Element.static.getJQuery( this.$overlay ),
9229 input: this.lookupInput,
9230 $container: config.$container
9231 } );
9232 this.lookupCache = {};
9233 this.lookupQuery = null;
9234 this.lookupRequest = null;
9235 this.lookupsDisabled = false;
9236 this.lookupInputFocused = false;
9237
9238 // Events
9239 this.lookupInput.$input.on( {
9240 focus: this.onLookupInputFocus.bind( this ),
9241 blur: this.onLookupInputBlur.bind( this ),
9242 mousedown: this.onLookupInputMouseDown.bind( this )
9243 } );
9244 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
9245 this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle' } );
9246
9247 // Initialization
9248 this.$element.addClass( 'oo-ui-lookupWidget' );
9249 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
9250 this.$overlay.append( this.lookupMenu.$element );
9251 };
9252
9253 /* Methods */
9254
9255 /**
9256 * Handle input focus event.
9257 *
9258 * @param {jQuery.Event} e Input focus event
9259 */
9260 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
9261 this.lookupInputFocused = true;
9262 this.populateLookupMenu();
9263 };
9264
9265 /**
9266 * Handle input blur event.
9267 *
9268 * @param {jQuery.Event} e Input blur event
9269 */
9270 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
9271 this.closeLookupMenu();
9272 this.lookupInputFocused = false;
9273 };
9274
9275 /**
9276 * Handle input mouse down event.
9277 *
9278 * @param {jQuery.Event} e Input mouse down event
9279 */
9280 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
9281 // Only open the menu if the input was already focused.
9282 // This way we allow the user to open the menu again after closing it with Esc
9283 // by clicking in the input. Opening (and populating) the menu when initially
9284 // clicking into the input is handled by the focus handler.
9285 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
9286 this.populateLookupMenu();
9287 }
9288 };
9289
9290 /**
9291 * Handle input change event.
9292 *
9293 * @param {string} value New input value
9294 */
9295 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
9296 if ( this.lookupInputFocused ) {
9297 this.populateLookupMenu();
9298 }
9299 };
9300
9301 /**
9302 * Handle the lookup menu being shown/hidden.
9303 * @param {boolean} visible Whether the lookup menu is now visible.
9304 */
9305 OO.ui.LookupInputWidget.prototype.onLookupMenuToggle = function ( visible ) {
9306 if ( !visible ) {
9307 // When the menu is hidden, abort any active request and clear the menu.
9308 // This has to be done here in addition to closeLookupMenu(), because
9309 // MenuSelectWidget will close itself when the user presses Esc.
9310 this.abortLookupRequest();
9311 this.lookupMenu.clearItems();
9312 }
9313 };
9314
9315 /**
9316 * Get lookup menu.
9317 *
9318 * @return {OO.ui.TextInputMenuSelectWidget}
9319 */
9320 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
9321 return this.lookupMenu;
9322 };
9323
9324 /**
9325 * Disable or re-enable lookups.
9326 *
9327 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
9328 *
9329 * @param {boolean} disabled Disable lookups
9330 */
9331 OO.ui.LookupInputWidget.prototype.setLookupsDisabled = function ( disabled ) {
9332 this.lookupsDisabled = !!disabled;
9333 };
9334
9335 /**
9336 * Open the menu. If there are no entries in the menu, this does nothing.
9337 *
9338 * @chainable
9339 */
9340 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
9341 if ( !this.lookupMenu.isEmpty() ) {
9342 this.lookupMenu.toggle( true );
9343 }
9344 return this;
9345 };
9346
9347 /**
9348 * Close the menu, empty it, and abort any pending request.
9349 *
9350 * @chainable
9351 */
9352 OO.ui.LookupInputWidget.prototype.closeLookupMenu = function () {
9353 this.lookupMenu.toggle( false );
9354 this.abortLookupRequest();
9355 this.lookupMenu.clearItems();
9356 return this;
9357 };
9358
9359 /**
9360 * Request menu items based on the input's current value, and when they arrive,
9361 * populate the menu with these items and show the menu.
9362 *
9363 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
9364 *
9365 * @chainable
9366 */
9367 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
9368 var widget = this,
9369 value = this.lookupInput.getValue();
9370
9371 if ( this.lookupsDisabled ) {
9372 return;
9373 }
9374
9375 // If the input is empty, clear the menu
9376 if ( value === '' ) {
9377 this.closeLookupMenu();
9378 // Skip population if there is already a request pending for the current value
9379 } else if ( value !== this.lookupQuery ) {
9380 this.getLookupMenuItems()
9381 .done( function ( items ) {
9382 widget.lookupMenu.clearItems();
9383 if ( items.length ) {
9384 widget.lookupMenu
9385 .addItems( items )
9386 .toggle( true );
9387 widget.initializeLookupMenuSelection();
9388 } else {
9389 widget.lookupMenu.toggle( false );
9390 }
9391 } )
9392 .fail( function () {
9393 widget.lookupMenu.clearItems();
9394 } );
9395 }
9396
9397 return this;
9398 };
9399
9400 /**
9401 * Select and highlight the first selectable item in the menu.
9402 *
9403 * @chainable
9404 */
9405 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
9406 if ( !this.lookupMenu.getSelectedItem() ) {
9407 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
9408 }
9409 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
9410 };
9411
9412 /**
9413 * Get lookup menu items for the current query.
9414 *
9415 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
9416 * of the done event. If the request was aborted to make way for a subsequent request,
9417 * this promise will not be rejected: it will remain pending forever.
9418 */
9419 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
9420 var widget = this,
9421 value = this.lookupInput.getValue(),
9422 deferred = $.Deferred(),
9423 ourRequest;
9424
9425 this.abortLookupRequest();
9426 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
9427 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[ value ] ) );
9428 } else {
9429 this.lookupInput.pushPending();
9430 this.lookupQuery = value;
9431 ourRequest = this.lookupRequest = this.getLookupRequest();
9432 ourRequest
9433 .always( function () {
9434 // We need to pop pending even if this is an old request, otherwise
9435 // the widget will remain pending forever.
9436 // TODO: this assumes that an aborted request will fail or succeed soon after
9437 // being aborted, or at least eventually. It would be nice if we could popPending()
9438 // at abort time, but only if we knew that we hadn't already called popPending()
9439 // for that request.
9440 widget.lookupInput.popPending();
9441 } )
9442 .done( function ( data ) {
9443 // If this is an old request (and aborting it somehow caused it to still succeed),
9444 // ignore its success completely
9445 if ( ourRequest === widget.lookupRequest ) {
9446 widget.lookupQuery = null;
9447 widget.lookupRequest = null;
9448 widget.lookupCache[ value ] = widget.getLookupCacheItemFromData( data );
9449 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[ value ] ) );
9450 }
9451 } )
9452 .fail( function () {
9453 // If this is an old request (or a request failing because it's being aborted),
9454 // ignore its failure completely
9455 if ( ourRequest === widget.lookupRequest ) {
9456 widget.lookupQuery = null;
9457 widget.lookupRequest = null;
9458 deferred.reject();
9459 }
9460 } );
9461 }
9462 return deferred.promise();
9463 };
9464
9465 /**
9466 * Abort the currently pending lookup request, if any.
9467 */
9468 OO.ui.LookupInputWidget.prototype.abortLookupRequest = function () {
9469 var oldRequest = this.lookupRequest;
9470 if ( oldRequest ) {
9471 // First unset this.lookupRequest to the fail handler will notice
9472 // that the request is no longer current
9473 this.lookupRequest = null;
9474 this.lookupQuery = null;
9475 oldRequest.abort();
9476 }
9477 };
9478
9479 /**
9480 * Get a new request object of the current lookup query value.
9481 *
9482 * @abstract
9483 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
9484 */
9485 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
9486 // Stub, implemented in subclass
9487 return null;
9488 };
9489
9490 /**
9491 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
9492 *
9493 * @abstract
9494 * @param {Mixed} data Cached result data, usually an array
9495 * @return {OO.ui.MenuOptionWidget[]} Menu items
9496 */
9497 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
9498 // Stub, implemented in subclass
9499 return [];
9500 };
9501
9502 /**
9503 * Get lookup cache item from server response data.
9504 *
9505 * @abstract
9506 * @param {Mixed} data Response from server
9507 * @return {Mixed} Cached result data
9508 */
9509 OO.ui.LookupInputWidget.prototype.getLookupCacheItemFromData = function () {
9510 // Stub, implemented in subclass
9511 return [];
9512 };
9513
9514 /**
9515 * Set of controls for an OO.ui.OutlineSelectWidget.
9516 *
9517 * Controls include moving items up and down, removing items, and adding different kinds of items.
9518 *
9519 * @class
9520 * @extends OO.ui.Widget
9521 * @mixins OO.ui.GroupElement
9522 * @mixins OO.ui.IconElement
9523 *
9524 * @constructor
9525 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9526 * @param {Object} [config] Configuration options
9527 */
9528 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9529 // Configuration initialization
9530 config = $.extend( { icon: 'add' }, config );
9531
9532 // Parent constructor
9533 OO.ui.OutlineControlsWidget.super.call( this, config );
9534
9535 // Mixin constructors
9536 OO.ui.GroupElement.call( this, config );
9537 OO.ui.IconElement.call( this, config );
9538
9539 // Properties
9540 this.outline = outline;
9541 this.$movers = this.$( '<div>' );
9542 this.upButton = new OO.ui.ButtonWidget( {
9543 $: this.$,
9544 framed: false,
9545 icon: 'collapse',
9546 title: OO.ui.msg( 'ooui-outline-control-move-up' )
9547 } );
9548 this.downButton = new OO.ui.ButtonWidget( {
9549 $: this.$,
9550 framed: false,
9551 icon: 'expand',
9552 title: OO.ui.msg( 'ooui-outline-control-move-down' )
9553 } );
9554 this.removeButton = new OO.ui.ButtonWidget( {
9555 $: this.$,
9556 framed: false,
9557 icon: 'remove',
9558 title: OO.ui.msg( 'ooui-outline-control-remove' )
9559 } );
9560
9561 // Events
9562 outline.connect( this, {
9563 select: 'onOutlineChange',
9564 add: 'onOutlineChange',
9565 remove: 'onOutlineChange'
9566 } );
9567 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
9568 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
9569 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
9570
9571 // Initialization
9572 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
9573 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
9574 this.$movers
9575 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9576 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
9577 this.$element.append( this.$icon, this.$group, this.$movers );
9578 };
9579
9580 /* Setup */
9581
9582 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
9583 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
9584 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
9585
9586 /* Events */
9587
9588 /**
9589 * @event move
9590 * @param {number} places Number of places to move
9591 */
9592
9593 /**
9594 * @event remove
9595 */
9596
9597 /* Methods */
9598
9599 /**
9600 * Handle outline change events.
9601 */
9602 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
9603 var i, len, firstMovable, lastMovable,
9604 items = this.outline.getItems(),
9605 selectedItem = this.outline.getSelectedItem(),
9606 movable = selectedItem && selectedItem.isMovable(),
9607 removable = selectedItem && selectedItem.isRemovable();
9608
9609 if ( movable ) {
9610 i = -1;
9611 len = items.length;
9612 while ( ++i < len ) {
9613 if ( items[ i ].isMovable() ) {
9614 firstMovable = items[ i ];
9615 break;
9616 }
9617 }
9618 i = len;
9619 while ( i-- ) {
9620 if ( items[ i ].isMovable() ) {
9621 lastMovable = items[ i ];
9622 break;
9623 }
9624 }
9625 }
9626 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
9627 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
9628 this.removeButton.setDisabled( !removable );
9629 };
9630
9631 /**
9632 * Mixin for widgets with a boolean on/off state.
9633 *
9634 * @abstract
9635 * @class
9636 *
9637 * @constructor
9638 * @param {Object} [config] Configuration options
9639 * @cfg {boolean} [value=false] Initial value
9640 */
9641 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
9642 // Configuration initialization
9643 config = config || {};
9644
9645 // Properties
9646 this.value = null;
9647
9648 // Initialization
9649 this.$element.addClass( 'oo-ui-toggleWidget' );
9650 this.setValue( !!config.value );
9651 };
9652
9653 /* Events */
9654
9655 /**
9656 * @event change
9657 * @param {boolean} value Changed value
9658 */
9659
9660 /* Methods */
9661
9662 /**
9663 * Get the value of the toggle.
9664 *
9665 * @return {boolean}
9666 */
9667 OO.ui.ToggleWidget.prototype.getValue = function () {
9668 return this.value;
9669 };
9670
9671 /**
9672 * Set the value of the toggle.
9673 *
9674 * @param {boolean} value New value
9675 * @fires change
9676 * @chainable
9677 */
9678 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
9679 value = !!value;
9680 if ( this.value !== value ) {
9681 this.value = value;
9682 this.emit( 'change', value );
9683 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
9684 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
9685 this.$element.attr( 'aria-checked', value.toString() );
9686 }
9687 return this;
9688 };
9689
9690 /**
9691 * Group widget for multiple related buttons.
9692 *
9693 * Use together with OO.ui.ButtonWidget.
9694 *
9695 * @class
9696 * @extends OO.ui.Widget
9697 * @mixins OO.ui.GroupElement
9698 *
9699 * @constructor
9700 * @param {Object} [config] Configuration options
9701 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
9702 */
9703 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
9704 // Configuration initialization
9705 config = config || {};
9706
9707 // Parent constructor
9708 OO.ui.ButtonGroupWidget.super.call( this, config );
9709
9710 // Mixin constructors
9711 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9712
9713 // Initialization
9714 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
9715 if ( $.isArray( config.items ) ) {
9716 this.addItems( config.items );
9717 }
9718 };
9719
9720 /* Setup */
9721
9722 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
9723 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
9724
9725 /**
9726 * Generic widget for buttons.
9727 *
9728 * @class
9729 * @extends OO.ui.Widget
9730 * @mixins OO.ui.ButtonElement
9731 * @mixins OO.ui.IconElement
9732 * @mixins OO.ui.IndicatorElement
9733 * @mixins OO.ui.LabelElement
9734 * @mixins OO.ui.TitledElement
9735 * @mixins OO.ui.FlaggedElement
9736 * @mixins OO.ui.TabIndexedElement
9737 *
9738 * @constructor
9739 * @param {Object} [config] Configuration options
9740 * @cfg {string} [href] Hyperlink to visit when clicked
9741 * @cfg {string} [target] Target to open hyperlink in
9742 */
9743 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
9744 // Configuration initialization
9745 config = config || {};
9746
9747 // Parent constructor
9748 OO.ui.ButtonWidget.super.call( this, config );
9749
9750 // Mixin constructors
9751 OO.ui.ButtonElement.call( this, config );
9752 OO.ui.IconElement.call( this, config );
9753 OO.ui.IndicatorElement.call( this, config );
9754 OO.ui.LabelElement.call( this, config );
9755 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
9756 OO.ui.FlaggedElement.call( this, config );
9757 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
9758
9759 // Properties
9760 this.href = null;
9761 this.target = null;
9762 this.isHyperlink = false;
9763
9764 // Events
9765 this.$button.on( {
9766 click: this.onClick.bind( this ),
9767 keypress: this.onKeyPress.bind( this )
9768 } );
9769
9770 // Initialization
9771 this.$button.append( this.$icon, this.$label, this.$indicator );
9772 this.$element
9773 .addClass( 'oo-ui-buttonWidget' )
9774 .append( this.$button );
9775 this.setHref( config.href );
9776 this.setTarget( config.target );
9777 };
9778
9779 /* Setup */
9780
9781 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
9782 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
9783 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
9784 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
9785 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
9786 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
9787 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
9788 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
9789
9790 /* Events */
9791
9792 /**
9793 * @event click
9794 */
9795
9796 /* Methods */
9797
9798 /**
9799 * Handles mouse click events.
9800 *
9801 * @param {jQuery.Event} e Mouse click event
9802 * @fires click
9803 */
9804 OO.ui.ButtonWidget.prototype.onClick = function () {
9805 if ( !this.isDisabled() ) {
9806 this.emit( 'click' );
9807 if ( this.isHyperlink ) {
9808 return true;
9809 }
9810 }
9811 return false;
9812 };
9813
9814 /**
9815 * @inheritdoc
9816 */
9817 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
9818 // Remove the tab-index while the button is down to prevent the button from stealing focus
9819 this.$button.removeAttr( 'tabindex' );
9820 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
9821 };
9822
9823 /**
9824 * @inheritdoc
9825 */
9826 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
9827 // Restore the tab-index after the button is up to restore the button's accessibility
9828 this.$button.attr( 'tabindex', this.tabIndex );
9829 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
9830 };
9831
9832 /**
9833 * Handles keypress events.
9834 *
9835 * @param {jQuery.Event} e Keypress event
9836 * @fires click
9837 */
9838 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
9839 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
9840 this.emit( 'click' );
9841 if ( this.isHyperlink ) {
9842 return true;
9843 }
9844 }
9845 return false;
9846 };
9847
9848 /**
9849 * Get hyperlink location.
9850 *
9851 * @return {string} Hyperlink location
9852 */
9853 OO.ui.ButtonWidget.prototype.getHref = function () {
9854 return this.href;
9855 };
9856
9857 /**
9858 * Get hyperlink target.
9859 *
9860 * @return {string} Hyperlink target
9861 */
9862 OO.ui.ButtonWidget.prototype.getTarget = function () {
9863 return this.target;
9864 };
9865
9866 /**
9867 * Set hyperlink location.
9868 *
9869 * @param {string|null} href Hyperlink location, null to remove
9870 */
9871 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
9872 href = typeof href === 'string' ? href : null;
9873
9874 if ( href !== this.href ) {
9875 this.href = href;
9876 if ( href !== null ) {
9877 this.$button.attr( 'href', href );
9878 this.isHyperlink = true;
9879 } else {
9880 this.$button.removeAttr( 'href' );
9881 this.isHyperlink = false;
9882 }
9883 }
9884
9885 return this;
9886 };
9887
9888 /**
9889 * Set hyperlink target.
9890 *
9891 * @param {string|null} target Hyperlink target, null to remove
9892 */
9893 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
9894 target = typeof target === 'string' ? target : null;
9895
9896 if ( target !== this.target ) {
9897 this.target = target;
9898 if ( target !== null ) {
9899 this.$button.attr( 'target', target );
9900 } else {
9901 this.$button.removeAttr( 'target' );
9902 }
9903 }
9904
9905 return this;
9906 };
9907
9908 /**
9909 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
9910 *
9911 * @class
9912 * @extends OO.ui.ButtonWidget
9913 * @mixins OO.ui.PendingElement
9914 *
9915 * @constructor
9916 * @param {Object} [config] Configuration options
9917 * @cfg {string} [action] Symbolic action name
9918 * @cfg {string[]} [modes] Symbolic mode names
9919 * @cfg {boolean} [framed=false] Render button with a frame
9920 */
9921 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
9922 // Configuration initialization
9923 config = $.extend( { framed: false }, config );
9924
9925 // Parent constructor
9926 OO.ui.ActionWidget.super.call( this, config );
9927
9928 // Mixin constructors
9929 OO.ui.PendingElement.call( this, config );
9930
9931 // Properties
9932 this.action = config.action || '';
9933 this.modes = config.modes || [];
9934 this.width = 0;
9935 this.height = 0;
9936
9937 // Initialization
9938 this.$element.addClass( 'oo-ui-actionWidget' );
9939 };
9940
9941 /* Setup */
9942
9943 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
9944 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
9945
9946 /* Events */
9947
9948 /**
9949 * @event resize
9950 */
9951
9952 /* Methods */
9953
9954 /**
9955 * Check if action is available in a certain mode.
9956 *
9957 * @param {string} mode Name of mode
9958 * @return {boolean} Has mode
9959 */
9960 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
9961 return this.modes.indexOf( mode ) !== -1;
9962 };
9963
9964 /**
9965 * Get symbolic action name.
9966 *
9967 * @return {string}
9968 */
9969 OO.ui.ActionWidget.prototype.getAction = function () {
9970 return this.action;
9971 };
9972
9973 /**
9974 * Get symbolic action name.
9975 *
9976 * @return {string}
9977 */
9978 OO.ui.ActionWidget.prototype.getModes = function () {
9979 return this.modes.slice();
9980 };
9981
9982 /**
9983 * Emit a resize event if the size has changed.
9984 *
9985 * @chainable
9986 */
9987 OO.ui.ActionWidget.prototype.propagateResize = function () {
9988 var width, height;
9989
9990 if ( this.isElementAttached() ) {
9991 width = this.$element.width();
9992 height = this.$element.height();
9993
9994 if ( width !== this.width || height !== this.height ) {
9995 this.width = width;
9996 this.height = height;
9997 this.emit( 'resize' );
9998 }
9999 }
10000
10001 return this;
10002 };
10003
10004 /**
10005 * @inheritdoc
10006 */
10007 OO.ui.ActionWidget.prototype.setIcon = function () {
10008 // Mixin method
10009 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10010 this.propagateResize();
10011
10012 return this;
10013 };
10014
10015 /**
10016 * @inheritdoc
10017 */
10018 OO.ui.ActionWidget.prototype.setLabel = function () {
10019 // Mixin method
10020 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10021 this.propagateResize();
10022
10023 return this;
10024 };
10025
10026 /**
10027 * @inheritdoc
10028 */
10029 OO.ui.ActionWidget.prototype.setFlags = function () {
10030 // Mixin method
10031 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10032 this.propagateResize();
10033
10034 return this;
10035 };
10036
10037 /**
10038 * @inheritdoc
10039 */
10040 OO.ui.ActionWidget.prototype.clearFlags = function () {
10041 // Mixin method
10042 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10043 this.propagateResize();
10044
10045 return this;
10046 };
10047
10048 /**
10049 * Toggle visibility of button.
10050 *
10051 * @param {boolean} [show] Show button, omit to toggle visibility
10052 * @chainable
10053 */
10054 OO.ui.ActionWidget.prototype.toggle = function () {
10055 // Parent method
10056 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10057 this.propagateResize();
10058
10059 return this;
10060 };
10061
10062 /**
10063 * Button that shows and hides a popup.
10064 *
10065 * @class
10066 * @extends OO.ui.ButtonWidget
10067 * @mixins OO.ui.PopupElement
10068 *
10069 * @constructor
10070 * @param {Object} [config] Configuration options
10071 */
10072 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10073 // Parent constructor
10074 OO.ui.PopupButtonWidget.super.call( this, config );
10075
10076 // Mixin constructors
10077 OO.ui.PopupElement.call( this, config );
10078
10079 // Initialization
10080 this.$element
10081 .addClass( 'oo-ui-popupButtonWidget' )
10082 .attr( 'aria-haspopup', 'true' )
10083 .append( this.popup.$element );
10084 };
10085
10086 /* Setup */
10087
10088 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10089 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10090
10091 /* Methods */
10092
10093 /**
10094 * Handles mouse click events.
10095 *
10096 * @param {jQuery.Event} e Mouse click event
10097 */
10098 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
10099 // Skip clicks within the popup
10100 if ( $.contains( this.popup.$element[ 0 ], e.target ) ) {
10101 return;
10102 }
10103
10104 if ( !this.isDisabled() ) {
10105 this.popup.toggle();
10106 // Parent method
10107 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
10108 }
10109 return false;
10110 };
10111
10112 /**
10113 * Button that toggles on and off.
10114 *
10115 * @class
10116 * @extends OO.ui.ButtonWidget
10117 * @mixins OO.ui.ToggleWidget
10118 *
10119 * @constructor
10120 * @param {Object} [config] Configuration options
10121 * @cfg {boolean} [value=false] Initial value
10122 */
10123 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10124 // Configuration initialization
10125 config = config || {};
10126
10127 // Parent constructor
10128 OO.ui.ToggleButtonWidget.super.call( this, config );
10129
10130 // Mixin constructors
10131 OO.ui.ToggleWidget.call( this, config );
10132
10133 // Initialization
10134 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10135 };
10136
10137 /* Setup */
10138
10139 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10140 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10141
10142 /* Methods */
10143
10144 /**
10145 * @inheritdoc
10146 */
10147 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
10148 if ( !this.isDisabled() ) {
10149 this.setValue( !this.value );
10150 }
10151
10152 // Parent method
10153 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
10154 };
10155
10156 /**
10157 * @inheritdoc
10158 */
10159 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10160 value = !!value;
10161 if ( value !== this.value ) {
10162 this.$button.attr( 'aria-pressed', value.toString() );
10163 this.setActive( value );
10164 }
10165
10166 // Parent method (from mixin)
10167 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10168
10169 return this;
10170 };
10171
10172 /**
10173 * Dropdown menu of options.
10174 *
10175 * Dropdown menus provide a control for accessing a menu and compose a menu within the widget, which
10176 * can be accessed using the #getMenu method.
10177 *
10178 * Use with OO.ui.MenuOptionWidget.
10179 *
10180 * @class
10181 * @extends OO.ui.Widget
10182 * @mixins OO.ui.IconElement
10183 * @mixins OO.ui.IndicatorElement
10184 * @mixins OO.ui.LabelElement
10185 * @mixins OO.ui.TitledElement
10186 *
10187 * @constructor
10188 * @param {Object} [config] Configuration options
10189 * @cfg {Object} [menu] Configuration options to pass to menu widget
10190 */
10191 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10192 // Configuration initialization
10193 config = $.extend( { indicator: 'down' }, config );
10194
10195 // Parent constructor
10196 OO.ui.DropdownWidget.super.call( this, config );
10197
10198 // Mixin constructors
10199 OO.ui.IconElement.call( this, config );
10200 OO.ui.IndicatorElement.call( this, config );
10201 OO.ui.LabelElement.call( this, config );
10202 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10203
10204 // Properties
10205 this.menu = new OO.ui.MenuSelectWidget( $.extend( { $: this.$, widget: this }, config.menu ) );
10206 this.$handle = this.$( '<span>' );
10207
10208 // Events
10209 this.$element.on( { click: this.onClick.bind( this ) } );
10210 this.menu.connect( this, { select: 'onMenuSelect' } );
10211
10212 // Initialization
10213 this.$handle
10214 .addClass( 'oo-ui-dropdownWidget-handle' )
10215 .append( this.$icon, this.$label, this.$indicator );
10216 this.$element
10217 .addClass( 'oo-ui-dropdownWidget' )
10218 .append( this.$handle, this.menu.$element );
10219 };
10220
10221 /* Setup */
10222
10223 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10224 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10225 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10226 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10227 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10228
10229 /* Methods */
10230
10231 /**
10232 * Get the menu.
10233 *
10234 * @return {OO.ui.MenuSelectWidget} Menu of widget
10235 */
10236 OO.ui.DropdownWidget.prototype.getMenu = function () {
10237 return this.menu;
10238 };
10239
10240 /**
10241 * Handles menu select events.
10242 *
10243 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10244 */
10245 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10246 var selectedLabel;
10247
10248 if ( !item ) {
10249 return;
10250 }
10251
10252 selectedLabel = item.getLabel();
10253
10254 // If the label is a DOM element, clone it, because setLabel will append() it
10255 if ( selectedLabel instanceof jQuery ) {
10256 selectedLabel = selectedLabel.clone();
10257 }
10258
10259 this.setLabel( selectedLabel );
10260 };
10261
10262 /**
10263 * Handles mouse click events.
10264 *
10265 * @param {jQuery.Event} e Mouse click event
10266 */
10267 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10268 // Skip clicks within the menu
10269 if ( $.contains( this.menu.$element[ 0 ], e.target ) ) {
10270 return;
10271 }
10272
10273 if ( !this.isDisabled() ) {
10274 if ( this.menu.isVisible() ) {
10275 this.menu.toggle( false );
10276 } else {
10277 this.menu.toggle( true );
10278 }
10279 }
10280 return false;
10281 };
10282
10283 /**
10284 * Icon widget.
10285 *
10286 * See OO.ui.IconElement for more information.
10287 *
10288 * @class
10289 * @extends OO.ui.Widget
10290 * @mixins OO.ui.IconElement
10291 * @mixins OO.ui.TitledElement
10292 *
10293 * @constructor
10294 * @param {Object} [config] Configuration options
10295 */
10296 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10297 // Configuration initialization
10298 config = config || {};
10299
10300 // Parent constructor
10301 OO.ui.IconWidget.super.call( this, config );
10302
10303 // Mixin constructors
10304 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10305 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10306
10307 // Initialization
10308 this.$element.addClass( 'oo-ui-iconWidget' );
10309 };
10310
10311 /* Setup */
10312
10313 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10314 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
10315 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
10316
10317 /* Static Properties */
10318
10319 OO.ui.IconWidget.static.tagName = 'span';
10320
10321 /**
10322 * Indicator widget.
10323 *
10324 * See OO.ui.IndicatorElement for more information.
10325 *
10326 * @class
10327 * @extends OO.ui.Widget
10328 * @mixins OO.ui.IndicatorElement
10329 * @mixins OO.ui.TitledElement
10330 *
10331 * @constructor
10332 * @param {Object} [config] Configuration options
10333 */
10334 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
10335 // Configuration initialization
10336 config = config || {};
10337
10338 // Parent constructor
10339 OO.ui.IndicatorWidget.super.call( this, config );
10340
10341 // Mixin constructors
10342 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
10343 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10344
10345 // Initialization
10346 this.$element.addClass( 'oo-ui-indicatorWidget' );
10347 };
10348
10349 /* Setup */
10350
10351 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
10352 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
10353 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
10354
10355 /* Static Properties */
10356
10357 OO.ui.IndicatorWidget.static.tagName = 'span';
10358
10359 /**
10360 * Base class for input widgets.
10361 *
10362 * @abstract
10363 * @class
10364 * @extends OO.ui.Widget
10365 * @mixins OO.ui.FlaggedElement
10366 * @mixins OO.ui.TabIndexedElement
10367 *
10368 * @constructor
10369 * @param {Object} [config] Configuration options
10370 * @cfg {string} [name=''] HTML input name
10371 * @cfg {string} [value=''] Input value
10372 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
10373 */
10374 OO.ui.InputWidget = function OoUiInputWidget( config ) {
10375 // Configuration initialization
10376 config = config || {};
10377
10378 // Parent constructor
10379 OO.ui.InputWidget.super.call( this, config );
10380
10381 // Properties
10382 this.$input = this.getInputElement( config );
10383 this.value = '';
10384 this.inputFilter = config.inputFilter;
10385
10386 // Mixin constructors
10387 OO.ui.FlaggedElement.call( this, config );
10388 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
10389
10390 // Events
10391 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
10392
10393 // Initialization
10394 this.$input
10395 .attr( 'name', config.name )
10396 .prop( 'disabled', this.isDisabled() );
10397 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
10398 this.setValue( config.value );
10399 };
10400
10401 /* Setup */
10402
10403 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
10404 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
10405 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
10406
10407 /* Events */
10408
10409 /**
10410 * @event change
10411 * @param {string} value
10412 */
10413
10414 /* Methods */
10415
10416 /**
10417 * Get input element.
10418 *
10419 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10420 * different circumstances. The element must have a `value` property (like form elements).
10421 *
10422 * @private
10423 * @param {Object} config Configuration options
10424 * @return {jQuery} Input element
10425 */
10426 OO.ui.InputWidget.prototype.getInputElement = function () {
10427 return this.$( '<input>' );
10428 };
10429
10430 /**
10431 * Handle potentially value-changing events.
10432 *
10433 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10434 */
10435 OO.ui.InputWidget.prototype.onEdit = function () {
10436 var widget = this;
10437 if ( !this.isDisabled() ) {
10438 // Allow the stack to clear so the value will be updated
10439 setTimeout( function () {
10440 widget.setValue( widget.$input.val() );
10441 } );
10442 }
10443 };
10444
10445 /**
10446 * Get the value of the input.
10447 *
10448 * @return {string} Input value
10449 */
10450 OO.ui.InputWidget.prototype.getValue = function () {
10451 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10452 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10453 var value = this.$input.val();
10454 if ( this.value !== value ) {
10455 this.setValue( value );
10456 }
10457 return this.value;
10458 };
10459
10460 /**
10461 * Sets the direction of the current input, either RTL or LTR
10462 *
10463 * @param {boolean} isRTL
10464 */
10465 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
10466 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
10467 };
10468
10469 /**
10470 * Set the value of the input.
10471 *
10472 * @param {string} value New value
10473 * @fires change
10474 * @chainable
10475 */
10476 OO.ui.InputWidget.prototype.setValue = function ( value ) {
10477 value = this.cleanUpValue( value );
10478 // Update the DOM if it has changed. Note that with cleanUpValue, it
10479 // is possible for the DOM value to change without this.value changing.
10480 if ( this.$input.val() !== value ) {
10481 this.$input.val( value );
10482 }
10483 if ( this.value !== value ) {
10484 this.value = value;
10485 this.emit( 'change', this.value );
10486 }
10487 return this;
10488 };
10489
10490 /**
10491 * Clean up incoming value.
10492 *
10493 * Ensures value is a string, and converts undefined and null to empty string.
10494 *
10495 * @private
10496 * @param {string} value Original value
10497 * @return {string} Cleaned up value
10498 */
10499 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
10500 if ( value === undefined || value === null ) {
10501 return '';
10502 } else if ( this.inputFilter ) {
10503 return this.inputFilter( String( value ) );
10504 } else {
10505 return String( value );
10506 }
10507 };
10508
10509 /**
10510 * Simulate the behavior of clicking on a label bound to this input.
10511 */
10512 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
10513 if ( !this.isDisabled() ) {
10514 if ( this.$input.is( ':checkbox,:radio' ) ) {
10515 this.$input.click();
10516 } else if ( this.$input.is( ':input' ) ) {
10517 this.$input[ 0 ].focus();
10518 }
10519 }
10520 };
10521
10522 /**
10523 * @inheritdoc
10524 */
10525 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
10526 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
10527 if ( this.$input ) {
10528 this.$input.prop( 'disabled', this.isDisabled() );
10529 }
10530 return this;
10531 };
10532
10533 /**
10534 * Focus the input.
10535 *
10536 * @chainable
10537 */
10538 OO.ui.InputWidget.prototype.focus = function () {
10539 this.$input[ 0 ].focus();
10540 return this;
10541 };
10542
10543 /**
10544 * Blur the input.
10545 *
10546 * @chainable
10547 */
10548 OO.ui.InputWidget.prototype.blur = function () {
10549 this.$input[ 0 ].blur();
10550 return this;
10551 };
10552
10553 /**
10554 * A button that is an input widget. Intended to be used within a OO.ui.FormLayout.
10555 *
10556 * @class
10557 * @extends OO.ui.InputWidget
10558 * @mixins OO.ui.ButtonElement
10559 * @mixins OO.ui.IconElement
10560 * @mixins OO.ui.IndicatorElement
10561 * @mixins OO.ui.LabelElement
10562 * @mixins OO.ui.TitledElement
10563 * @mixins OO.ui.FlaggedElement
10564 *
10565 * @constructor
10566 * @param {Object} [config] Configuration options
10567 * @cfg {string} [type='button'] HTML tag `type` attribute, may be 'button', 'submit' or 'reset'
10568 * @cfg {boolean} [useInputTag=false] Whether to use `<input/>` rather than `<button/>`. Only useful
10569 * if you need IE 6 support in a form with multiple buttons. If you use this option, icons and
10570 * indicators will not be displayed, it won't be possible to have a non-plaintext label, and it
10571 * won't be possible to set a value (which will internally become identical to the label).
10572 */
10573 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
10574 // Configuration initialization
10575 config = $.extend( { type: 'button', useInputTag: false }, config );
10576
10577 // Properties (must be set before parent constructor, which calls #setValue)
10578 this.useInputTag = config.useInputTag;
10579
10580 // Parent constructor
10581 OO.ui.ButtonInputWidget.super.call( this, config );
10582
10583 // Mixin constructors
10584 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
10585 OO.ui.IconElement.call( this, config );
10586 OO.ui.IndicatorElement.call( this, config );
10587 OO.ui.LabelElement.call( this, config );
10588 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
10589 OO.ui.FlaggedElement.call( this, config );
10590
10591 // Events
10592 this.$input.on( {
10593 click: this.onClick.bind( this ),
10594 keypress: this.onKeyPress.bind( this )
10595 } );
10596
10597 // Initialization
10598 if ( !config.useInputTag ) {
10599 this.$input.append( this.$icon, this.$label, this.$indicator );
10600 }
10601 this.$element.addClass( 'oo-ui-buttonInputWidget' );
10602 };
10603
10604 /* Setup */
10605
10606 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
10607 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
10608 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
10609 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
10610 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
10611 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
10612 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
10613
10614 /* Events */
10615
10616 /**
10617 * @event click
10618 */
10619
10620 /* Methods */
10621
10622 /**
10623 * @inheritdoc
10624 * @private
10625 */
10626 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
10627 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
10628 return this.$( html );
10629 };
10630
10631 /**
10632 * Set label value.
10633 *
10634 * Overridden to support setting the 'value' of `<input/>` elements.
10635 *
10636 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
10637 * text; or null for no label
10638 * @chainable
10639 */
10640 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
10641 OO.ui.LabelElement.prototype.setLabel.call( this, label );
10642
10643 if ( this.useInputTag ) {
10644 if ( typeof label === 'function' ) {
10645 label = OO.ui.resolveMsg( label );
10646 }
10647 if ( label instanceof jQuery ) {
10648 label = label.text();
10649 }
10650 if ( !label ) {
10651 label = '';
10652 }
10653 this.$input.val( label );
10654 }
10655
10656 return this;
10657 };
10658
10659 /**
10660 * Set the value of the input.
10661 *
10662 * Overridden to disable for `<input/>` elements, which have value identical to the label.
10663 *
10664 * @param {string} value New value
10665 * @chainable
10666 */
10667 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
10668 if ( !this.useInputTag ) {
10669 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
10670 }
10671 return this;
10672 };
10673
10674 /**
10675 * Handles mouse click events.
10676 *
10677 * @param {jQuery.Event} e Mouse click event
10678 * @fires click
10679 */
10680 OO.ui.ButtonInputWidget.prototype.onClick = function () {
10681 if ( !this.isDisabled() ) {
10682 this.emit( 'click' );
10683 }
10684 return false;
10685 };
10686
10687 /**
10688 * Handles keypress events.
10689 *
10690 * @param {jQuery.Event} e Keypress event
10691 * @fires click
10692 */
10693 OO.ui.ButtonInputWidget.prototype.onKeyPress = function ( e ) {
10694 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10695 this.emit( 'click' );
10696 }
10697 return false;
10698 };
10699
10700 /**
10701 * Checkbox input widget.
10702 *
10703 * @class
10704 * @extends OO.ui.InputWidget
10705 *
10706 * @constructor
10707 * @param {Object} [config] Configuration options
10708 * @cfg {boolean} [selected=false] Whether the checkbox is initially selected
10709 */
10710 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
10711 // Parent constructor
10712 OO.ui.CheckboxInputWidget.super.call( this, config );
10713
10714 // Initialization
10715 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
10716 this.setSelected( config.selected !== undefined ? config.selected : false );
10717 };
10718
10719 /* Setup */
10720
10721 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
10722
10723 /* Methods */
10724
10725 /**
10726 * @inheritdoc
10727 * @private
10728 */
10729 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
10730 return this.$( '<input type="checkbox" />' );
10731 };
10732
10733 /**
10734 * @inheritdoc
10735 */
10736 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
10737 var widget = this;
10738 if ( !this.isDisabled() ) {
10739 // Allow the stack to clear so the value will be updated
10740 setTimeout( function () {
10741 widget.setSelected( widget.$input.prop( 'checked' ) );
10742 } );
10743 }
10744 };
10745
10746 /**
10747 * Set selection state of this checkbox.
10748 *
10749 * @param {boolean} state Whether the checkbox is selected
10750 * @chainable
10751 */
10752 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
10753 state = !!state;
10754 if ( this.selected !== state ) {
10755 this.selected = state;
10756 this.$input.prop( 'checked', this.selected );
10757 this.emit( 'change', this.selected );
10758 }
10759 return this;
10760 };
10761
10762 /**
10763 * Check if this checkbox is selected.
10764 *
10765 * @return {boolean} Checkbox is selected
10766 */
10767 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
10768 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10769 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10770 var selected = this.$input.prop( 'checked' );
10771 if ( this.selected !== selected ) {
10772 this.setSelected( selected );
10773 }
10774 return this.selected;
10775 };
10776
10777 /**
10778 * A OO.ui.DropdownWidget synchronized with a `<input type=hidden>` for form submission. Intended to
10779 * be used within a OO.ui.FormLayout.
10780 *
10781 * @class
10782 * @extends OO.ui.InputWidget
10783 *
10784 * @constructor
10785 * @param {Object} [config] Configuration options
10786 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10787 */
10788 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
10789 // Configuration initialization
10790 config = config || {};
10791
10792 // Properties (must be done before parent constructor which calls #setDisabled)
10793 this.dropdownWidget = new OO.ui.DropdownWidget( {
10794 $: this.$
10795 } );
10796
10797 // Parent constructor
10798 OO.ui.DropdownInputWidget.super.call( this, config );
10799
10800 // Events
10801 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
10802
10803 // Initialization
10804 this.setOptions( config.options || [] );
10805 this.$element
10806 .addClass( 'oo-ui-dropdownInputWidget' )
10807 .append( this.dropdownWidget.$element );
10808 };
10809
10810 /* Setup */
10811
10812 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
10813
10814 /* Methods */
10815
10816 /**
10817 * @inheritdoc
10818 * @private
10819 */
10820 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
10821 return this.$( '<input type="hidden">' );
10822 };
10823
10824 /**
10825 * Handles menu select events.
10826 *
10827 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10828 */
10829 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
10830 this.setValue( item.getData() );
10831 };
10832
10833 /**
10834 * @inheritdoc
10835 */
10836 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
10837 var item = this.dropdownWidget.getMenu().getItemFromData( value );
10838 if ( item ) {
10839 this.dropdownWidget.getMenu().selectItem( item );
10840 }
10841 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
10842 return this;
10843 };
10844
10845 /**
10846 * @inheritdoc
10847 */
10848 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
10849 this.dropdownWidget.setDisabled( state );
10850 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
10851 return this;
10852 };
10853
10854 /**
10855 * Set the options available for this input.
10856 *
10857 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10858 * @chainable
10859 */
10860 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
10861 var value = this.getValue();
10862
10863 // Rebuild the dropdown menu
10864 this.dropdownWidget.getMenu()
10865 .clearItems()
10866 .addItems( options.map( function ( opt ) {
10867 return new OO.ui.MenuOptionWidget( {
10868 data: opt.data,
10869 label: opt.label !== undefined ? opt.label : opt.data
10870 } );
10871 } ) );
10872
10873 // Restore the previous value, or reset to something sensible
10874 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
10875 // Previous value is still available, ensure consistency with the dropdown
10876 this.setValue( value );
10877 } else {
10878 // No longer valid, reset
10879 if ( options.length ) {
10880 this.setValue( options[ 0 ].data );
10881 }
10882 }
10883
10884 return this;
10885 };
10886
10887 /**
10888 * @inheritdoc
10889 */
10890 OO.ui.DropdownInputWidget.prototype.focus = function () {
10891 this.dropdownWidget.getMenu().toggle( true );
10892 return this;
10893 };
10894
10895 /**
10896 * @inheritdoc
10897 */
10898 OO.ui.DropdownInputWidget.prototype.blur = function () {
10899 this.dropdownWidget.getMenu().toggle( false );
10900 return this;
10901 };
10902
10903 /**
10904 * Radio input widget.
10905 *
10906 * Radio buttons only make sense as a set, and you probably want to use the OO.ui.RadioSelectWidget
10907 * class instead of using this class directly.
10908 *
10909 * @class
10910 * @extends OO.ui.InputWidget
10911 *
10912 * @constructor
10913 * @param {Object} [config] Configuration options
10914 * @cfg {boolean} [selected=false] Whether the radio button is initially selected
10915 */
10916 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
10917 // Parent constructor
10918 OO.ui.RadioInputWidget.super.call( this, config );
10919
10920 // Initialization
10921 this.$element.addClass( 'oo-ui-radioInputWidget' );
10922 this.setSelected( config.selected !== undefined ? config.selected : false );
10923 };
10924
10925 /* Setup */
10926
10927 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
10928
10929 /* Methods */
10930
10931 /**
10932 * @inheritdoc
10933 * @private
10934 */
10935 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
10936 return this.$( '<input type="radio" />' );
10937 };
10938
10939 /**
10940 * @inheritdoc
10941 */
10942 OO.ui.RadioInputWidget.prototype.onEdit = function () {
10943 // RadioInputWidget doesn't track its state.
10944 };
10945
10946 /**
10947 * Set selection state of this radio button.
10948 *
10949 * @param {boolean} state Whether the button is selected
10950 * @chainable
10951 */
10952 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
10953 // RadioInputWidget doesn't track its state.
10954 this.$input.prop( 'checked', state );
10955 return this;
10956 };
10957
10958 /**
10959 * Check if this radio button is selected.
10960 *
10961 * @return {boolean} Radio is selected
10962 */
10963 OO.ui.RadioInputWidget.prototype.isSelected = function () {
10964 return this.$input.prop( 'checked' );
10965 };
10966
10967 /**
10968 * Input widget with a text field.
10969 *
10970 * @class
10971 * @extends OO.ui.InputWidget
10972 * @mixins OO.ui.IconElement
10973 * @mixins OO.ui.IndicatorElement
10974 * @mixins OO.ui.PendingElement
10975 *
10976 * @constructor
10977 * @param {Object} [config] Configuration options
10978 * @cfg {string} [type='text'] HTML tag `type` attribute
10979 * @cfg {string} [placeholder] Placeholder text
10980 * @cfg {boolean} [autofocus=false] Ask the browser to focus this widget, using the 'autofocus' HTML
10981 * attribute
10982 * @cfg {boolean} [readOnly=false] Prevent changes
10983 * @cfg {number} [maxLength] Maximum allowed number of characters to input
10984 * @cfg {boolean} [multiline=false] Allow multiple lines of text
10985 * @cfg {boolean} [autosize=false] Automatically resize to fit content
10986 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
10987 * @cfg {string} [labelPosition='after'] Label position, 'before' or 'after'
10988 * @cfg {RegExp|string} [validate] Regular expression to validate against (or symbolic name referencing
10989 * one, see #static-validationPatterns)
10990 */
10991 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10992 // Configuration initialization
10993 config = $.extend( {
10994 type: 'text',
10995 labelPosition: 'after',
10996 maxRows: 10
10997 }, config );
10998
10999 // Parent constructor
11000 OO.ui.TextInputWidget.super.call( this, config );
11001
11002 // Mixin constructors
11003 OO.ui.IconElement.call( this, config );
11004 OO.ui.IndicatorElement.call( this, config );
11005 OO.ui.PendingElement.call( this, config );
11006 OO.ui.LabelElement.call( this, config );
11007
11008 // Properties
11009 this.readOnly = false;
11010 this.multiline = !!config.multiline;
11011 this.autosize = !!config.autosize;
11012 this.maxRows = config.maxRows;
11013 this.validate = null;
11014 this.attached = false;
11015
11016 // Clone for resizing
11017 if ( this.autosize ) {
11018 this.$clone = this.$input
11019 .clone()
11020 .insertAfter( this.$input )
11021 .hide();
11022 }
11023
11024 this.setValidation( config.validate );
11025 this.setPosition( config.labelPosition );
11026
11027 // Events
11028 this.$input.on( {
11029 keypress: this.onKeyPress.bind( this ),
11030 blur: this.setValidityFlag.bind( this )
11031 } );
11032 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
11033 this.$element.on( 'DOMNodeRemovedFromDocument', this.onElementDetach.bind( this ) );
11034 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11035 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11036 this.on( 'labelChange', this.updatePosition.bind( this ) );
11037
11038 // Initialization
11039 this.$element
11040 .addClass( 'oo-ui-textInputWidget' )
11041 .append( this.$icon, this.$indicator, this.$label );
11042 this.setReadOnly( !!config.readOnly );
11043 if ( config.placeholder ) {
11044 this.$input.attr( 'placeholder', config.placeholder );
11045 }
11046 if ( config.maxLength ) {
11047 this.$input.attr( 'maxlength', config.maxLength );
11048 }
11049 if ( config.autofocus ) {
11050 this.$input.attr( 'autofocus', 'autofocus' );
11051 }
11052 };
11053
11054 /* Setup */
11055
11056 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11057 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11058 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11059 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11060 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11061
11062 /* Static properties */
11063
11064 OO.ui.TextInputWidget.static.validationPatterns = {
11065 'non-empty': /.+/,
11066 integer: /^\d+$/
11067 };
11068
11069 /* Events */
11070
11071 /**
11072 * User presses enter inside the text box.
11073 *
11074 * Not called if input is multiline.
11075 *
11076 * @event enter
11077 */
11078
11079 /**
11080 * User clicks the icon.
11081 *
11082 * @event icon
11083 */
11084
11085 /**
11086 * User clicks the indicator.
11087 *
11088 * @event indicator
11089 */
11090
11091 /* Methods */
11092
11093 /**
11094 * Handle icon mouse down events.
11095 *
11096 * @param {jQuery.Event} e Mouse down event
11097 * @fires icon
11098 */
11099 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11100 if ( e.which === 1 ) {
11101 this.$input[ 0 ].focus();
11102 this.emit( 'icon' );
11103 return false;
11104 }
11105 };
11106
11107 /**
11108 * Handle indicator mouse down events.
11109 *
11110 * @param {jQuery.Event} e Mouse down event
11111 * @fires indicator
11112 */
11113 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11114 if ( e.which === 1 ) {
11115 this.$input[ 0 ].focus();
11116 this.emit( 'indicator' );
11117 return false;
11118 }
11119 };
11120
11121 /**
11122 * Handle key press events.
11123 *
11124 * @param {jQuery.Event} e Key press event
11125 * @fires enter If enter key is pressed and input is not multiline
11126 */
11127 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11128 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11129 this.emit( 'enter', e );
11130 }
11131 };
11132
11133 /**
11134 * Handle element attach events.
11135 *
11136 * @param {jQuery.Event} e Element attach event
11137 */
11138 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11139 this.attached = true;
11140 // If we reattached elsewhere, the valCache is now invalid
11141 this.valCache = null;
11142 this.adjustSize();
11143 this.positionLabel();
11144 };
11145
11146 /**
11147 * Handle element detach events.
11148 *
11149 * @param {jQuery.Event} e Element detach event
11150 */
11151 OO.ui.TextInputWidget.prototype.onElementDetach = function () {
11152 this.attached = false;
11153 };
11154
11155 /**
11156 * @inheritdoc
11157 */
11158 OO.ui.TextInputWidget.prototype.onEdit = function () {
11159 this.adjustSize();
11160
11161 // Parent method
11162 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11163 };
11164
11165 /**
11166 * @inheritdoc
11167 */
11168 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11169 // Parent method
11170 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11171
11172 this.setValidityFlag();
11173 this.adjustSize();
11174 return this;
11175 };
11176
11177 /**
11178 * Check if the widget is read-only.
11179 *
11180 * @return {boolean}
11181 */
11182 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11183 return this.readOnly;
11184 };
11185
11186 /**
11187 * Set the read-only state of the widget.
11188 *
11189 * This should probably change the widget's appearance and prevent it from being used.
11190 *
11191 * @param {boolean} state Make input read-only
11192 * @chainable
11193 */
11194 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11195 this.readOnly = !!state;
11196 this.$input.prop( 'readOnly', this.readOnly );
11197 return this;
11198 };
11199
11200 /**
11201 * Automatically adjust the size of the text input.
11202 *
11203 * This only affects multi-line inputs that are auto-sized.
11204 *
11205 * @chainable
11206 */
11207 OO.ui.TextInputWidget.prototype.adjustSize = function () {
11208 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
11209
11210 if ( this.multiline && this.autosize && this.attached && this.$input.val() !== this.valCache ) {
11211 this.$clone
11212 .val( this.$input.val() )
11213 .attr( 'rows', '' )
11214 // Set inline height property to 0 to measure scroll height
11215 .css( 'height', 0 );
11216
11217 this.$clone[ 0 ].style.display = 'block';
11218
11219 this.valCache = this.$input.val();
11220
11221 scrollHeight = this.$clone[ 0 ].scrollHeight;
11222
11223 // Remove inline height property to measure natural heights
11224 this.$clone.css( 'height', '' );
11225 innerHeight = this.$clone.innerHeight();
11226 outerHeight = this.$clone.outerHeight();
11227
11228 // Measure max rows height
11229 this.$clone
11230 .attr( 'rows', this.maxRows )
11231 .css( 'height', 'auto' )
11232 .val( '' );
11233 maxInnerHeight = this.$clone.innerHeight();
11234
11235 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11236 // Equals 1 on Blink-based browsers and 0 everywhere else
11237 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11238 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11239
11240 this.$clone[ 0 ].style.display = 'none';
11241
11242 // Only apply inline height when expansion beyond natural height is needed
11243 if ( idealHeight > innerHeight ) {
11244 // Use the difference between the inner and outer height as a buffer
11245 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
11246 } else {
11247 this.$input.css( 'height', '' );
11248 }
11249 }
11250 return this;
11251 };
11252
11253 /**
11254 * @inheritdoc
11255 * @private
11256 */
11257 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
11258 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="' + config.type + '" />' );
11259 };
11260
11261 /**
11262 * Check if input supports multiple lines.
11263 *
11264 * @return {boolean}
11265 */
11266 OO.ui.TextInputWidget.prototype.isMultiline = function () {
11267 return !!this.multiline;
11268 };
11269
11270 /**
11271 * Check if input automatically adjusts its size.
11272 *
11273 * @return {boolean}
11274 */
11275 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
11276 return !!this.autosize;
11277 };
11278
11279 /**
11280 * Select the contents of the input.
11281 *
11282 * @chainable
11283 */
11284 OO.ui.TextInputWidget.prototype.select = function () {
11285 this.$input.select();
11286 return this;
11287 };
11288
11289 /**
11290 * Sets the validation pattern to use.
11291 * @param {RegExp|string|null} validate Regular expression (or symbolic name referencing
11292 * one, see #static-validationPatterns)
11293 */
11294 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
11295 if ( validate instanceof RegExp ) {
11296 this.validate = validate;
11297 } else {
11298 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
11299 }
11300 };
11301
11302 /**
11303 * Sets the 'invalid' flag appropriately.
11304 */
11305 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
11306 var widget = this;
11307 this.isValid().done( function ( valid ) {
11308 widget.setFlags( { invalid: !valid } );
11309 } );
11310 };
11311
11312 /**
11313 * Returns whether or not the current value is considered valid, according to the
11314 * supplied validation pattern.
11315 *
11316 * @return {jQuery.Deferred}
11317 */
11318 OO.ui.TextInputWidget.prototype.isValid = function () {
11319 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
11320 };
11321
11322 /**
11323 * Set the position of the inline label.
11324 *
11325 * @param {string} labelPosition Label position, 'before' or 'after'
11326 * @chainable
11327 */
11328 OO.ui.TextInputWidget.prototype.setPosition = function ( labelPosition ) {
11329 this.labelPosition = labelPosition;
11330 this.updatePosition();
11331 return this;
11332 };
11333
11334 /**
11335 * Update the position of the inline label.
11336 *
11337 * @chainable
11338 */
11339 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11340 var after = this.labelPosition === 'after';
11341
11342 this.$element
11343 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', this.label && after )
11344 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', this.label && !after );
11345
11346 if ( this.label ) {
11347 this.positionLabel();
11348 }
11349
11350 return this;
11351 };
11352
11353 /**
11354 * Position the label by setting the correct padding on the input.
11355 *
11356 * @chainable
11357 */
11358 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11359 // Clear old values
11360 this.$input
11361 // Clear old values if present
11362 .css( {
11363 'padding-right': '',
11364 'padding-left': ''
11365 } );
11366
11367 if ( !this.$label.text() ) {
11368 return;
11369 }
11370
11371 var after = this.labelPosition === 'after',
11372 rtl = this.$element.css( 'direction' ) === 'rtl',
11373 property = after === rtl ? 'padding-left' : 'padding-right';
11374
11375 this.$input.css( property, this.$label.outerWidth() );
11376
11377 return this;
11378 };
11379
11380 /**
11381 * Text input with a menu of optional values.
11382 *
11383 * @class
11384 * @extends OO.ui.Widget
11385 *
11386 * @constructor
11387 * @param {Object} [config] Configuration options
11388 * @cfg {Object} [menu] Configuration options to pass to menu widget
11389 * @cfg {Object} [input] Configuration options to pass to input widget
11390 * @cfg {jQuery} [$overlay] Overlay layer; defaults to relative positioning
11391 */
11392 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
11393 // Configuration initialization
11394 config = config || {};
11395
11396 // Parent constructor
11397 OO.ui.ComboBoxWidget.super.call( this, config );
11398
11399 // Properties
11400 this.$overlay = config.$overlay || this.$element;
11401 this.input = new OO.ui.TextInputWidget( $.extend(
11402 { $: this.$, indicator: 'down', disabled: this.isDisabled() },
11403 config.input
11404 ) );
11405 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
11406 {
11407 $: OO.ui.Element.static.getJQuery( this.$overlay ),
11408 widget: this,
11409 input: this.input,
11410 disabled: this.isDisabled()
11411 },
11412 config.menu
11413 ) );
11414
11415 // Events
11416 this.input.connect( this, {
11417 change: 'onInputChange',
11418 indicator: 'onInputIndicator',
11419 enter: 'onInputEnter'
11420 } );
11421 this.menu.connect( this, {
11422 choose: 'onMenuChoose',
11423 add: 'onMenuItemsChange',
11424 remove: 'onMenuItemsChange'
11425 } );
11426
11427 // Initialization
11428 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
11429 this.$overlay.append( this.menu.$element );
11430 this.onMenuItemsChange();
11431 };
11432
11433 /* Setup */
11434
11435 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
11436
11437 /* Methods */
11438
11439 /**
11440 * Get the combobox's menu.
11441 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
11442 */
11443 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
11444 return this.menu;
11445 };
11446
11447 /**
11448 * Handle input change events.
11449 *
11450 * @param {string} value New value
11451 */
11452 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
11453 var match = this.menu.getItemFromData( value );
11454
11455 this.menu.selectItem( match );
11456
11457 if ( !this.isDisabled() ) {
11458 this.menu.toggle( true );
11459 }
11460 };
11461
11462 /**
11463 * Handle input indicator events.
11464 */
11465 OO.ui.ComboBoxWidget.prototype.onInputIndicator = function () {
11466 if ( !this.isDisabled() ) {
11467 this.menu.toggle();
11468 }
11469 };
11470
11471 /**
11472 * Handle input enter events.
11473 */
11474 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
11475 if ( !this.isDisabled() ) {
11476 this.menu.toggle( false );
11477 }
11478 };
11479
11480 /**
11481 * Handle menu choose events.
11482 *
11483 * @param {OO.ui.OptionWidget} item Chosen item
11484 */
11485 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
11486 if ( item ) {
11487 this.input.setValue( item.getData() );
11488 }
11489 };
11490
11491 /**
11492 * Handle menu item change events.
11493 */
11494 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
11495 var match = this.menu.getItemFromData( this.input.getValue() );
11496 this.menu.selectItem( match );
11497 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
11498 };
11499
11500 /**
11501 * @inheritdoc
11502 */
11503 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
11504 // Parent method
11505 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
11506
11507 if ( this.input ) {
11508 this.input.setDisabled( this.isDisabled() );
11509 }
11510 if ( this.menu ) {
11511 this.menu.setDisabled( this.isDisabled() );
11512 }
11513
11514 return this;
11515 };
11516
11517 /**
11518 * Label widget.
11519 *
11520 * @class
11521 * @extends OO.ui.Widget
11522 * @mixins OO.ui.LabelElement
11523 *
11524 * @constructor
11525 * @param {Object} [config] Configuration options
11526 * @cfg {OO.ui.InputWidget} [input] Input widget this label is for
11527 */
11528 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
11529 // Configuration initialization
11530 config = config || {};
11531
11532 // Parent constructor
11533 OO.ui.LabelWidget.super.call( this, config );
11534
11535 // Mixin constructors
11536 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
11537 OO.ui.TitledElement.call( this, config );
11538
11539 // Properties
11540 this.input = config.input;
11541
11542 // Events
11543 if ( this.input instanceof OO.ui.InputWidget ) {
11544 this.$element.on( 'click', this.onClick.bind( this ) );
11545 }
11546
11547 // Initialization
11548 this.$element.addClass( 'oo-ui-labelWidget' );
11549 };
11550
11551 /* Setup */
11552
11553 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
11554 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
11555 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
11556
11557 /* Static Properties */
11558
11559 OO.ui.LabelWidget.static.tagName = 'span';
11560
11561 /* Methods */
11562
11563 /**
11564 * Handles label mouse click events.
11565 *
11566 * @param {jQuery.Event} e Mouse click event
11567 */
11568 OO.ui.LabelWidget.prototype.onClick = function () {
11569 this.input.simulateLabelClick();
11570 return false;
11571 };
11572
11573 /**
11574 * Generic option widget for use with OO.ui.SelectWidget.
11575 *
11576 * @class
11577 * @extends OO.ui.Widget
11578 * @mixins OO.ui.LabelElement
11579 * @mixins OO.ui.FlaggedElement
11580 *
11581 * @constructor
11582 * @param {Object} [config] Configuration options
11583 */
11584 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
11585 // Configuration initialization
11586 config = config || {};
11587
11588 // Parent constructor
11589 OO.ui.OptionWidget.super.call( this, config );
11590
11591 // Mixin constructors
11592 OO.ui.ItemWidget.call( this );
11593 OO.ui.LabelElement.call( this, config );
11594 OO.ui.FlaggedElement.call( this, config );
11595
11596 // Properties
11597 this.selected = false;
11598 this.highlighted = false;
11599 this.pressed = false;
11600
11601 // Initialization
11602 this.$element
11603 .data( 'oo-ui-optionWidget', this )
11604 .attr( 'role', 'option' )
11605 .addClass( 'oo-ui-optionWidget' )
11606 .append( this.$label );
11607 };
11608
11609 /* Setup */
11610
11611 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
11612 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
11613 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
11614 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
11615
11616 /* Static Properties */
11617
11618 OO.ui.OptionWidget.static.selectable = true;
11619
11620 OO.ui.OptionWidget.static.highlightable = true;
11621
11622 OO.ui.OptionWidget.static.pressable = true;
11623
11624 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
11625
11626 /* Methods */
11627
11628 /**
11629 * Check if option can be selected.
11630 *
11631 * @return {boolean} Item is selectable
11632 */
11633 OO.ui.OptionWidget.prototype.isSelectable = function () {
11634 return this.constructor.static.selectable && !this.isDisabled();
11635 };
11636
11637 /**
11638 * Check if option can be highlighted.
11639 *
11640 * @return {boolean} Item is highlightable
11641 */
11642 OO.ui.OptionWidget.prototype.isHighlightable = function () {
11643 return this.constructor.static.highlightable && !this.isDisabled();
11644 };
11645
11646 /**
11647 * Check if option can be pressed.
11648 *
11649 * @return {boolean} Item is pressable
11650 */
11651 OO.ui.OptionWidget.prototype.isPressable = function () {
11652 return this.constructor.static.pressable && !this.isDisabled();
11653 };
11654
11655 /**
11656 * Check if option is selected.
11657 *
11658 * @return {boolean} Item is selected
11659 */
11660 OO.ui.OptionWidget.prototype.isSelected = function () {
11661 return this.selected;
11662 };
11663
11664 /**
11665 * Check if option is highlighted.
11666 *
11667 * @return {boolean} Item is highlighted
11668 */
11669 OO.ui.OptionWidget.prototype.isHighlighted = function () {
11670 return this.highlighted;
11671 };
11672
11673 /**
11674 * Check if option is pressed.
11675 *
11676 * @return {boolean} Item is pressed
11677 */
11678 OO.ui.OptionWidget.prototype.isPressed = function () {
11679 return this.pressed;
11680 };
11681
11682 /**
11683 * Set selected state.
11684 *
11685 * @param {boolean} [state=false] Select option
11686 * @chainable
11687 */
11688 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
11689 if ( this.constructor.static.selectable ) {
11690 this.selected = !!state;
11691 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
11692 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
11693 this.scrollElementIntoView();
11694 }
11695 this.updateThemeClasses();
11696 }
11697 return this;
11698 };
11699
11700 /**
11701 * Set highlighted state.
11702 *
11703 * @param {boolean} [state=false] Highlight option
11704 * @chainable
11705 */
11706 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
11707 if ( this.constructor.static.highlightable ) {
11708 this.highlighted = !!state;
11709 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
11710 this.updateThemeClasses();
11711 }
11712 return this;
11713 };
11714
11715 /**
11716 * Set pressed state.
11717 *
11718 * @param {boolean} [state=false] Press option
11719 * @chainable
11720 */
11721 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
11722 if ( this.constructor.static.pressable ) {
11723 this.pressed = !!state;
11724 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
11725 this.updateThemeClasses();
11726 }
11727 return this;
11728 };
11729
11730 /**
11731 * Option widget with an option icon and indicator.
11732 *
11733 * Use together with OO.ui.SelectWidget.
11734 *
11735 * @class
11736 * @extends OO.ui.OptionWidget
11737 * @mixins OO.ui.IconElement
11738 * @mixins OO.ui.IndicatorElement
11739 *
11740 * @constructor
11741 * @param {Object} [config] Configuration options
11742 */
11743 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
11744 // Parent constructor
11745 OO.ui.DecoratedOptionWidget.super.call( this, config );
11746
11747 // Mixin constructors
11748 OO.ui.IconElement.call( this, config );
11749 OO.ui.IndicatorElement.call( this, config );
11750
11751 // Initialization
11752 this.$element
11753 .addClass( 'oo-ui-decoratedOptionWidget' )
11754 .prepend( this.$icon )
11755 .append( this.$indicator );
11756 };
11757
11758 /* Setup */
11759
11760 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
11761 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
11762 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
11763
11764 /**
11765 * Option widget that looks like a button.
11766 *
11767 * Use together with OO.ui.ButtonSelectWidget.
11768 *
11769 * @class
11770 * @extends OO.ui.DecoratedOptionWidget
11771 * @mixins OO.ui.ButtonElement
11772 * @mixins OO.ui.TabIndexedElement
11773 *
11774 * @constructor
11775 * @param {Object} [config] Configuration options
11776 */
11777 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
11778 // Parent constructor
11779 OO.ui.ButtonOptionWidget.super.call( this, config );
11780
11781 // Mixin constructors
11782 OO.ui.ButtonElement.call( this, config );
11783 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
11784
11785 // Initialization
11786 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
11787 this.$button.append( this.$element.contents() );
11788 this.$element.append( this.$button );
11789 };
11790
11791 /* Setup */
11792
11793 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
11794 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
11795 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
11796
11797 /* Static Properties */
11798
11799 // Allow button mouse down events to pass through so they can be handled by the parent select widget
11800 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
11801
11802 /* Methods */
11803
11804 /**
11805 * @inheritdoc
11806 */
11807 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
11808 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
11809
11810 if ( this.constructor.static.selectable ) {
11811 this.setActive( state );
11812 }
11813
11814 return this;
11815 };
11816
11817 /**
11818 * Option widget that looks like a radio button.
11819 *
11820 * Use together with OO.ui.RadioSelectWidget.
11821 *
11822 * @class
11823 * @extends OO.ui.OptionWidget
11824 *
11825 * @constructor
11826 * @param {Object} [config] Configuration options
11827 */
11828 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
11829 // Parent constructor
11830 OO.ui.RadioOptionWidget.super.call( this, config );
11831
11832 // Properties
11833 this.radio = new OO.ui.RadioInputWidget( { value: config.data } );
11834
11835 // Initialization
11836 this.$element
11837 .addClass( 'oo-ui-radioOptionWidget' )
11838 .prepend( this.radio.$element );
11839 };
11840
11841 /* Setup */
11842
11843 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
11844
11845 /* Static Properties */
11846
11847 OO.ui.RadioOptionWidget.static.highlightable = false;
11848
11849 OO.ui.RadioOptionWidget.static.pressable = false;
11850
11851 /* Methods */
11852
11853 /**
11854 * @inheritdoc
11855 */
11856 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
11857 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
11858
11859 this.radio.setSelected( state );
11860
11861 return this;
11862 };
11863
11864 /**
11865 * Item of an OO.ui.MenuSelectWidget.
11866 *
11867 * @class
11868 * @extends OO.ui.DecoratedOptionWidget
11869 *
11870 * @constructor
11871 * @param {Object} [config] Configuration options
11872 */
11873 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
11874 // Configuration initialization
11875 config = $.extend( { icon: 'check' }, config );
11876
11877 // Parent constructor
11878 OO.ui.MenuOptionWidget.super.call( this, config );
11879
11880 // Initialization
11881 this.$element
11882 .attr( 'role', 'menuitem' )
11883 .addClass( 'oo-ui-menuOptionWidget' );
11884 };
11885
11886 /* Setup */
11887
11888 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
11889
11890 /**
11891 * Section to group one or more items in a OO.ui.MenuSelectWidget.
11892 *
11893 * @class
11894 * @extends OO.ui.DecoratedOptionWidget
11895 *
11896 * @constructor
11897 * @param {Object} [config] Configuration options
11898 */
11899 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
11900 // Parent constructor
11901 OO.ui.MenuSectionOptionWidget.super.call( this, config );
11902
11903 // Initialization
11904 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
11905 };
11906
11907 /* Setup */
11908
11909 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
11910
11911 /* Static Properties */
11912
11913 OO.ui.MenuSectionOptionWidget.static.selectable = false;
11914
11915 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
11916
11917 /**
11918 * Items for an OO.ui.OutlineSelectWidget.
11919 *
11920 * @class
11921 * @extends OO.ui.DecoratedOptionWidget
11922 *
11923 * @constructor
11924 * @param {Object} [config] Configuration options
11925 * @cfg {number} [level] Indentation level
11926 * @cfg {boolean} [movable] Allow modification from outline controls
11927 */
11928 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
11929 // Configuration initialization
11930 config = config || {};
11931
11932 // Parent constructor
11933 OO.ui.OutlineOptionWidget.super.call( this, config );
11934
11935 // Properties
11936 this.level = 0;
11937 this.movable = !!config.movable;
11938 this.removable = !!config.removable;
11939
11940 // Initialization
11941 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
11942 this.setLevel( config.level );
11943 };
11944
11945 /* Setup */
11946
11947 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
11948
11949 /* Static Properties */
11950
11951 OO.ui.OutlineOptionWidget.static.highlightable = false;
11952
11953 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
11954
11955 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
11956
11957 OO.ui.OutlineOptionWidget.static.levels = 3;
11958
11959 /* Methods */
11960
11961 /**
11962 * Check if item is movable.
11963 *
11964 * Movability is used by outline controls.
11965 *
11966 * @return {boolean} Item is movable
11967 */
11968 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
11969 return this.movable;
11970 };
11971
11972 /**
11973 * Check if item is removable.
11974 *
11975 * Removability is used by outline controls.
11976 *
11977 * @return {boolean} Item is removable
11978 */
11979 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
11980 return this.removable;
11981 };
11982
11983 /**
11984 * Get indentation level.
11985 *
11986 * @return {number} Indentation level
11987 */
11988 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
11989 return this.level;
11990 };
11991
11992 /**
11993 * Set movability.
11994 *
11995 * Movability is used by outline controls.
11996 *
11997 * @param {boolean} movable Item is movable
11998 * @chainable
11999 */
12000 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
12001 this.movable = !!movable;
12002 this.updateThemeClasses();
12003 return this;
12004 };
12005
12006 /**
12007 * Set removability.
12008 *
12009 * Removability is used by outline controls.
12010 *
12011 * @param {boolean} movable Item is removable
12012 * @chainable
12013 */
12014 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
12015 this.removable = !!removable;
12016 this.updateThemeClasses();
12017 return this;
12018 };
12019
12020 /**
12021 * Set indentation level.
12022 *
12023 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12024 * @chainable
12025 */
12026 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
12027 var levels = this.constructor.static.levels,
12028 levelClass = this.constructor.static.levelClass,
12029 i = levels;
12030
12031 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
12032 while ( i-- ) {
12033 if ( this.level === i ) {
12034 this.$element.addClass( levelClass + i );
12035 } else {
12036 this.$element.removeClass( levelClass + i );
12037 }
12038 }
12039 this.updateThemeClasses();
12040
12041 return this;
12042 };
12043
12044 /**
12045 * Container for content that is overlaid and positioned absolutely.
12046 *
12047 * @class
12048 * @extends OO.ui.Widget
12049 * @mixins OO.ui.LabelElement
12050 *
12051 * @constructor
12052 * @param {Object} [config] Configuration options
12053 * @cfg {number} [width=320] Width of popup in pixels
12054 * @cfg {number} [height] Height of popup, omit to use automatic height
12055 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12056 * @cfg {string} [align='center'] Alignment of popup to origin
12057 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
12058 * @cfg {number} [containerPadding=10] How much padding to keep between popup and container
12059 * @cfg {jQuery} [$content] Content to append to the popup's body
12060 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
12061 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
12062 * @cfg {boolean} [head] Show label and close button at the top
12063 * @cfg {boolean} [padded] Add padding to the body
12064 */
12065 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
12066 // Configuration initialization
12067 config = config || {};
12068
12069 // Parent constructor
12070 OO.ui.PopupWidget.super.call( this, config );
12071
12072 // Mixin constructors
12073 OO.ui.LabelElement.call( this, config );
12074 OO.ui.ClippableElement.call( this, config );
12075
12076 // Properties
12077 this.visible = false;
12078 this.$popup = this.$( '<div>' );
12079 this.$head = this.$( '<div>' );
12080 this.$body = this.$( '<div>' );
12081 this.$anchor = this.$( '<div>' );
12082 // If undefined, will be computed lazily in updateDimensions()
12083 this.$container = config.$container;
12084 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
12085 this.autoClose = !!config.autoClose;
12086 this.$autoCloseIgnore = config.$autoCloseIgnore;
12087 this.transitionTimeout = null;
12088 this.anchor = null;
12089 this.width = config.width !== undefined ? config.width : 320;
12090 this.height = config.height !== undefined ? config.height : null;
12091 this.align = config.align || 'center';
12092 this.closeButton = new OO.ui.ButtonWidget( { $: this.$, framed: false, icon: 'close' } );
12093 this.onMouseDownHandler = this.onMouseDown.bind( this );
12094
12095 // Events
12096 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
12097
12098 // Initialization
12099 this.toggleAnchor( config.anchor === undefined || config.anchor );
12100 this.$body.addClass( 'oo-ui-popupWidget-body' );
12101 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
12102 this.$head
12103 .addClass( 'oo-ui-popupWidget-head' )
12104 .append( this.$label, this.closeButton.$element );
12105 if ( !config.head ) {
12106 this.$head.hide();
12107 }
12108 this.$popup
12109 .addClass( 'oo-ui-popupWidget-popup' )
12110 .append( this.$head, this.$body );
12111 this.$element
12112 .hide()
12113 .addClass( 'oo-ui-popupWidget' )
12114 .append( this.$popup, this.$anchor );
12115 // Move content, which was added to #$element by OO.ui.Widget, to the body
12116 if ( config.$content instanceof jQuery ) {
12117 this.$body.append( config.$content );
12118 }
12119 if ( config.padded ) {
12120 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
12121 }
12122 this.setClippableElement( this.$body );
12123 };
12124
12125 /* Setup */
12126
12127 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
12128 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
12129 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
12130
12131 /* Methods */
12132
12133 /**
12134 * Handles mouse down events.
12135 *
12136 * @param {jQuery.Event} e Mouse down event
12137 */
12138 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
12139 if (
12140 this.isVisible() &&
12141 !$.contains( this.$element[ 0 ], e.target ) &&
12142 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
12143 ) {
12144 this.toggle( false );
12145 }
12146 };
12147
12148 /**
12149 * Bind mouse down listener.
12150 */
12151 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
12152 // Capture clicks outside popup
12153 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
12154 };
12155
12156 /**
12157 * Handles close button click events.
12158 */
12159 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
12160 if ( this.isVisible() ) {
12161 this.toggle( false );
12162 }
12163 };
12164
12165 /**
12166 * Unbind mouse down listener.
12167 */
12168 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
12169 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
12170 };
12171
12172 /**
12173 * Set whether to show a anchor.
12174 *
12175 * @param {boolean} [show] Show anchor, omit to toggle
12176 */
12177 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
12178 show = show === undefined ? !this.anchored : !!show;
12179
12180 if ( this.anchored !== show ) {
12181 if ( show ) {
12182 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
12183 } else {
12184 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
12185 }
12186 this.anchored = show;
12187 }
12188 };
12189
12190 /**
12191 * Check if showing a anchor.
12192 *
12193 * @return {boolean} anchor is visible
12194 */
12195 OO.ui.PopupWidget.prototype.hasAnchor = function () {
12196 return this.anchor;
12197 };
12198
12199 /**
12200 * @inheritdoc
12201 */
12202 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
12203 show = show === undefined ? !this.isVisible() : !!show;
12204
12205 var change = show !== this.isVisible();
12206
12207 // Parent method
12208 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
12209
12210 if ( change ) {
12211 if ( show ) {
12212 if ( this.autoClose ) {
12213 this.bindMouseDownListener();
12214 }
12215 this.updateDimensions();
12216 this.toggleClipping( true );
12217 } else {
12218 this.toggleClipping( false );
12219 if ( this.autoClose ) {
12220 this.unbindMouseDownListener();
12221 }
12222 }
12223 }
12224
12225 return this;
12226 };
12227
12228 /**
12229 * Set the size of the popup.
12230 *
12231 * Changing the size may also change the popup's position depending on the alignment.
12232 *
12233 * @param {number} width Width
12234 * @param {number} height Height
12235 * @param {boolean} [transition=false] Use a smooth transition
12236 * @chainable
12237 */
12238 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
12239 this.width = width;
12240 this.height = height !== undefined ? height : null;
12241 if ( this.isVisible() ) {
12242 this.updateDimensions( transition );
12243 }
12244 };
12245
12246 /**
12247 * Update the size and position.
12248 *
12249 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
12250 * be called automatically.
12251 *
12252 * @param {boolean} [transition=false] Use a smooth transition
12253 * @chainable
12254 */
12255 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
12256 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
12257 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
12258 widget = this;
12259
12260 if ( !this.$container ) {
12261 // Lazy-initialize $container if not specified in constructor
12262 this.$container = this.$( this.getClosestScrollableElementContainer() );
12263 }
12264
12265 // Set height and width before measuring things, since it might cause our measurements
12266 // to change (e.g. due to scrollbars appearing or disappearing)
12267 this.$popup.css( {
12268 width: this.width,
12269 height: this.height !== null ? this.height : 'auto'
12270 } );
12271
12272 // Compute initial popupOffset based on alignment
12273 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
12274
12275 // Figure out if this will cause the popup to go beyond the edge of the container
12276 originOffset = this.$element.offset().left;
12277 containerLeft = this.$container.offset().left;
12278 containerWidth = this.$container.innerWidth();
12279 containerRight = containerLeft + containerWidth;
12280 popupLeft = popupOffset - this.containerPadding;
12281 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
12282 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
12283 overlapRight = containerRight - ( originOffset + popupRight );
12284
12285 // Adjust offset to make the popup not go beyond the edge, if needed
12286 if ( overlapRight < 0 ) {
12287 popupOffset += overlapRight;
12288 } else if ( overlapLeft < 0 ) {
12289 popupOffset -= overlapLeft;
12290 }
12291
12292 // Adjust offset to avoid anchor being rendered too close to the edge
12293 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
12294 // TODO: Find a measurement that works for CSS anchors and image anchors
12295 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
12296 if ( popupOffset + this.width < anchorWidth ) {
12297 popupOffset = anchorWidth - this.width;
12298 } else if ( -popupOffset < anchorWidth ) {
12299 popupOffset = -anchorWidth;
12300 }
12301
12302 // Prevent transition from being interrupted
12303 clearTimeout( this.transitionTimeout );
12304 if ( transition ) {
12305 // Enable transition
12306 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
12307 }
12308
12309 // Position body relative to anchor
12310 this.$popup.css( 'margin-left', popupOffset );
12311
12312 if ( transition ) {
12313 // Prevent transitioning after transition is complete
12314 this.transitionTimeout = setTimeout( function () {
12315 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
12316 }, 200 );
12317 } else {
12318 // Prevent transitioning immediately
12319 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
12320 }
12321
12322 // Reevaluate clipping state since we've relocated and resized the popup
12323 this.clip();
12324
12325 return this;
12326 };
12327
12328 /**
12329 * Progress bar widget.
12330 *
12331 * @class
12332 * @extends OO.ui.Widget
12333 *
12334 * @constructor
12335 * @param {Object} [config] Configuration options
12336 * @cfg {number|boolean} [progress=false] Initial progress percent or false for indeterminate
12337 */
12338 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
12339 // Configuration initialization
12340 config = config || {};
12341
12342 // Parent constructor
12343 OO.ui.ProgressBarWidget.super.call( this, config );
12344
12345 // Properties
12346 this.$bar = this.$( '<div>' );
12347 this.progress = null;
12348
12349 // Initialization
12350 this.setProgress( config.progress !== undefined ? config.progress : false );
12351 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
12352 this.$element
12353 .attr( {
12354 role: 'progressbar',
12355 'aria-valuemin': 0,
12356 'aria-valuemax': 100
12357 } )
12358 .addClass( 'oo-ui-progressBarWidget' )
12359 .append( this.$bar );
12360 };
12361
12362 /* Setup */
12363
12364 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
12365
12366 /* Static Properties */
12367
12368 OO.ui.ProgressBarWidget.static.tagName = 'div';
12369
12370 /* Methods */
12371
12372 /**
12373 * Get progress percent
12374 *
12375 * @return {number} Progress percent
12376 */
12377 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
12378 return this.progress;
12379 };
12380
12381 /**
12382 * Set progress percent
12383 *
12384 * @param {number|boolean} progress Progress percent or false for indeterminate
12385 */
12386 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
12387 this.progress = progress;
12388
12389 if ( progress !== false ) {
12390 this.$bar.css( 'width', this.progress + '%' );
12391 this.$element.attr( 'aria-valuenow', this.progress );
12392 } else {
12393 this.$bar.css( 'width', '' );
12394 this.$element.removeAttr( 'aria-valuenow' );
12395 }
12396 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
12397 };
12398
12399 /**
12400 * Search widget.
12401 *
12402 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
12403 * Results are cleared and populated each time the query is changed.
12404 *
12405 * @class
12406 * @extends OO.ui.Widget
12407 *
12408 * @constructor
12409 * @param {Object} [config] Configuration options
12410 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
12411 * @cfg {string} [value] Initial query value
12412 */
12413 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
12414 // Configuration initialization
12415 config = config || {};
12416
12417 // Parent constructor
12418 OO.ui.SearchWidget.super.call( this, config );
12419
12420 // Properties
12421 this.query = new OO.ui.TextInputWidget( {
12422 $: this.$,
12423 icon: 'search',
12424 placeholder: config.placeholder,
12425 value: config.value
12426 } );
12427 this.results = new OO.ui.SelectWidget( { $: this.$ } );
12428 this.$query = this.$( '<div>' );
12429 this.$results = this.$( '<div>' );
12430
12431 // Events
12432 this.query.connect( this, {
12433 change: 'onQueryChange',
12434 enter: 'onQueryEnter'
12435 } );
12436 this.results.connect( this, {
12437 highlight: 'onResultsHighlight',
12438 select: 'onResultsSelect'
12439 } );
12440 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
12441
12442 // Initialization
12443 this.$query
12444 .addClass( 'oo-ui-searchWidget-query' )
12445 .append( this.query.$element );
12446 this.$results
12447 .addClass( 'oo-ui-searchWidget-results' )
12448 .append( this.results.$element );
12449 this.$element
12450 .addClass( 'oo-ui-searchWidget' )
12451 .append( this.$results, this.$query );
12452 };
12453
12454 /* Setup */
12455
12456 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
12457
12458 /* Events */
12459
12460 /**
12461 * @event highlight
12462 * @param {Object|null} item Item data or null if no item is highlighted
12463 */
12464
12465 /**
12466 * @event select
12467 * @param {Object|null} item Item data or null if no item is selected
12468 */
12469
12470 /* Methods */
12471
12472 /**
12473 * Handle query key down events.
12474 *
12475 * @param {jQuery.Event} e Key down event
12476 */
12477 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
12478 var highlightedItem, nextItem,
12479 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
12480
12481 if ( dir ) {
12482 highlightedItem = this.results.getHighlightedItem();
12483 if ( !highlightedItem ) {
12484 highlightedItem = this.results.getSelectedItem();
12485 }
12486 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
12487 this.results.highlightItem( nextItem );
12488 nextItem.scrollElementIntoView();
12489 }
12490 };
12491
12492 /**
12493 * Handle select widget select events.
12494 *
12495 * Clears existing results. Subclasses should repopulate items according to new query.
12496 *
12497 * @param {string} value New value
12498 */
12499 OO.ui.SearchWidget.prototype.onQueryChange = function () {
12500 // Reset
12501 this.results.clearItems();
12502 };
12503
12504 /**
12505 * Handle select widget enter key events.
12506 *
12507 * Selects highlighted item.
12508 *
12509 * @param {string} value New value
12510 */
12511 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
12512 // Reset
12513 this.results.selectItem( this.results.getHighlightedItem() );
12514 };
12515
12516 /**
12517 * Handle select widget highlight events.
12518 *
12519 * @param {OO.ui.OptionWidget} item Highlighted item
12520 * @fires highlight
12521 */
12522 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
12523 this.emit( 'highlight', item ? item.getData() : null );
12524 };
12525
12526 /**
12527 * Handle select widget select events.
12528 *
12529 * @param {OO.ui.OptionWidget} item Selected item
12530 * @fires select
12531 */
12532 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
12533 this.emit( 'select', item ? item.getData() : null );
12534 };
12535
12536 /**
12537 * Get the query input.
12538 *
12539 * @return {OO.ui.TextInputWidget} Query input
12540 */
12541 OO.ui.SearchWidget.prototype.getQuery = function () {
12542 return this.query;
12543 };
12544
12545 /**
12546 * Get the results list.
12547 *
12548 * @return {OO.ui.SelectWidget} Select list
12549 */
12550 OO.ui.SearchWidget.prototype.getResults = function () {
12551 return this.results;
12552 };
12553
12554 /**
12555 * Generic selection of options.
12556 *
12557 * Items can contain any rendering. Any widget that provides options, from which the user must
12558 * choose one, should be built on this class.
12559 *
12560 * Use together with OO.ui.OptionWidget.
12561 *
12562 * @class
12563 * @extends OO.ui.Widget
12564 * @mixins OO.ui.GroupElement
12565 *
12566 * @constructor
12567 * @param {Object} [config] Configuration options
12568 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
12569 */
12570 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
12571 // Configuration initialization
12572 config = config || {};
12573
12574 // Parent constructor
12575 OO.ui.SelectWidget.super.call( this, config );
12576
12577 // Mixin constructors
12578 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
12579
12580 // Properties
12581 this.pressed = false;
12582 this.selecting = null;
12583 this.onMouseUpHandler = this.onMouseUp.bind( this );
12584 this.onMouseMoveHandler = this.onMouseMove.bind( this );
12585
12586 // Events
12587 this.$element.on( {
12588 mousedown: this.onMouseDown.bind( this ),
12589 mouseover: this.onMouseOver.bind( this ),
12590 mouseleave: this.onMouseLeave.bind( this )
12591 } );
12592
12593 // Initialization
12594 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
12595 if ( $.isArray( config.items ) ) {
12596 this.addItems( config.items );
12597 }
12598 };
12599
12600 /* Setup */
12601
12602 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
12603
12604 // Need to mixin base class as well
12605 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
12606 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
12607
12608 /* Events */
12609
12610 /**
12611 * @event highlight
12612 * @param {OO.ui.OptionWidget|null} item Highlighted item
12613 */
12614
12615 /**
12616 * @event press
12617 * @param {OO.ui.OptionWidget|null} item Pressed item
12618 */
12619
12620 /**
12621 * @event select
12622 * @param {OO.ui.OptionWidget|null} item Selected item
12623 */
12624
12625 /**
12626 * @event choose
12627 * @param {OO.ui.OptionWidget|null} item Chosen item
12628 */
12629
12630 /**
12631 * @event add
12632 * @param {OO.ui.OptionWidget[]} items Added items
12633 * @param {number} index Index items were added at
12634 */
12635
12636 /**
12637 * @event remove
12638 * @param {OO.ui.OptionWidget[]} items Removed items
12639 */
12640
12641 /* Methods */
12642
12643 /**
12644 * Handle mouse down events.
12645 *
12646 * @private
12647 * @param {jQuery.Event} e Mouse down event
12648 */
12649 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
12650 var item;
12651
12652 if ( !this.isDisabled() && e.which === 1 ) {
12653 this.togglePressed( true );
12654 item = this.getTargetItem( e );
12655 if ( item && item.isSelectable() ) {
12656 this.pressItem( item );
12657 this.selecting = item;
12658 this.getElementDocument().addEventListener(
12659 'mouseup',
12660 this.onMouseUpHandler,
12661 true
12662 );
12663 this.getElementDocument().addEventListener(
12664 'mousemove',
12665 this.onMouseMoveHandler,
12666 true
12667 );
12668 }
12669 }
12670 return false;
12671 };
12672
12673 /**
12674 * Handle mouse up events.
12675 *
12676 * @private
12677 * @param {jQuery.Event} e Mouse up event
12678 */
12679 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
12680 var item;
12681
12682 this.togglePressed( false );
12683 if ( !this.selecting ) {
12684 item = this.getTargetItem( e );
12685 if ( item && item.isSelectable() ) {
12686 this.selecting = item;
12687 }
12688 }
12689 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
12690 this.pressItem( null );
12691 this.chooseItem( this.selecting );
12692 this.selecting = null;
12693 }
12694
12695 this.getElementDocument().removeEventListener(
12696 'mouseup',
12697 this.onMouseUpHandler,
12698 true
12699 );
12700 this.getElementDocument().removeEventListener(
12701 'mousemove',
12702 this.onMouseMoveHandler,
12703 true
12704 );
12705
12706 return false;
12707 };
12708
12709 /**
12710 * Handle mouse move events.
12711 *
12712 * @private
12713 * @param {jQuery.Event} e Mouse move event
12714 */
12715 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
12716 var item;
12717
12718 if ( !this.isDisabled() && this.pressed ) {
12719 item = this.getTargetItem( e );
12720 if ( item && item !== this.selecting && item.isSelectable() ) {
12721 this.pressItem( item );
12722 this.selecting = item;
12723 }
12724 }
12725 return false;
12726 };
12727
12728 /**
12729 * Handle mouse over events.
12730 *
12731 * @private
12732 * @param {jQuery.Event} e Mouse over event
12733 */
12734 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
12735 var item;
12736
12737 if ( !this.isDisabled() ) {
12738 item = this.getTargetItem( e );
12739 this.highlightItem( item && item.isHighlightable() ? item : null );
12740 }
12741 return false;
12742 };
12743
12744 /**
12745 * Handle mouse leave events.
12746 *
12747 * @private
12748 * @param {jQuery.Event} e Mouse over event
12749 */
12750 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
12751 if ( !this.isDisabled() ) {
12752 this.highlightItem( null );
12753 }
12754 return false;
12755 };
12756
12757 /**
12758 * Get the closest item to a jQuery.Event.
12759 *
12760 * @private
12761 * @param {jQuery.Event} e
12762 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
12763 */
12764 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
12765 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
12766 if ( $item.length ) {
12767 return $item.data( 'oo-ui-optionWidget' );
12768 }
12769 return null;
12770 };
12771
12772 /**
12773 * Get selected item.
12774 *
12775 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
12776 */
12777 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
12778 var i, len;
12779
12780 for ( i = 0, len = this.items.length; i < len; i++ ) {
12781 if ( this.items[ i ].isSelected() ) {
12782 return this.items[ i ];
12783 }
12784 }
12785 return null;
12786 };
12787
12788 /**
12789 * Get highlighted item.
12790 *
12791 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
12792 */
12793 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
12794 var i, len;
12795
12796 for ( i = 0, len = this.items.length; i < len; i++ ) {
12797 if ( this.items[ i ].isHighlighted() ) {
12798 return this.items[ i ];
12799 }
12800 }
12801 return null;
12802 };
12803
12804 /**
12805 * Toggle pressed state.
12806 *
12807 * @param {boolean} pressed An option is being pressed
12808 */
12809 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
12810 if ( pressed === undefined ) {
12811 pressed = !this.pressed;
12812 }
12813 if ( pressed !== this.pressed ) {
12814 this.$element
12815 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
12816 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
12817 this.pressed = pressed;
12818 }
12819 };
12820
12821 /**
12822 * Highlight an item.
12823 *
12824 * Highlighting is mutually exclusive.
12825 *
12826 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
12827 * @fires highlight
12828 * @chainable
12829 */
12830 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
12831 var i, len, highlighted,
12832 changed = false;
12833
12834 for ( i = 0, len = this.items.length; i < len; i++ ) {
12835 highlighted = this.items[ i ] === item;
12836 if ( this.items[ i ].isHighlighted() !== highlighted ) {
12837 this.items[ i ].setHighlighted( highlighted );
12838 changed = true;
12839 }
12840 }
12841 if ( changed ) {
12842 this.emit( 'highlight', item );
12843 }
12844
12845 return this;
12846 };
12847
12848 /**
12849 * Select an item.
12850 *
12851 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
12852 * @fires select
12853 * @chainable
12854 */
12855 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
12856 var i, len, selected,
12857 changed = false;
12858
12859 for ( i = 0, len = this.items.length; i < len; i++ ) {
12860 selected = this.items[ i ] === item;
12861 if ( this.items[ i ].isSelected() !== selected ) {
12862 this.items[ i ].setSelected( selected );
12863 changed = true;
12864 }
12865 }
12866 if ( changed ) {
12867 this.emit( 'select', item );
12868 }
12869
12870 return this;
12871 };
12872
12873 /**
12874 * Press an item.
12875 *
12876 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
12877 * @fires press
12878 * @chainable
12879 */
12880 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
12881 var i, len, pressed,
12882 changed = false;
12883
12884 for ( i = 0, len = this.items.length; i < len; i++ ) {
12885 pressed = this.items[ i ] === item;
12886 if ( this.items[ i ].isPressed() !== pressed ) {
12887 this.items[ i ].setPressed( pressed );
12888 changed = true;
12889 }
12890 }
12891 if ( changed ) {
12892 this.emit( 'press', item );
12893 }
12894
12895 return this;
12896 };
12897
12898 /**
12899 * Choose an item.
12900 *
12901 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
12902 * an item is selected using the keyboard or mouse.
12903 *
12904 * @param {OO.ui.OptionWidget} item Item to choose
12905 * @fires choose
12906 * @chainable
12907 */
12908 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
12909 this.selectItem( item );
12910 this.emit( 'choose', item );
12911
12912 return this;
12913 };
12914
12915 /**
12916 * Get an item relative to another one.
12917 *
12918 * @param {OO.ui.OptionWidget|null} item Item to start at, null to get relative to list start
12919 * @param {number} direction Direction to move in, -1 to move backward, 1 to move forward
12920 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
12921 */
12922 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
12923 var currentIndex, nextIndex, i,
12924 increase = direction > 0 ? 1 : -1,
12925 len = this.items.length;
12926
12927 if ( item instanceof OO.ui.OptionWidget ) {
12928 currentIndex = $.inArray( item, this.items );
12929 nextIndex = ( currentIndex + increase + len ) % len;
12930 } else {
12931 // If no item is selected and moving forward, start at the beginning.
12932 // If moving backward, start at the end.
12933 nextIndex = direction > 0 ? 0 : len - 1;
12934 }
12935
12936 for ( i = 0; i < len; i++ ) {
12937 item = this.items[ nextIndex ];
12938 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
12939 return item;
12940 }
12941 nextIndex = ( nextIndex + increase + len ) % len;
12942 }
12943 return null;
12944 };
12945
12946 /**
12947 * Get the next selectable item.
12948 *
12949 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
12950 */
12951 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
12952 var i, len, item;
12953
12954 for ( i = 0, len = this.items.length; i < len; i++ ) {
12955 item = this.items[ i ];
12956 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
12957 return item;
12958 }
12959 }
12960
12961 return null;
12962 };
12963
12964 /**
12965 * Add items.
12966 *
12967 * @param {OO.ui.OptionWidget[]} items Items to add
12968 * @param {number} [index] Index to insert items after
12969 * @fires add
12970 * @chainable
12971 */
12972 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
12973 // Mixin method
12974 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
12975
12976 // Always provide an index, even if it was omitted
12977 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
12978
12979 return this;
12980 };
12981
12982 /**
12983 * Remove items.
12984 *
12985 * Items will be detached, not removed, so they can be used later.
12986 *
12987 * @param {OO.ui.OptionWidget[]} items Items to remove
12988 * @fires remove
12989 * @chainable
12990 */
12991 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
12992 var i, len, item;
12993
12994 // Deselect items being removed
12995 for ( i = 0, len = items.length; i < len; i++ ) {
12996 item = items[ i ];
12997 if ( item.isSelected() ) {
12998 this.selectItem( null );
12999 }
13000 }
13001
13002 // Mixin method
13003 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
13004
13005 this.emit( 'remove', items );
13006
13007 return this;
13008 };
13009
13010 /**
13011 * Clear all items.
13012 *
13013 * Items will be detached, not removed, so they can be used later.
13014 *
13015 * @fires remove
13016 * @chainable
13017 */
13018 OO.ui.SelectWidget.prototype.clearItems = function () {
13019 var items = this.items.slice();
13020
13021 // Mixin method
13022 OO.ui.GroupWidget.prototype.clearItems.call( this );
13023
13024 // Clear selection
13025 this.selectItem( null );
13026
13027 this.emit( 'remove', items );
13028
13029 return this;
13030 };
13031
13032 /**
13033 * Select widget containing button options.
13034 *
13035 * Use together with OO.ui.ButtonOptionWidget.
13036 *
13037 * @class
13038 * @extends OO.ui.SelectWidget
13039 *
13040 * @constructor
13041 * @param {Object} [config] Configuration options
13042 */
13043 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
13044 // Parent constructor
13045 OO.ui.ButtonSelectWidget.super.call( this, config );
13046
13047 // Initialization
13048 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
13049 };
13050
13051 /* Setup */
13052
13053 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
13054
13055 /**
13056 * Select widget containing radio button options.
13057 *
13058 * Use together with OO.ui.RadioOptionWidget.
13059 *
13060 * @class
13061 * @extends OO.ui.SelectWidget
13062 *
13063 * @constructor
13064 * @param {Object} [config] Configuration options
13065 */
13066 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
13067 // Parent constructor
13068 OO.ui.RadioSelectWidget.super.call( this, config );
13069
13070 // Initialization
13071 this.$element.addClass( 'oo-ui-radioSelectWidget' );
13072 };
13073
13074 /* Setup */
13075
13076 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
13077
13078 /**
13079 * Overlaid menu of options.
13080 *
13081 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
13082 * the menu.
13083 *
13084 * Use together with OO.ui.MenuOptionWidget.
13085 *
13086 * @class
13087 * @extends OO.ui.SelectWidget
13088 * @mixins OO.ui.ClippableElement
13089 *
13090 * @constructor
13091 * @param {Object} [config] Configuration options
13092 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
13093 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
13094 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
13095 */
13096 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
13097 // Configuration initialization
13098 config = config || {};
13099
13100 // Parent constructor
13101 OO.ui.MenuSelectWidget.super.call( this, config );
13102
13103 // Mixin constructors
13104 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
13105
13106 // Properties
13107 this.visible = false;
13108 this.newItems = null;
13109 this.autoHide = config.autoHide === undefined || !!config.autoHide;
13110 this.$input = config.input ? config.input.$input : null;
13111 this.$widget = config.widget ? config.widget.$element : null;
13112 this.$previousFocus = null;
13113 this.isolated = !config.input;
13114 this.onKeyDownHandler = this.onKeyDown.bind( this );
13115 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
13116
13117 // Initialization
13118 this.$element
13119 .hide()
13120 .attr( 'role', 'menu' )
13121 .addClass( 'oo-ui-menuSelectWidget' );
13122 };
13123
13124 /* Setup */
13125
13126 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
13127 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
13128
13129 /* Methods */
13130
13131 /**
13132 * Handles document mouse down events.
13133 *
13134 * @param {jQuery.Event} e Key down event
13135 */
13136 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
13137 if (
13138 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
13139 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
13140 ) {
13141 this.toggle( false );
13142 }
13143 };
13144
13145 /**
13146 * Handles key down events.
13147 *
13148 * @param {jQuery.Event} e Key down event
13149 */
13150 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
13151 var nextItem,
13152 handled = false,
13153 highlightItem = this.getHighlightedItem();
13154
13155 if ( !this.isDisabled() && this.isVisible() ) {
13156 if ( !highlightItem ) {
13157 highlightItem = this.getSelectedItem();
13158 }
13159 switch ( e.keyCode ) {
13160 case OO.ui.Keys.ENTER:
13161 this.chooseItem( highlightItem );
13162 handled = true;
13163 break;
13164 case OO.ui.Keys.UP:
13165 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
13166 handled = true;
13167 break;
13168 case OO.ui.Keys.DOWN:
13169 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
13170 handled = true;
13171 break;
13172 case OO.ui.Keys.ESCAPE:
13173 if ( highlightItem ) {
13174 highlightItem.setHighlighted( false );
13175 }
13176 this.toggle( false );
13177 handled = true;
13178 break;
13179 }
13180
13181 if ( nextItem ) {
13182 this.highlightItem( nextItem );
13183 nextItem.scrollElementIntoView();
13184 }
13185
13186 if ( handled ) {
13187 e.preventDefault();
13188 e.stopPropagation();
13189 return false;
13190 }
13191 }
13192 };
13193
13194 /**
13195 * Bind key down listener.
13196 */
13197 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
13198 if ( this.$input ) {
13199 this.$input.on( 'keydown', this.onKeyDownHandler );
13200 } else {
13201 // Capture menu navigation keys
13202 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
13203 }
13204 };
13205
13206 /**
13207 * Unbind key down listener.
13208 */
13209 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
13210 if ( this.$input ) {
13211 this.$input.off( 'keydown' );
13212 } else {
13213 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
13214 }
13215 };
13216
13217 /**
13218 * Choose an item.
13219 *
13220 * This will close the menu, unlike #selectItem which only changes selection.
13221 *
13222 * @param {OO.ui.OptionWidget} item Item to choose
13223 * @chainable
13224 */
13225 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
13226 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
13227 this.toggle( false );
13228 return this;
13229 };
13230
13231 /**
13232 * @inheritdoc
13233 */
13234 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
13235 var i, len, item;
13236
13237 // Parent method
13238 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
13239
13240 // Auto-initialize
13241 if ( !this.newItems ) {
13242 this.newItems = [];
13243 }
13244
13245 for ( i = 0, len = items.length; i < len; i++ ) {
13246 item = items[ i ];
13247 if ( this.isVisible() ) {
13248 // Defer fitting label until item has been attached
13249 item.fitLabel();
13250 } else {
13251 this.newItems.push( item );
13252 }
13253 }
13254
13255 // Reevaluate clipping
13256 this.clip();
13257
13258 return this;
13259 };
13260
13261 /**
13262 * @inheritdoc
13263 */
13264 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
13265 // Parent method
13266 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
13267
13268 // Reevaluate clipping
13269 this.clip();
13270
13271 return this;
13272 };
13273
13274 /**
13275 * @inheritdoc
13276 */
13277 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
13278 // Parent method
13279 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
13280
13281 // Reevaluate clipping
13282 this.clip();
13283
13284 return this;
13285 };
13286
13287 /**
13288 * @inheritdoc
13289 */
13290 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
13291 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
13292
13293 var i, len,
13294 change = visible !== this.isVisible(),
13295 elementDoc = this.getElementDocument(),
13296 widgetDoc = this.$widget ? this.$widget[ 0 ].ownerDocument : null;
13297
13298 // Parent method
13299 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
13300
13301 if ( change ) {
13302 if ( visible ) {
13303 this.bindKeyDownListener();
13304
13305 // Change focus to enable keyboard navigation
13306 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
13307 this.$previousFocus = this.$( ':focus' );
13308 this.$input[ 0 ].focus();
13309 }
13310 if ( this.newItems && this.newItems.length ) {
13311 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
13312 this.newItems[ i ].fitLabel();
13313 }
13314 this.newItems = null;
13315 }
13316 this.toggleClipping( true );
13317
13318 // Auto-hide
13319 if ( this.autoHide ) {
13320 elementDoc.addEventListener(
13321 'mousedown', this.onDocumentMouseDownHandler, true
13322 );
13323 // Support $widget being in a different document
13324 if ( widgetDoc && widgetDoc !== elementDoc ) {
13325 widgetDoc.addEventListener(
13326 'mousedown', this.onDocumentMouseDownHandler, true
13327 );
13328 }
13329 }
13330 } else {
13331 this.unbindKeyDownListener();
13332 if ( this.isolated && this.$previousFocus ) {
13333 this.$previousFocus[ 0 ].focus();
13334 this.$previousFocus = null;
13335 }
13336 elementDoc.removeEventListener(
13337 'mousedown', this.onDocumentMouseDownHandler, true
13338 );
13339 // Support $widget being in a different document
13340 if ( widgetDoc && widgetDoc !== elementDoc ) {
13341 widgetDoc.removeEventListener(
13342 'mousedown', this.onDocumentMouseDownHandler, true
13343 );
13344 }
13345 this.toggleClipping( false );
13346 }
13347 }
13348
13349 return this;
13350 };
13351
13352 /**
13353 * Menu for a text input widget.
13354 *
13355 * This menu is specially designed to be positioned beneath the text input widget. Even if the input
13356 * is in a different frame, the menu's position is automatically calculated and maintained when the
13357 * menu is toggled or the window is resized.
13358 *
13359 * @class
13360 * @extends OO.ui.MenuSelectWidget
13361 *
13362 * @constructor
13363 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
13364 * @param {Object} [config] Configuration options
13365 * @cfg {jQuery} [$container=input.$element] Element to render menu under
13366 */
13367 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( input, config ) {
13368 // Configuration initialization
13369 config = config || {};
13370
13371 // Parent constructor
13372 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
13373
13374 // Properties
13375 this.input = input;
13376 this.$container = config.$container || this.input.$element;
13377 this.onWindowResizeHandler = this.onWindowResize.bind( this );
13378
13379 // Initialization
13380 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
13381 };
13382
13383 /* Setup */
13384
13385 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
13386
13387 /* Methods */
13388
13389 /**
13390 * Handle window resize event.
13391 *
13392 * @param {jQuery.Event} e Window resize event
13393 */
13394 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
13395 this.position();
13396 };
13397
13398 /**
13399 * @inheritdoc
13400 */
13401 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
13402 visible = visible === undefined ? !this.isVisible() : !!visible;
13403
13404 var change = visible !== this.isVisible();
13405
13406 if ( change && visible ) {
13407 // Make sure the width is set before the parent method runs.
13408 // After this we have to call this.position(); again to actually
13409 // position ourselves correctly.
13410 this.position();
13411 }
13412
13413 // Parent method
13414 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
13415
13416 if ( change ) {
13417 if ( this.isVisible() ) {
13418 this.position();
13419 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
13420 } else {
13421 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
13422 }
13423 }
13424
13425 return this;
13426 };
13427
13428 /**
13429 * Position the menu.
13430 *
13431 * @chainable
13432 */
13433 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
13434 var $container = this.$container,
13435 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
13436
13437 // Position under input
13438 pos.top += $container.height();
13439 this.$element.css( pos );
13440
13441 // Set width
13442 this.setIdealSize( $container.width() );
13443 // We updated the position, so re-evaluate the clipping state
13444 this.clip();
13445
13446 return this;
13447 };
13448
13449 /**
13450 * Structured list of items.
13451 *
13452 * Use with OO.ui.OutlineOptionWidget.
13453 *
13454 * @class
13455 * @extends OO.ui.SelectWidget
13456 *
13457 * @constructor
13458 * @param {Object} [config] Configuration options
13459 */
13460 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
13461 // Configuration initialization
13462 config = config || {};
13463
13464 // Parent constructor
13465 OO.ui.OutlineSelectWidget.super.call( this, config );
13466
13467 // Initialization
13468 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
13469 };
13470
13471 /* Setup */
13472
13473 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
13474
13475 /**
13476 * Switch that slides on and off.
13477 *
13478 * @class
13479 * @extends OO.ui.Widget
13480 * @mixins OO.ui.ToggleWidget
13481 *
13482 * @constructor
13483 * @param {Object} [config] Configuration options
13484 * @cfg {boolean} [value=false] Initial value
13485 */
13486 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
13487 // Parent constructor
13488 OO.ui.ToggleSwitchWidget.super.call( this, config );
13489
13490 // Mixin constructors
13491 OO.ui.ToggleWidget.call( this, config );
13492
13493 // Properties
13494 this.dragging = false;
13495 this.dragStart = null;
13496 this.sliding = false;
13497 this.$glow = this.$( '<span>' );
13498 this.$grip = this.$( '<span>' );
13499
13500 // Events
13501 this.$element.on( 'click', this.onClick.bind( this ) );
13502
13503 // Initialization
13504 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
13505 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
13506 this.$element
13507 .addClass( 'oo-ui-toggleSwitchWidget' )
13508 .append( this.$glow, this.$grip );
13509 };
13510
13511 /* Setup */
13512
13513 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
13514 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
13515
13516 /* Methods */
13517
13518 /**
13519 * Handle mouse down events.
13520 *
13521 * @param {jQuery.Event} e Mouse down event
13522 */
13523 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
13524 if ( !this.isDisabled() && e.which === 1 ) {
13525 this.setValue( !this.value );
13526 }
13527 };
13528
13529 }( OO ) );