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