f013b06fb46bb3b7d7d8e22021f61f4d80cb7098
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.6.4
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-01-31T01:15:57Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Get the user's language and any fallback languages.
49 *
50 * These language codes are used to localize user interface elements in the user's language.
51 *
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
54 *
55 * @return {string[]} Language codes, in descending order of priority
56 */
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
59 };
60
61 /**
62 * Get a value in an object keyed by language code.
63 *
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
68 */
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
71
72 // Requested language
73 if ( obj[ lang ] ) {
74 return obj[ lang ];
75 }
76 // Known user language
77 langs = OO.ui.getUserLanguages();
78 for ( i = 0, len = langs.length; i < len; i++ ) {
79 lang = langs[ i ];
80 if ( obj[ lang ] ) {
81 return obj[ lang ];
82 }
83 }
84 // Fallback language
85 if ( obj[ fallback ] ) {
86 return obj[ fallback ];
87 }
88 // First existing language
89 for ( lang in obj ) {
90 return obj[ lang ];
91 }
92
93 return undefined;
94 };
95
96 /**
97 * Check if a node is contained within another node
98 *
99 * Similar to jQuery#contains except a list of containers can be supplied
100 * and a boolean argument allows you to include the container in the match list
101 *
102 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
103 * @param {HTMLElement} contained Node to find
104 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
105 * @return {boolean} The node is in the list of target nodes
106 */
107 OO.ui.contains = function ( containers, contained, matchContainers ) {
108 var i;
109 if ( !Array.isArray( containers ) ) {
110 containers = [ containers ];
111 }
112 for ( i = containers.length - 1; i >= 0; i-- ) {
113 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
114 return true;
115 }
116 }
117 return false;
118 };
119
120 ( function () {
121 /**
122 * Message store for the default implementation of OO.ui.msg
123 *
124 * Environments that provide a localization system should not use this, but should override
125 * OO.ui.msg altogether.
126 *
127 * @private
128 */
129 var messages = {
130 // Tool tip for a button that moves items in a list down one place
131 'ooui-outline-control-move-down': 'Move item down',
132 // Tool tip for a button that moves items in a list up one place
133 'ooui-outline-control-move-up': 'Move item up',
134 // Tool tip for a button that removes items from a list
135 'ooui-outline-control-remove': 'Remove item',
136 // Label for the toolbar group that contains a list of all other available tools
137 'ooui-toolbar-more': 'More',
138 // Label for the fake tool that expands the full list of tools in a toolbar group
139 'ooui-toolgroup-expand': 'More',
140 // Label for the fake tool that collapses the full list of tools in a toolbar group
141 'ooui-toolgroup-collapse': 'Fewer',
142 // Default label for the accept button of a confirmation dialog
143 'ooui-dialog-message-accept': 'OK',
144 // Default label for the reject button of a confirmation dialog
145 'ooui-dialog-message-reject': 'Cancel',
146 // Title for process dialog error description
147 'ooui-dialog-process-error': 'Something went wrong',
148 // Label for process dialog dismiss error button, visible when describing errors
149 'ooui-dialog-process-dismiss': 'Dismiss',
150 // Label for process dialog retry action button, visible when describing only recoverable errors
151 'ooui-dialog-process-retry': 'Try again',
152 // Label for process dialog retry action button, visible when describing only warnings
153 'ooui-dialog-process-continue': 'Continue'
154 };
155
156 /**
157 * Get a localized message.
158 *
159 * In environments that provide a localization system, this function should be overridden to
160 * return the message translated in the user's language. The default implementation always returns
161 * English messages.
162 *
163 * After the message key, message parameters may optionally be passed. In the default implementation,
164 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
165 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
166 * they support unnamed, ordered message parameters.
167 *
168 * @abstract
169 * @param {string} key Message key
170 * @param {Mixed...} [params] Message parameters
171 * @return {string} Translated message with parameters substituted
172 */
173 OO.ui.msg = function ( key ) {
174 var message = messages[ key ],
175 params = Array.prototype.slice.call( arguments, 1 );
176 if ( typeof message === 'string' ) {
177 // Perform $1 substitution
178 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
179 var i = parseInt( n, 10 );
180 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
181 } );
182 } else {
183 // Return placeholder if message not found
184 message = '[' + key + ']';
185 }
186 return message;
187 };
188
189 /**
190 * Package a message and arguments for deferred resolution.
191 *
192 * Use this when you are statically specifying a message and the message may not yet be present.
193 *
194 * @param {string} key Message key
195 * @param {Mixed...} [params] Message parameters
196 * @return {Function} Function that returns the resolved message when executed
197 */
198 OO.ui.deferMsg = function () {
199 var args = arguments;
200 return function () {
201 return OO.ui.msg.apply( OO.ui, args );
202 };
203 };
204
205 /**
206 * Resolve a message.
207 *
208 * If the message is a function it will be executed, otherwise it will pass through directly.
209 *
210 * @param {Function|string} msg Deferred message, or message text
211 * @return {string} Resolved message
212 */
213 OO.ui.resolveMsg = function ( msg ) {
214 if ( $.isFunction( msg ) ) {
215 return msg();
216 }
217 return msg;
218 };
219
220 } )();
221
222 /**
223 * Element that can be marked as pending.
224 *
225 * @abstract
226 * @class
227 *
228 * @constructor
229 * @param {Object} [config] Configuration options
230 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
231 */
232 OO.ui.PendingElement = function OoUiPendingElement( config ) {
233 // Configuration initialization
234 config = config || {};
235
236 // Properties
237 this.pending = 0;
238 this.$pending = null;
239
240 // Initialisation
241 this.setPendingElement( config.$pending || this.$element );
242 };
243
244 /* Setup */
245
246 OO.initClass( OO.ui.PendingElement );
247
248 /* Methods */
249
250 /**
251 * Set the pending element (and clean up any existing one).
252 *
253 * @param {jQuery} $pending The element to set to pending.
254 */
255 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
256 if ( this.$pending ) {
257 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
258 }
259
260 this.$pending = $pending;
261 if ( this.pending > 0 ) {
262 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
263 }
264 };
265
266 /**
267 * Check if input is pending.
268 *
269 * @return {boolean}
270 */
271 OO.ui.PendingElement.prototype.isPending = function () {
272 return !!this.pending;
273 };
274
275 /**
276 * Increase the pending stack.
277 *
278 * @chainable
279 */
280 OO.ui.PendingElement.prototype.pushPending = function () {
281 if ( this.pending === 0 ) {
282 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
283 this.updateThemeClasses();
284 }
285 this.pending++;
286
287 return this;
288 };
289
290 /**
291 * Reduce the pending stack.
292 *
293 * Clamped at zero.
294 *
295 * @chainable
296 */
297 OO.ui.PendingElement.prototype.popPending = function () {
298 if ( this.pending === 1 ) {
299 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
300 this.updateThemeClasses();
301 }
302 this.pending = Math.max( 0, this.pending - 1 );
303
304 return this;
305 };
306
307 /**
308 * List of actions.
309 *
310 * @abstract
311 * @class
312 * @mixins OO.EventEmitter
313 *
314 * @constructor
315 * @param {Object} [config] Configuration options
316 */
317 OO.ui.ActionSet = function OoUiActionSet( config ) {
318 // Configuration initialization
319 config = config || {};
320
321 // Mixin constructors
322 OO.EventEmitter.call( this );
323
324 // Properties
325 this.list = [];
326 this.categories = {
327 actions: 'getAction',
328 flags: 'getFlags',
329 modes: 'getModes'
330 };
331 this.categorized = {};
332 this.special = {};
333 this.others = [];
334 this.organized = false;
335 this.changing = false;
336 this.changed = false;
337 };
338
339 /* Setup */
340
341 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
342
343 /* Static Properties */
344
345 /**
346 * Symbolic name of dialog.
347 *
348 * @abstract
349 * @static
350 * @inheritable
351 * @property {string}
352 */
353 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
354
355 /* Events */
356
357 /**
358 * @event click
359 * @param {OO.ui.ActionWidget} action Action that was clicked
360 */
361
362 /**
363 * @event resize
364 * @param {OO.ui.ActionWidget} action Action that was resized
365 */
366
367 /**
368 * @event add
369 * @param {OO.ui.ActionWidget[]} added Actions added
370 */
371
372 /**
373 * @event remove
374 * @param {OO.ui.ActionWidget[]} added Actions removed
375 */
376
377 /**
378 * @event change
379 */
380
381 /* Methods */
382
383 /**
384 * Handle action change events.
385 *
386 * @fires change
387 */
388 OO.ui.ActionSet.prototype.onActionChange = function () {
389 this.organized = false;
390 if ( this.changing ) {
391 this.changed = true;
392 } else {
393 this.emit( 'change' );
394 }
395 };
396
397 /**
398 * Check if a action is one of the special actions.
399 *
400 * @param {OO.ui.ActionWidget} action Action to check
401 * @return {boolean} Action is special
402 */
403 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
404 var flag;
405
406 for ( flag in this.special ) {
407 if ( action === this.special[ flag ] ) {
408 return true;
409 }
410 }
411
412 return false;
413 };
414
415 /**
416 * Get actions.
417 *
418 * @param {Object} [filters] Filters to use, omit to get all actions
419 * @param {string|string[]} [filters.actions] Actions that actions must have
420 * @param {string|string[]} [filters.flags] Flags that actions must have
421 * @param {string|string[]} [filters.modes] Modes that actions must have
422 * @param {boolean} [filters.visible] Actions must be visible
423 * @param {boolean} [filters.disabled] Actions must be disabled
424 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
425 */
426 OO.ui.ActionSet.prototype.get = function ( filters ) {
427 var i, len, list, category, actions, index, match, matches;
428
429 if ( filters ) {
430 this.organize();
431
432 // Collect category candidates
433 matches = [];
434 for ( category in this.categorized ) {
435 list = filters[ category ];
436 if ( list ) {
437 if ( !Array.isArray( list ) ) {
438 list = [ list ];
439 }
440 for ( i = 0, len = list.length; i < len; i++ ) {
441 actions = this.categorized[ category ][ list[ i ] ];
442 if ( Array.isArray( actions ) ) {
443 matches.push.apply( matches, actions );
444 }
445 }
446 }
447 }
448 // Remove by boolean filters
449 for ( i = 0, len = matches.length; i < len; i++ ) {
450 match = matches[ i ];
451 if (
452 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
453 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
454 ) {
455 matches.splice( i, 1 );
456 len--;
457 i--;
458 }
459 }
460 // Remove duplicates
461 for ( i = 0, len = matches.length; i < len; i++ ) {
462 match = matches[ i ];
463 index = matches.lastIndexOf( match );
464 while ( index !== i ) {
465 matches.splice( index, 1 );
466 len--;
467 index = matches.lastIndexOf( match );
468 }
469 }
470 return matches;
471 }
472 return this.list.slice();
473 };
474
475 /**
476 * Get special actions.
477 *
478 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
479 * Special flags can be configured by changing #static-specialFlags in a subclass.
480 *
481 * @return {OO.ui.ActionWidget|null} Safe action
482 */
483 OO.ui.ActionSet.prototype.getSpecial = function () {
484 this.organize();
485 return $.extend( {}, this.special );
486 };
487
488 /**
489 * Get other actions.
490 *
491 * Other actions include all non-special visible actions.
492 *
493 * @return {OO.ui.ActionWidget[]} Other actions
494 */
495 OO.ui.ActionSet.prototype.getOthers = function () {
496 this.organize();
497 return this.others.slice();
498 };
499
500 /**
501 * Toggle actions based on their modes.
502 *
503 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
504 * visibility; matching actions will be shown, non-matching actions will be hidden.
505 *
506 * @param {string} mode Mode actions must have
507 * @chainable
508 * @fires toggle
509 * @fires change
510 */
511 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
512 var i, len, action;
513
514 this.changing = true;
515 for ( i = 0, len = this.list.length; i < len; i++ ) {
516 action = this.list[ i ];
517 action.toggle( action.hasMode( mode ) );
518 }
519
520 this.organized = false;
521 this.changing = false;
522 this.emit( 'change' );
523
524 return this;
525 };
526
527 /**
528 * Change which actions are able to be performed.
529 *
530 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
531 *
532 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
533 * indicate actions are able to be performed
534 * @chainable
535 */
536 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
537 var i, len, action, item;
538
539 for ( i = 0, len = this.list.length; i < len; i++ ) {
540 item = this.list[ i ];
541 action = item.getAction();
542 if ( actions[ action ] !== undefined ) {
543 item.setDisabled( !actions[ action ] );
544 }
545 }
546
547 return this;
548 };
549
550 /**
551 * Executes a function once per action.
552 *
553 * When making changes to multiple actions, use this method instead of iterating over the actions
554 * manually to defer emitting a change event until after all actions have been changed.
555 *
556 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
557 * @param {Function} callback Callback to run for each action; callback is invoked with three
558 * arguments: the action, the action's index, the list of actions being iterated over
559 * @chainable
560 */
561 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
562 this.changed = false;
563 this.changing = true;
564 this.get( filter ).forEach( callback );
565 this.changing = false;
566 if ( this.changed ) {
567 this.emit( 'change' );
568 }
569
570 return this;
571 };
572
573 /**
574 * Add actions.
575 *
576 * @param {OO.ui.ActionWidget[]} actions Actions to add
577 * @chainable
578 * @fires add
579 * @fires change
580 */
581 OO.ui.ActionSet.prototype.add = function ( actions ) {
582 var i, len, action;
583
584 this.changing = true;
585 for ( i = 0, len = actions.length; i < len; i++ ) {
586 action = actions[ i ];
587 action.connect( this, {
588 click: [ 'emit', 'click', action ],
589 resize: [ 'emit', 'resize', action ],
590 toggle: [ 'onActionChange' ]
591 } );
592 this.list.push( action );
593 }
594 this.organized = false;
595 this.emit( 'add', actions );
596 this.changing = false;
597 this.emit( 'change' );
598
599 return this;
600 };
601
602 /**
603 * Remove actions.
604 *
605 * @param {OO.ui.ActionWidget[]} actions Actions to remove
606 * @chainable
607 * @fires remove
608 * @fires change
609 */
610 OO.ui.ActionSet.prototype.remove = function ( actions ) {
611 var i, len, index, action;
612
613 this.changing = true;
614 for ( i = 0, len = actions.length; i < len; i++ ) {
615 action = actions[ i ];
616 index = this.list.indexOf( action );
617 if ( index !== -1 ) {
618 action.disconnect( this );
619 this.list.splice( index, 1 );
620 }
621 }
622 this.organized = false;
623 this.emit( 'remove', actions );
624 this.changing = false;
625 this.emit( 'change' );
626
627 return this;
628 };
629
630 /**
631 * Remove all actions.
632 *
633 * @chainable
634 * @fires remove
635 * @fires change
636 */
637 OO.ui.ActionSet.prototype.clear = function () {
638 var i, len, action,
639 removed = this.list.slice();
640
641 this.changing = true;
642 for ( i = 0, len = this.list.length; i < len; i++ ) {
643 action = this.list[ i ];
644 action.disconnect( this );
645 }
646
647 this.list = [];
648
649 this.organized = false;
650 this.emit( 'remove', removed );
651 this.changing = false;
652 this.emit( 'change' );
653
654 return this;
655 };
656
657 /**
658 * Organize actions.
659 *
660 * This is called whenever organized information is requested. It will only reorganize the actions
661 * if something has changed since the last time it ran.
662 *
663 * @private
664 * @chainable
665 */
666 OO.ui.ActionSet.prototype.organize = function () {
667 var i, iLen, j, jLen, flag, action, category, list, item, special,
668 specialFlags = this.constructor.static.specialFlags;
669
670 if ( !this.organized ) {
671 this.categorized = {};
672 this.special = {};
673 this.others = [];
674 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
675 action = this.list[ i ];
676 if ( action.isVisible() ) {
677 // Populate categories
678 for ( category in this.categories ) {
679 if ( !this.categorized[ category ] ) {
680 this.categorized[ category ] = {};
681 }
682 list = action[ this.categories[ category ] ]();
683 if ( !Array.isArray( list ) ) {
684 list = [ list ];
685 }
686 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
687 item = list[ j ];
688 if ( !this.categorized[ category ][ item ] ) {
689 this.categorized[ category ][ item ] = [];
690 }
691 this.categorized[ category ][ item ].push( action );
692 }
693 }
694 // Populate special/others
695 special = false;
696 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
697 flag = specialFlags[ j ];
698 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
699 this.special[ flag ] = action;
700 special = true;
701 break;
702 }
703 }
704 if ( !special ) {
705 this.others.push( action );
706 }
707 }
708 }
709 this.organized = true;
710 }
711
712 return this;
713 };
714
715 /**
716 * DOM element abstraction.
717 *
718 * @abstract
719 * @class
720 *
721 * @constructor
722 * @param {Object} [config] Configuration options
723 * @cfg {Function} [$] jQuery for the frame the widget is in
724 * @cfg {string[]} [classes] CSS class names to add
725 * @cfg {string} [id] HTML id attribute
726 * @cfg {string} [text] Text to insert
727 * @cfg {jQuery} [$content] Content elements to append (after text)
728 * @cfg {Mixed} [data] Element data
729 */
730 OO.ui.Element = function OoUiElement( config ) {
731 // Configuration initialization
732 config = config || {};
733
734 // Properties
735 this.$ = config.$ || OO.ui.Element.static.getJQuery( document );
736 this.data = config.data;
737 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
738 this.elementGroup = null;
739 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
740 this.updateThemeClassesPending = false;
741
742 // Initialization
743 if ( $.isArray( config.classes ) ) {
744 this.$element.addClass( config.classes.join( ' ' ) );
745 }
746 if ( config.id ) {
747 this.$element.attr( 'id', config.id );
748 }
749 if ( config.text ) {
750 this.$element.text( config.text );
751 }
752 if ( config.$content ) {
753 this.$element.append( config.$content );
754 }
755 };
756
757 /* Setup */
758
759 OO.initClass( OO.ui.Element );
760
761 /* Static Properties */
762
763 /**
764 * HTML tag name.
765 *
766 * This may be ignored if #getTagName is overridden.
767 *
768 * @static
769 * @inheritable
770 * @property {string}
771 */
772 OO.ui.Element.static.tagName = 'div';
773
774 /* Static Methods */
775
776 /**
777 * Get a jQuery function within a specific document.
778 *
779 * @static
780 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
781 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
782 * not in an iframe
783 * @return {Function} Bound jQuery function
784 */
785 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
786 function wrapper( selector ) {
787 return $( selector, wrapper.context );
788 }
789
790 wrapper.context = this.getDocument( context );
791
792 if ( $iframe ) {
793 wrapper.$iframe = $iframe;
794 }
795
796 return wrapper;
797 };
798
799 /**
800 * Get the document of an element.
801 *
802 * @static
803 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
804 * @return {HTMLDocument|null} Document object
805 */
806 OO.ui.Element.static.getDocument = function ( obj ) {
807 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
808 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
809 // Empty jQuery selections might have a context
810 obj.context ||
811 // HTMLElement
812 obj.ownerDocument ||
813 // Window
814 obj.document ||
815 // HTMLDocument
816 ( obj.nodeType === 9 && obj ) ||
817 null;
818 };
819
820 /**
821 * Get the window of an element or document.
822 *
823 * @static
824 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
825 * @return {Window} Window object
826 */
827 OO.ui.Element.static.getWindow = function ( obj ) {
828 var doc = this.getDocument( obj );
829 return doc.parentWindow || doc.defaultView;
830 };
831
832 /**
833 * Get the direction of an element or document.
834 *
835 * @static
836 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
837 * @return {string} Text direction, either 'ltr' or 'rtl'
838 */
839 OO.ui.Element.static.getDir = function ( obj ) {
840 var isDoc, isWin;
841
842 if ( obj instanceof jQuery ) {
843 obj = obj[ 0 ];
844 }
845 isDoc = obj.nodeType === 9;
846 isWin = obj.document !== undefined;
847 if ( isDoc || isWin ) {
848 if ( isWin ) {
849 obj = obj.document;
850 }
851 obj = obj.body;
852 }
853 return $( obj ).css( 'direction' );
854 };
855
856 /**
857 * Get the offset between two frames.
858 *
859 * TODO: Make this function not use recursion.
860 *
861 * @static
862 * @param {Window} from Window of the child frame
863 * @param {Window} [to=window] Window of the parent frame
864 * @param {Object} [offset] Offset to start with, used internally
865 * @return {Object} Offset object, containing left and top properties
866 */
867 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
868 var i, len, frames, frame, rect;
869
870 if ( !to ) {
871 to = window;
872 }
873 if ( !offset ) {
874 offset = { top: 0, left: 0 };
875 }
876 if ( from.parent === from ) {
877 return offset;
878 }
879
880 // Get iframe element
881 frames = from.parent.document.getElementsByTagName( 'iframe' );
882 for ( i = 0, len = frames.length; i < len; i++ ) {
883 if ( frames[ i ].contentWindow === from ) {
884 frame = frames[ i ];
885 break;
886 }
887 }
888
889 // Recursively accumulate offset values
890 if ( frame ) {
891 rect = frame.getBoundingClientRect();
892 offset.left += rect.left;
893 offset.top += rect.top;
894 if ( from !== to ) {
895 this.getFrameOffset( from.parent, offset );
896 }
897 }
898 return offset;
899 };
900
901 /**
902 * Get the offset between two elements.
903 *
904 * The two elements may be in a different frame, but in that case the frame $element is in must
905 * be contained in the frame $anchor is in.
906 *
907 * @static
908 * @param {jQuery} $element Element whose position to get
909 * @param {jQuery} $anchor Element to get $element's position relative to
910 * @return {Object} Translated position coordinates, containing top and left properties
911 */
912 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
913 var iframe, iframePos,
914 pos = $element.offset(),
915 anchorPos = $anchor.offset(),
916 elementDocument = this.getDocument( $element ),
917 anchorDocument = this.getDocument( $anchor );
918
919 // If $element isn't in the same document as $anchor, traverse up
920 while ( elementDocument !== anchorDocument ) {
921 iframe = elementDocument.defaultView.frameElement;
922 if ( !iframe ) {
923 throw new Error( '$element frame is not contained in $anchor frame' );
924 }
925 iframePos = $( iframe ).offset();
926 pos.left += iframePos.left;
927 pos.top += iframePos.top;
928 elementDocument = iframe.ownerDocument;
929 }
930 pos.left -= anchorPos.left;
931 pos.top -= anchorPos.top;
932 return pos;
933 };
934
935 /**
936 * Get element border sizes.
937 *
938 * @static
939 * @param {HTMLElement} el Element to measure
940 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
941 */
942 OO.ui.Element.static.getBorders = function ( el ) {
943 var doc = el.ownerDocument,
944 win = doc.parentWindow || doc.defaultView,
945 style = win && win.getComputedStyle ?
946 win.getComputedStyle( el, null ) :
947 el.currentStyle,
948 $el = $( el ),
949 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
950 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
951 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
952 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
953
954 return {
955 top: top,
956 left: left,
957 bottom: bottom,
958 right: right
959 };
960 };
961
962 /**
963 * Get dimensions of an element or window.
964 *
965 * @static
966 * @param {HTMLElement|Window} el Element to measure
967 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
968 */
969 OO.ui.Element.static.getDimensions = function ( el ) {
970 var $el, $win,
971 doc = el.ownerDocument || el.document,
972 win = doc.parentWindow || doc.defaultView;
973
974 if ( win === el || el === doc.documentElement ) {
975 $win = $( win );
976 return {
977 borders: { top: 0, left: 0, bottom: 0, right: 0 },
978 scroll: {
979 top: $win.scrollTop(),
980 left: $win.scrollLeft()
981 },
982 scrollbar: { right: 0, bottom: 0 },
983 rect: {
984 top: 0,
985 left: 0,
986 bottom: $win.innerHeight(),
987 right: $win.innerWidth()
988 }
989 };
990 } else {
991 $el = $( el );
992 return {
993 borders: this.getBorders( el ),
994 scroll: {
995 top: $el.scrollTop(),
996 left: $el.scrollLeft()
997 },
998 scrollbar: {
999 right: $el.innerWidth() - el.clientWidth,
1000 bottom: $el.innerHeight() - el.clientHeight
1001 },
1002 rect: el.getBoundingClientRect()
1003 };
1004 }
1005 };
1006
1007 /**
1008 * Get scrollable object parent
1009 *
1010 * documentElement can't be used to get or set the scrollTop
1011 * property on Blink. Changing and testing its value lets us
1012 * use 'body' or 'documentElement' based on what is working.
1013 *
1014 * https://code.google.com/p/chromium/issues/detail?id=303131
1015 *
1016 * @static
1017 * @param {HTMLElement} el Element to find scrollable parent for
1018 * @return {HTMLElement} Scrollable parent
1019 */
1020 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1021 var scrollTop, body;
1022
1023 if ( OO.ui.scrollableElement === undefined ) {
1024 body = el.ownerDocument.body;
1025 scrollTop = body.scrollTop;
1026 body.scrollTop = 1;
1027
1028 if ( body.scrollTop === 1 ) {
1029 body.scrollTop = scrollTop;
1030 OO.ui.scrollableElement = 'body';
1031 } else {
1032 OO.ui.scrollableElement = 'documentElement';
1033 }
1034 }
1035
1036 return el.ownerDocument[ OO.ui.scrollableElement ];
1037 };
1038
1039 /**
1040 * Get closest scrollable container.
1041 *
1042 * Traverses up until either a scrollable element or the root is reached, in which case the window
1043 * will be returned.
1044 *
1045 * @static
1046 * @param {HTMLElement} el Element to find scrollable container for
1047 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1048 * @return {HTMLElement} Closest scrollable container
1049 */
1050 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1051 var i, val,
1052 props = [ 'overflow' ],
1053 $parent = $( el ).parent();
1054
1055 if ( dimension === 'x' || dimension === 'y' ) {
1056 props.push( 'overflow-' + dimension );
1057 }
1058
1059 while ( $parent.length ) {
1060 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1061 return $parent[ 0 ];
1062 }
1063 i = props.length;
1064 while ( i-- ) {
1065 val = $parent.css( props[ i ] );
1066 if ( val === 'auto' || val === 'scroll' ) {
1067 return $parent[ 0 ];
1068 }
1069 }
1070 $parent = $parent.parent();
1071 }
1072 return this.getDocument( el ).body;
1073 };
1074
1075 /**
1076 * Scroll element into view.
1077 *
1078 * @static
1079 * @param {HTMLElement} el Element to scroll into view
1080 * @param {Object} [config] Configuration options
1081 * @param {string} [config.duration] jQuery animation duration value
1082 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1083 * to scroll in both directions
1084 * @param {Function} [config.complete] Function to call when scrolling completes
1085 */
1086 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1087 // Configuration initialization
1088 config = config || {};
1089
1090 var rel, anim = {},
1091 callback = typeof config.complete === 'function' && config.complete,
1092 sc = this.getClosestScrollableContainer( el, config.direction ),
1093 $sc = $( sc ),
1094 eld = this.getDimensions( el ),
1095 scd = this.getDimensions( sc ),
1096 $win = $( this.getWindow( el ) );
1097
1098 // Compute the distances between the edges of el and the edges of the scroll viewport
1099 if ( $sc.is( 'html, body' ) ) {
1100 // If the scrollable container is the root, this is easy
1101 rel = {
1102 top: eld.rect.top,
1103 bottom: $win.innerHeight() - eld.rect.bottom,
1104 left: eld.rect.left,
1105 right: $win.innerWidth() - eld.rect.right
1106 };
1107 } else {
1108 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1109 rel = {
1110 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1111 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1112 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1113 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1114 };
1115 }
1116
1117 if ( !config.direction || config.direction === 'y' ) {
1118 if ( rel.top < 0 ) {
1119 anim.scrollTop = scd.scroll.top + rel.top;
1120 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1121 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1122 }
1123 }
1124 if ( !config.direction || config.direction === 'x' ) {
1125 if ( rel.left < 0 ) {
1126 anim.scrollLeft = scd.scroll.left + rel.left;
1127 } else if ( rel.left > 0 && rel.right < 0 ) {
1128 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1129 }
1130 }
1131 if ( !$.isEmptyObject( anim ) ) {
1132 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1133 if ( callback ) {
1134 $sc.queue( function ( next ) {
1135 callback();
1136 next();
1137 } );
1138 }
1139 } else {
1140 if ( callback ) {
1141 callback();
1142 }
1143 }
1144 };
1145
1146 /**
1147 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1148 * and reserve space for them, because it probably doesn't.
1149 *
1150 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1151 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1152 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1153 * and then reattach (or show) them back.
1154 *
1155 * @static
1156 * @param {HTMLElement} el Element to reconsider the scrollbars on
1157 */
1158 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1159 var i, len, nodes = [];
1160 // Detach all children
1161 while ( el.firstChild ) {
1162 nodes.push( el.firstChild );
1163 el.removeChild( el.firstChild );
1164 }
1165 // Force reflow
1166 void el.offsetHeight;
1167 // Reattach all children
1168 for ( i = 0, len = nodes.length; i < len; i++ ) {
1169 el.appendChild( nodes[ i ] );
1170 }
1171 };
1172
1173 /* Methods */
1174
1175 /**
1176 * Get element data.
1177 *
1178 * @return {Mixed} Element data
1179 */
1180 OO.ui.Element.prototype.getData = function () {
1181 return this.data;
1182 };
1183
1184 /**
1185 * Set element data.
1186 *
1187 * @param {Mixed} Element data
1188 * @chainable
1189 */
1190 OO.ui.Element.prototype.setData = function ( data ) {
1191 this.data = data;
1192 return this;
1193 };
1194
1195 /**
1196 * Check if element supports one or more methods.
1197 *
1198 * @param {string|string[]} methods Method or list of methods to check
1199 * @return {boolean} All methods are supported
1200 */
1201 OO.ui.Element.prototype.supports = function ( methods ) {
1202 var i, len,
1203 support = 0;
1204
1205 methods = $.isArray( methods ) ? methods : [ methods ];
1206 for ( i = 0, len = methods.length; i < len; i++ ) {
1207 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1208 support++;
1209 }
1210 }
1211
1212 return methods.length === support;
1213 };
1214
1215 /**
1216 * Update the theme-provided classes.
1217 *
1218 * @localdoc This is called in element mixins and widget classes any time state changes.
1219 * Updating is debounced, minimizing overhead of changing multiple attributes and
1220 * guaranteeing that theme updates do not occur within an element's constructor
1221 */
1222 OO.ui.Element.prototype.updateThemeClasses = function () {
1223 if ( !this.updateThemeClassesPending ) {
1224 this.updateThemeClassesPending = true;
1225 setTimeout( this.debouncedUpdateThemeClassesHandler );
1226 }
1227 };
1228
1229 /**
1230 * @private
1231 */
1232 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1233 OO.ui.theme.updateElementClasses( this );
1234 this.updateThemeClassesPending = false;
1235 };
1236
1237 /**
1238 * Get the HTML tag name.
1239 *
1240 * Override this method to base the result on instance information.
1241 *
1242 * @return {string} HTML tag name
1243 */
1244 OO.ui.Element.prototype.getTagName = function () {
1245 return this.constructor.static.tagName;
1246 };
1247
1248 /**
1249 * Check if the element is attached to the DOM
1250 * @return {boolean} The element is attached to the DOM
1251 */
1252 OO.ui.Element.prototype.isElementAttached = function () {
1253 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1254 };
1255
1256 /**
1257 * Get the DOM document.
1258 *
1259 * @return {HTMLDocument} Document object
1260 */
1261 OO.ui.Element.prototype.getElementDocument = function () {
1262 // Don't use this.$.context because subclasses can rebind this.$
1263 // Don't cache this in other ways either because subclasses could can change this.$element
1264 return OO.ui.Element.static.getDocument( this.$element );
1265 };
1266
1267 /**
1268 * Get the DOM window.
1269 *
1270 * @return {Window} Window object
1271 */
1272 OO.ui.Element.prototype.getElementWindow = function () {
1273 return OO.ui.Element.static.getWindow( this.$element );
1274 };
1275
1276 /**
1277 * Get closest scrollable container.
1278 */
1279 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1280 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1281 };
1282
1283 /**
1284 * Get group element is in.
1285 *
1286 * @return {OO.ui.GroupElement|null} Group element, null if none
1287 */
1288 OO.ui.Element.prototype.getElementGroup = function () {
1289 return this.elementGroup;
1290 };
1291
1292 /**
1293 * Set group element is in.
1294 *
1295 * @param {OO.ui.GroupElement|null} group Group element, null if none
1296 * @chainable
1297 */
1298 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1299 this.elementGroup = group;
1300 return this;
1301 };
1302
1303 /**
1304 * Scroll element into view.
1305 *
1306 * @param {Object} [config] Configuration options
1307 */
1308 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1309 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1310 };
1311
1312 /**
1313 * Container for elements.
1314 *
1315 * @abstract
1316 * @class
1317 * @extends OO.ui.Element
1318 * @mixins OO.EventEmitter
1319 *
1320 * @constructor
1321 * @param {Object} [config] Configuration options
1322 */
1323 OO.ui.Layout = function OoUiLayout( config ) {
1324 // Configuration initialization
1325 config = config || {};
1326
1327 // Parent constructor
1328 OO.ui.Layout.super.call( this, config );
1329
1330 // Mixin constructors
1331 OO.EventEmitter.call( this );
1332
1333 // Initialization
1334 this.$element.addClass( 'oo-ui-layout' );
1335 };
1336
1337 /* Setup */
1338
1339 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1340 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1341
1342 /**
1343 * User interface control.
1344 *
1345 * @abstract
1346 * @class
1347 * @extends OO.ui.Element
1348 * @mixins OO.EventEmitter
1349 *
1350 * @constructor
1351 * @param {Object} [config] Configuration options
1352 * @cfg {boolean} [disabled=false] Disable
1353 */
1354 OO.ui.Widget = function OoUiWidget( config ) {
1355 // Initialize config
1356 config = $.extend( { disabled: false }, config );
1357
1358 // Parent constructor
1359 OO.ui.Widget.super.call( this, config );
1360
1361 // Mixin constructors
1362 OO.EventEmitter.call( this );
1363
1364 // Properties
1365 this.visible = true;
1366 this.disabled = null;
1367 this.wasDisabled = null;
1368
1369 // Initialization
1370 this.$element.addClass( 'oo-ui-widget' );
1371 this.setDisabled( !!config.disabled );
1372 };
1373
1374 /* Setup */
1375
1376 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1377 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1378
1379 /* Events */
1380
1381 /**
1382 * @event disable
1383 * @param {boolean} disabled Widget is disabled
1384 */
1385
1386 /**
1387 * @event toggle
1388 * @param {boolean} visible Widget is visible
1389 */
1390
1391 /* Methods */
1392
1393 /**
1394 * Check if the widget is disabled.
1395 *
1396 * @return {boolean} Button is disabled
1397 */
1398 OO.ui.Widget.prototype.isDisabled = function () {
1399 return this.disabled;
1400 };
1401
1402 /**
1403 * Check if widget is visible.
1404 *
1405 * @return {boolean} Widget is visible
1406 */
1407 OO.ui.Widget.prototype.isVisible = function () {
1408 return this.visible;
1409 };
1410
1411 /**
1412 * Set the disabled state of the widget.
1413 *
1414 * This should probably change the widgets' appearance and prevent it from being used.
1415 *
1416 * @param {boolean} disabled Disable widget
1417 * @chainable
1418 */
1419 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1420 var isDisabled;
1421
1422 this.disabled = !!disabled;
1423 isDisabled = this.isDisabled();
1424 if ( isDisabled !== this.wasDisabled ) {
1425 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1426 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1427 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1428 this.emit( 'disable', isDisabled );
1429 this.updateThemeClasses();
1430 }
1431 this.wasDisabled = isDisabled;
1432
1433 return this;
1434 };
1435
1436 /**
1437 * Toggle visibility of widget.
1438 *
1439 * @param {boolean} [show] Make widget visible, omit to toggle visibility
1440 * @fires visible
1441 * @chainable
1442 */
1443 OO.ui.Widget.prototype.toggle = function ( show ) {
1444 show = show === undefined ? !this.visible : !!show;
1445
1446 if ( show !== this.isVisible() ) {
1447 this.visible = show;
1448 this.$element.toggle( show );
1449 this.emit( 'toggle', show );
1450 }
1451
1452 return this;
1453 };
1454
1455 /**
1456 * Update the disabled state, in case of changes in parent widget.
1457 *
1458 * @chainable
1459 */
1460 OO.ui.Widget.prototype.updateDisabled = function () {
1461 this.setDisabled( this.disabled );
1462 return this;
1463 };
1464
1465 /**
1466 * Container for elements in a child frame.
1467 *
1468 * Use together with OO.ui.WindowManager.
1469 *
1470 * @abstract
1471 * @class
1472 * @extends OO.ui.Element
1473 * @mixins OO.EventEmitter
1474 *
1475 * When a window is opened, the setup and ready processes are executed. Similarly, the hold and
1476 * teardown processes are executed when the window is closed.
1477 *
1478 * - {@link OO.ui.WindowManager#openWindow} or {@link #open} methods are used to start opening
1479 * - Window manager begins opening window
1480 * - {@link #getSetupProcess} method is called and its result executed
1481 * - {@link #getReadyProcess} method is called and its result executed
1482 * - Window is now open
1483 *
1484 * - {@link OO.ui.WindowManager#closeWindow} or {@link #close} methods are used to start closing
1485 * - Window manager begins closing window
1486 * - {@link #getHoldProcess} method is called and its result executed
1487 * - {@link #getTeardownProcess} method is called and its result executed
1488 * - Window is now closed
1489 *
1490 * Each process (setup, ready, hold and teardown) can be extended in subclasses by overriding
1491 * {@link #getSetupProcess}, {@link #getReadyProcess}, {@link #getHoldProcess} and
1492 * {@link #getTeardownProcess} respectively. Each process is executed in series, so asynchronous
1493 * processing can complete. Always assume window processes are executed asynchronously. See
1494 * OO.ui.Process for more details about how to work with processes. Some events, as well as the
1495 * #open and #close methods, provide promises which are resolved when the window enters a new state.
1496 *
1497 * Sizing of windows is specified using symbolic names which are interpreted by the window manager.
1498 * If the requested size is not recognized, the window manager will choose a sensible fallback.
1499 *
1500 * @constructor
1501 * @param {Object} [config] Configuration options
1502 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large`, `larger` or
1503 * `full`; omit to use #static-size
1504 */
1505 OO.ui.Window = function OoUiWindow( config ) {
1506 // Configuration initialization
1507 config = config || {};
1508
1509 // Parent constructor
1510 OO.ui.Window.super.call( this, config );
1511
1512 // Mixin constructors
1513 OO.EventEmitter.call( this );
1514
1515 // Properties
1516 this.manager = null;
1517 this.initialized = false;
1518 this.visible = false;
1519 this.opening = null;
1520 this.closing = null;
1521 this.opened = null;
1522 this.timing = null;
1523 this.loading = null;
1524 this.size = config.size || this.constructor.static.size;
1525 this.$frame = this.$( '<div>' );
1526 this.$overlay = this.$( '<div>' );
1527
1528 // Initialization
1529 this.$element
1530 .addClass( 'oo-ui-window' )
1531 .append( this.$frame, this.$overlay );
1532 this.$frame.addClass( 'oo-ui-window-frame' );
1533 this.$overlay.addClass( 'oo-ui-window-overlay' );
1534
1535 // NOTE: Additional initialization will occur when #setManager is called
1536 };
1537
1538 /* Setup */
1539
1540 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1541 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1542
1543 /* Static Properties */
1544
1545 /**
1546 * Symbolic name of size.
1547 *
1548 * Size is used if no size is configured during construction.
1549 *
1550 * @static
1551 * @inheritable
1552 * @property {string}
1553 */
1554 OO.ui.Window.static.size = 'medium';
1555
1556 /* Static Methods */
1557
1558 /**
1559 * Transplant the CSS styles from as parent document to a frame's document.
1560 *
1561 * This loops over the style sheets in the parent document, and copies their nodes to the
1562 * frame's document. It then polls the document to see when all styles have loaded, and once they
1563 * have, resolves the promise.
1564 *
1565 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
1566 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
1567 * Firefox, where the styles won't load until the iframe becomes visible.
1568 *
1569 * For details of how we arrived at the strategy used in this function, see #load.
1570 *
1571 * @static
1572 * @inheritable
1573 * @param {HTMLDocument} parentDoc Document to transplant styles from
1574 * @param {HTMLDocument} frameDoc Document to transplant styles to
1575 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
1576 * @return {jQuery.Promise} Promise resolved when styles have loaded
1577 */
1578 OO.ui.Window.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
1579 var i, numSheets, styleNode, styleText, newNode, timeoutID, pollNodeId, $pendingPollNodes,
1580 $pollNodes = $( [] ),
1581 // Fake font-family value
1582 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
1583 nextIndex = parentDoc.oouiFrameTransplantStylesNextIndex || 0,
1584 deferred = $.Deferred();
1585
1586 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
1587 styleNode = parentDoc.styleSheets[ i ].ownerNode;
1588 if ( styleNode.disabled ) {
1589 continue;
1590 }
1591
1592 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
1593 // External stylesheet; use @import
1594 styleText = '@import url(' + styleNode.href + ');';
1595 } else {
1596 // Internal stylesheet; just copy the text
1597 // For IE10 we need to fall back to .cssText, BUT that's undefined in
1598 // other browsers, so fall back to '' rather than 'undefined'
1599 styleText = styleNode.textContent || parentDoc.styleSheets[ i ].cssText || '';
1600 }
1601
1602 // Create a node with a unique ID that we're going to monitor to see when the CSS
1603 // has loaded
1604 if ( styleNode.oouiFrameTransplantStylesId ) {
1605 // If we're nesting transplantStyles operations and this node already has
1606 // a CSS rule to wait for loading, reuse it
1607 pollNodeId = styleNode.oouiFrameTransplantStylesId;
1608 } else {
1609 // Otherwise, create a new ID
1610 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + nextIndex;
1611 nextIndex++;
1612
1613 // Add #pollNodeId { font-family: ... } to the end of the stylesheet / after the @import
1614 // The font-family rule will only take effect once the @import finishes
1615 styleText += '\n' + '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
1616 }
1617
1618 // Create a node with id=pollNodeId
1619 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
1620 .attr( 'id', pollNodeId )
1621 .appendTo( frameDoc.body )
1622 );
1623
1624 // Add our modified CSS as a <style> tag
1625 newNode = frameDoc.createElement( 'style' );
1626 newNode.textContent = styleText;
1627 newNode.oouiFrameTransplantStylesId = pollNodeId;
1628 frameDoc.head.appendChild( newNode );
1629 }
1630 frameDoc.oouiFrameTransplantStylesNextIndex = nextIndex;
1631
1632 // Poll every 100ms until all external stylesheets have loaded
1633 $pendingPollNodes = $pollNodes;
1634 timeoutID = setTimeout( function pollExternalStylesheets() {
1635 while (
1636 $pendingPollNodes.length > 0 &&
1637 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
1638 ) {
1639 $pendingPollNodes = $pendingPollNodes.slice( 1 );
1640 }
1641
1642 if ( $pendingPollNodes.length === 0 ) {
1643 // We're done!
1644 if ( timeoutID !== null ) {
1645 timeoutID = null;
1646 $pollNodes.remove();
1647 deferred.resolve();
1648 }
1649 } else {
1650 timeoutID = setTimeout( pollExternalStylesheets, 100 );
1651 }
1652 }, 100 );
1653 // ...but give up after a while
1654 if ( timeout !== 0 ) {
1655 setTimeout( function () {
1656 if ( timeoutID ) {
1657 clearTimeout( timeoutID );
1658 timeoutID = null;
1659 $pollNodes.remove();
1660 deferred.reject();
1661 }
1662 }, timeout || 5000 );
1663 }
1664
1665 return deferred.promise();
1666 };
1667
1668 /* Methods */
1669
1670 /**
1671 * Handle mouse down events.
1672 *
1673 * @param {jQuery.Event} e Mouse down event
1674 */
1675 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1676 // Prevent clicking on the click-block from stealing focus
1677 if ( e.target === this.$element[ 0 ] ) {
1678 return false;
1679 }
1680 };
1681
1682 /**
1683 * Check if window has been initialized.
1684 *
1685 * @return {boolean} Window has been initialized
1686 */
1687 OO.ui.Window.prototype.isInitialized = function () {
1688 return this.initialized;
1689 };
1690
1691 /**
1692 * Check if window is visible.
1693 *
1694 * @return {boolean} Window is visible
1695 */
1696 OO.ui.Window.prototype.isVisible = function () {
1697 return this.visible;
1698 };
1699
1700 /**
1701 * Check if window is loading.
1702 *
1703 * @return {boolean} Window is loading
1704 */
1705 OO.ui.Window.prototype.isLoading = function () {
1706 return this.loading && this.loading.state() === 'pending';
1707 };
1708
1709 /**
1710 * Check if window is loaded.
1711 *
1712 * @return {boolean} Window is loaded
1713 */
1714 OO.ui.Window.prototype.isLoaded = function () {
1715 return this.loading && this.loading.state() === 'resolved';
1716 };
1717
1718 /**
1719 * Check if window is opening.
1720 *
1721 * This is a wrapper around OO.ui.WindowManager#isOpening.
1722 *
1723 * @return {boolean} Window is opening
1724 */
1725 OO.ui.Window.prototype.isOpening = function () {
1726 return this.manager.isOpening( this );
1727 };
1728
1729 /**
1730 * Check if window is closing.
1731 *
1732 * This is a wrapper around OO.ui.WindowManager#isClosing.
1733 *
1734 * @return {boolean} Window is closing
1735 */
1736 OO.ui.Window.prototype.isClosing = function () {
1737 return this.manager.isClosing( this );
1738 };
1739
1740 /**
1741 * Check if window is opened.
1742 *
1743 * This is a wrapper around OO.ui.WindowManager#isOpened.
1744 *
1745 * @return {boolean} Window is opened
1746 */
1747 OO.ui.Window.prototype.isOpened = function () {
1748 return this.manager.isOpened( this );
1749 };
1750
1751 /**
1752 * Get the window manager.
1753 *
1754 * @return {OO.ui.WindowManager} Manager of window
1755 */
1756 OO.ui.Window.prototype.getManager = function () {
1757 return this.manager;
1758 };
1759
1760 /**
1761 * Get the window size.
1762 *
1763 * @return {string} Symbolic size name, e.g. `small`, `medium`, `large`, `larger`, `full`
1764 */
1765 OO.ui.Window.prototype.getSize = function () {
1766 return this.size;
1767 };
1768
1769 /**
1770 * Disable transitions on window's frame for the duration of the callback function, then enable them
1771 * back.
1772 *
1773 * @private
1774 * @param {Function} callback Function to call while transitions are disabled
1775 */
1776 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1777 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1778 // Disable transitions first, otherwise we'll get values from when the window was animating.
1779 var oldTransition,
1780 styleObj = this.$frame[ 0 ].style;
1781 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1782 styleObj.MozTransition || styleObj.WebkitTransition;
1783 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1784 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1785 callback();
1786 // Force reflow to make sure the style changes done inside callback really are not transitioned
1787 this.$frame.height();
1788 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1789 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1790 };
1791
1792 /**
1793 * Get the height of the dialog contents.
1794 *
1795 * @return {number} Content height
1796 */
1797 OO.ui.Window.prototype.getContentHeight = function () {
1798 var bodyHeight,
1799 win = this,
1800 bodyStyleObj = this.$body[ 0 ].style,
1801 frameStyleObj = this.$frame[ 0 ].style;
1802
1803 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1804 // Disable transitions first, otherwise we'll get values from when the window was animating.
1805 this.withoutSizeTransitions( function () {
1806 var oldHeight = frameStyleObj.height,
1807 oldPosition = bodyStyleObj.position;
1808 frameStyleObj.height = '1px';
1809 // Force body to resize to new width
1810 bodyStyleObj.position = 'relative';
1811 bodyHeight = win.getBodyHeight();
1812 frameStyleObj.height = oldHeight;
1813 bodyStyleObj.position = oldPosition;
1814 } );
1815
1816 return (
1817 // Add buffer for border
1818 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1819 // Use combined heights of children
1820 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1821 );
1822 };
1823
1824 /**
1825 * Get the height of the dialog contents.
1826 *
1827 * When this function is called, the dialog will temporarily have been resized
1828 * to height=1px, so .scrollHeight measurements can be taken accurately.
1829 *
1830 * @return {number} Height of content
1831 */
1832 OO.ui.Window.prototype.getBodyHeight = function () {
1833 return this.$body[ 0 ].scrollHeight;
1834 };
1835
1836 /**
1837 * Get the directionality of the frame
1838 *
1839 * @return {string} Directionality, 'ltr' or 'rtl'
1840 */
1841 OO.ui.Window.prototype.getDir = function () {
1842 return this.dir;
1843 };
1844
1845 /**
1846 * Get a process for setting up a window for use.
1847 *
1848 * Each time the window is opened this process will set it up for use in a particular context, based
1849 * on the `data` argument.
1850 *
1851 * When you override this method, you can add additional setup steps to the process the parent
1852 * method provides using the 'first' and 'next' methods.
1853 *
1854 * @abstract
1855 * @param {Object} [data] Window opening data
1856 * @return {OO.ui.Process} Setup process
1857 */
1858 OO.ui.Window.prototype.getSetupProcess = function () {
1859 return new OO.ui.Process();
1860 };
1861
1862 /**
1863 * Get a process for readying a window for use.
1864 *
1865 * Each time the window is open and setup, this process will ready it up for use in a particular
1866 * context, based on the `data` argument.
1867 *
1868 * When you override this method, you can add additional setup steps to the process the parent
1869 * method provides using the 'first' and 'next' methods.
1870 *
1871 * @abstract
1872 * @param {Object} [data] Window opening data
1873 * @return {OO.ui.Process} Setup process
1874 */
1875 OO.ui.Window.prototype.getReadyProcess = function () {
1876 return new OO.ui.Process();
1877 };
1878
1879 /**
1880 * Get a process for holding a window from use.
1881 *
1882 * Each time the window is closed, this process will hold it from use in a particular context, based
1883 * on the `data` argument.
1884 *
1885 * When you override this method, you can add additional setup steps to the process the parent
1886 * method provides using the 'first' and 'next' methods.
1887 *
1888 * @abstract
1889 * @param {Object} [data] Window closing data
1890 * @return {OO.ui.Process} Hold process
1891 */
1892 OO.ui.Window.prototype.getHoldProcess = function () {
1893 return new OO.ui.Process();
1894 };
1895
1896 /**
1897 * Get a process for tearing down a window after use.
1898 *
1899 * Each time the window is closed this process will tear it down and do something with the user's
1900 * interactions within the window, based on the `data` argument.
1901 *
1902 * When you override this method, you can add additional teardown steps to the process the parent
1903 * method provides using the 'first' and 'next' methods.
1904 *
1905 * @abstract
1906 * @param {Object} [data] Window closing data
1907 * @return {OO.ui.Process} Teardown process
1908 */
1909 OO.ui.Window.prototype.getTeardownProcess = function () {
1910 return new OO.ui.Process();
1911 };
1912
1913 /**
1914 * Toggle visibility of window.
1915 *
1916 * If the window is isolated and hasn't fully loaded yet, the visibility property will be used
1917 * instead of display.
1918 *
1919 * @param {boolean} [show] Make window visible, omit to toggle visibility
1920 * @fires toggle
1921 * @chainable
1922 */
1923 OO.ui.Window.prototype.toggle = function ( show ) {
1924 show = show === undefined ? !this.visible : !!show;
1925
1926 if ( show !== this.isVisible() ) {
1927 this.visible = show;
1928
1929 if ( this.isolated && !this.isLoaded() ) {
1930 // Hide the window using visibility instead of display until loading is complete
1931 // Can't use display: none; because that prevents the iframe from loading in Firefox
1932 this.$element.css( 'visibility', show ? 'visible' : 'hidden' );
1933 } else {
1934 this.$element.toggle( show ).css( 'visibility', '' );
1935 }
1936 this.emit( 'toggle', show );
1937 }
1938
1939 return this;
1940 };
1941
1942 /**
1943 * Set the window manager.
1944 *
1945 * This must be called before initialize. Calling it more than once will cause an error.
1946 *
1947 * @param {OO.ui.WindowManager} manager Manager for this window
1948 * @throws {Error} If called more than once
1949 * @chainable
1950 */
1951 OO.ui.Window.prototype.setManager = function ( manager ) {
1952 if ( this.manager ) {
1953 throw new Error( 'Cannot set window manager, window already has a manager' );
1954 }
1955
1956 // Properties
1957 this.manager = manager;
1958 this.isolated = manager.shouldIsolate();
1959
1960 // Initialization
1961 if ( this.isolated ) {
1962 this.$iframe = this.$( '<iframe>' );
1963 this.$iframe.attr( { frameborder: 0, scrolling: 'no' } );
1964 this.$frame.append( this.$iframe );
1965 this.$ = function () {
1966 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
1967 };
1968 // WARNING: Do not use this.$ again until #initialize is called
1969 } else {
1970 this.$content = this.$( '<div>' );
1971 this.$document = $( this.getElementDocument() );
1972 this.$content.addClass( 'oo-ui-window-content' ).attr( 'tabIndex', 0 );
1973 this.$frame.append( this.$content );
1974 }
1975 this.toggle( false );
1976
1977 // Figure out directionality:
1978 this.dir = OO.ui.Element.static.getDir( this.$iframe || this.$content ) || 'ltr';
1979
1980 return this;
1981 };
1982
1983 /**
1984 * Set the window size.
1985 *
1986 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1987 * @chainable
1988 */
1989 OO.ui.Window.prototype.setSize = function ( size ) {
1990 this.size = size;
1991 this.updateSize();
1992 return this;
1993 };
1994
1995 /**
1996 * Update the window size.
1997 *
1998 * @chainable
1999 */
2000 OO.ui.Window.prototype.updateSize = function () {
2001 this.manager.updateWindowSize( this );
2002 return this;
2003 };
2004
2005 /**
2006 * Set window dimensions.
2007 *
2008 * Properties are applied to the frame container.
2009 *
2010 * @param {Object} dim CSS dimension properties
2011 * @param {string|number} [dim.width] Width
2012 * @param {string|number} [dim.minWidth] Minimum width
2013 * @param {string|number} [dim.maxWidth] Maximum width
2014 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2015 * @param {string|number} [dim.minWidth] Minimum height
2016 * @param {string|number} [dim.maxWidth] Maximum height
2017 * @chainable
2018 */
2019 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2020 var height,
2021 win = this,
2022 styleObj = this.$frame[ 0 ].style;
2023
2024 // Calculate the height we need to set using the correct width
2025 if ( dim.height === undefined ) {
2026 this.withoutSizeTransitions( function () {
2027 var oldWidth = styleObj.width;
2028 win.$frame.css( 'width', dim.width || '' );
2029 height = win.getContentHeight();
2030 styleObj.width = oldWidth;
2031 } );
2032 } else {
2033 height = dim.height;
2034 }
2035
2036 this.$frame.css( {
2037 width: dim.width || '',
2038 minWidth: dim.minWidth || '',
2039 maxWidth: dim.maxWidth || '',
2040 height: height || '',
2041 minHeight: dim.minHeight || '',
2042 maxHeight: dim.maxHeight || ''
2043 } );
2044
2045 return this;
2046 };
2047
2048 /**
2049 * Initialize window contents.
2050 *
2051 * The first time the window is opened, #initialize is called when it's safe to begin populating
2052 * its contents. See #getSetupProcess for a way to make changes each time the window opens.
2053 *
2054 * Once this method is called, this.$ can be used to create elements within the frame.
2055 *
2056 * @throws {Error} If not attached to a manager
2057 * @chainable
2058 */
2059 OO.ui.Window.prototype.initialize = function () {
2060 if ( !this.manager ) {
2061 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2062 }
2063
2064 // Properties
2065 this.$head = this.$( '<div>' );
2066 this.$body = this.$( '<div>' );
2067 this.$foot = this.$( '<div>' );
2068 this.$innerOverlay = this.$( '<div>' );
2069
2070 // Events
2071 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2072
2073 // Initialization
2074 this.$head.addClass( 'oo-ui-window-head' );
2075 this.$body.addClass( 'oo-ui-window-body' );
2076 this.$foot.addClass( 'oo-ui-window-foot' );
2077 this.$innerOverlay.addClass( 'oo-ui-window-inner-overlay' );
2078 this.$content.append( this.$head, this.$body, this.$foot, this.$innerOverlay );
2079
2080 return this;
2081 };
2082
2083 /**
2084 * Open window.
2085 *
2086 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
2087 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
2088 *
2089 * @param {Object} [data] Window opening data
2090 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
2091 * first argument will be a promise which will be resolved when the window begins closing
2092 */
2093 OO.ui.Window.prototype.open = function ( data ) {
2094 return this.manager.openWindow( this, data );
2095 };
2096
2097 /**
2098 * Close window.
2099 *
2100 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
2101 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
2102 *
2103 * @param {Object} [data] Window closing data
2104 * @return {jQuery.Promise} Promise resolved when window is closed
2105 */
2106 OO.ui.Window.prototype.close = function ( data ) {
2107 return this.manager.closeWindow( this, data );
2108 };
2109
2110 /**
2111 * Setup window.
2112 *
2113 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2114 * by other systems.
2115 *
2116 * @param {Object} [data] Window opening data
2117 * @return {jQuery.Promise} Promise resolved when window is setup
2118 */
2119 OO.ui.Window.prototype.setup = function ( data ) {
2120 var win = this,
2121 deferred = $.Deferred();
2122
2123 this.$element.show();
2124 this.visible = true;
2125 this.getSetupProcess( data ).execute().done( function () {
2126 // Force redraw by asking the browser to measure the elements' widths
2127 win.$element.addClass( 'oo-ui-window-setup' ).width();
2128 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2129 deferred.resolve();
2130 } );
2131
2132 return deferred.promise();
2133 };
2134
2135 /**
2136 * Ready window.
2137 *
2138 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2139 * by other systems.
2140 *
2141 * @param {Object} [data] Window opening data
2142 * @return {jQuery.Promise} Promise resolved when window is ready
2143 */
2144 OO.ui.Window.prototype.ready = function ( data ) {
2145 var win = this,
2146 deferred = $.Deferred();
2147
2148 this.$content.focus();
2149 this.getReadyProcess( data ).execute().done( function () {
2150 // Force redraw by asking the browser to measure the elements' widths
2151 win.$element.addClass( 'oo-ui-window-ready' ).width();
2152 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2153 deferred.resolve();
2154 } );
2155
2156 return deferred.promise();
2157 };
2158
2159 /**
2160 * Hold window.
2161 *
2162 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2163 * by other systems.
2164 *
2165 * @param {Object} [data] Window closing data
2166 * @return {jQuery.Promise} Promise resolved when window is held
2167 */
2168 OO.ui.Window.prototype.hold = function ( data ) {
2169 var win = this,
2170 deferred = $.Deferred();
2171
2172 this.getHoldProcess( data ).execute().done( function () {
2173 // Get the focused element within the window's content
2174 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2175
2176 // Blur the focused element
2177 if ( $focus.length ) {
2178 $focus[ 0 ].blur();
2179 }
2180
2181 // Force redraw by asking the browser to measure the elements' widths
2182 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2183 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2184 deferred.resolve();
2185 } );
2186
2187 return deferred.promise();
2188 };
2189
2190 /**
2191 * Teardown window.
2192 *
2193 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2194 * by other systems.
2195 *
2196 * @param {Object} [data] Window closing data
2197 * @return {jQuery.Promise} Promise resolved when window is torn down
2198 */
2199 OO.ui.Window.prototype.teardown = function ( data ) {
2200 var win = this,
2201 deferred = $.Deferred();
2202
2203 this.getTeardownProcess( data ).execute().done( function () {
2204 // Force redraw by asking the browser to measure the elements' widths
2205 win.$element.removeClass( 'oo-ui-window-load oo-ui-window-setup' ).width();
2206 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2207 win.$element.hide();
2208 win.visible = false;
2209 deferred.resolve();
2210 } );
2211
2212 return deferred.promise();
2213 };
2214
2215 /**
2216 * Load the frame contents.
2217 *
2218 * Once the iframe's stylesheets are loaded the returned promise will be resolved. Calling while
2219 * loading will return a promise but not trigger a new loading cycle. Calling after loading is
2220 * complete will return a promise that's already been resolved.
2221 *
2222 * Sounds simple right? Read on...
2223 *
2224 * When you create a dynamic iframe using open/write/close, the window.load event for the
2225 * iframe is triggered when you call close, and there's no further load event to indicate that
2226 * everything is actually loaded.
2227 *
2228 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
2229 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
2230 * are added to document.styleSheets immediately, and the only way you can determine whether they've
2231 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
2232 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
2233 *
2234 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>`
2235 * tags. Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets
2236 * until the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the
2237 * `@import` has finished. And because the contents of the `<style>` tag are from the same origin,
2238 * accessing .cssRules is allowed.
2239 *
2240 * However, now that we control the styles we're injecting, we might as well do away with
2241 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
2242 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
2243 * and wait for its font-family to change to someValue. Because `@import` is blocking, the
2244 * font-family rule is not applied until after the `@import` finishes.
2245 *
2246 * All this stylesheet injection and polling magic is in #transplantStyles.
2247 *
2248 * @return {jQuery.Promise} Promise resolved when loading is complete
2249 */
2250 OO.ui.Window.prototype.load = function () {
2251 var sub, doc, loading,
2252 win = this;
2253
2254 this.$element.addClass( 'oo-ui-window-load' );
2255
2256 // Non-isolated windows are already "loaded"
2257 if ( !this.loading && !this.isolated ) {
2258 this.loading = $.Deferred().resolve();
2259 this.initialize();
2260 // Set initialized state after so sub-classes aren't confused by it being set by calling
2261 // their parent initialize method
2262 this.initialized = true;
2263 }
2264
2265 // Return existing promise if already loading or loaded
2266 if ( this.loading ) {
2267 return this.loading.promise();
2268 }
2269
2270 // Load the frame
2271 loading = this.loading = $.Deferred();
2272 sub = this.$iframe.prop( 'contentWindow' );
2273 doc = sub.document;
2274
2275 // Initialize contents
2276 doc.open();
2277 doc.write(
2278 '<!doctype html>' +
2279 '<html>' +
2280 '<body class="oo-ui-window-isolated oo-ui-' + this.dir + '"' +
2281 ' style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
2282 '<div class="oo-ui-window-content"></div>' +
2283 '</body>' +
2284 '</html>'
2285 );
2286 doc.close();
2287
2288 // Properties
2289 this.$ = OO.ui.Element.static.getJQuery( doc, this.$iframe );
2290 this.$content = this.$( '.oo-ui-window-content' ).attr( 'tabIndex', 0 );
2291 this.$document = this.$( doc );
2292
2293 // Initialization
2294 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[ 0 ] )
2295 .always( function () {
2296 // Initialize isolated windows
2297 win.initialize();
2298 // Set initialized state after so sub-classes aren't confused by it being set by calling
2299 // their parent initialize method
2300 win.initialized = true;
2301 // Undo the visibility: hidden; hack and apply display: none;
2302 // We can do this safely now that the iframe has initialized
2303 // (don't do this from within #initialize because it has to happen
2304 // after the all subclasses have been handled as well).
2305 win.toggle( win.isVisible() );
2306
2307 loading.resolve();
2308 } );
2309
2310 return loading.promise();
2311 };
2312
2313 /**
2314 * Base class for all dialogs.
2315 *
2316 * Logic:
2317 * - Manage the window (open and close, etc.).
2318 * - Store the internal name and display title.
2319 * - A stack to track one or more pending actions.
2320 * - Manage a set of actions that can be performed.
2321 * - Configure and create action widgets.
2322 *
2323 * User interface:
2324 * - Close the dialog with Escape key.
2325 * - Visually lock the dialog while an action is in
2326 * progress (aka "pending").
2327 *
2328 * Subclass responsibilities:
2329 * - Display the title somewhere.
2330 * - Add content to the dialog.
2331 * - Provide a UI to close the dialog.
2332 * - Display the action widgets somewhere.
2333 *
2334 * @abstract
2335 * @class
2336 * @extends OO.ui.Window
2337 * @mixins OO.ui.PendingElement
2338 *
2339 * @constructor
2340 * @param {Object} [config] Configuration options
2341 */
2342 OO.ui.Dialog = function OoUiDialog( config ) {
2343 // Parent constructor
2344 OO.ui.Dialog.super.call( this, config );
2345
2346 // Mixin constructors
2347 OO.ui.PendingElement.call( this );
2348
2349 // Properties
2350 this.actions = new OO.ui.ActionSet();
2351 this.attachedActions = [];
2352 this.currentAction = null;
2353 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2354
2355 // Events
2356 this.actions.connect( this, {
2357 click: 'onActionClick',
2358 resize: 'onActionResize',
2359 change: 'onActionsChange'
2360 } );
2361
2362 // Initialization
2363 this.$element
2364 .addClass( 'oo-ui-dialog' )
2365 .attr( 'role', 'dialog' );
2366 };
2367
2368 /* Setup */
2369
2370 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2371 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2372
2373 /* Static Properties */
2374
2375 /**
2376 * Symbolic name of dialog.
2377 *
2378 * @abstract
2379 * @static
2380 * @inheritable
2381 * @property {string}
2382 */
2383 OO.ui.Dialog.static.name = '';
2384
2385 /**
2386 * Dialog title.
2387 *
2388 * @abstract
2389 * @static
2390 * @inheritable
2391 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2392 */
2393 OO.ui.Dialog.static.title = '';
2394
2395 /**
2396 * List of OO.ui.ActionWidget configuration options.
2397 *
2398 * @static
2399 * inheritable
2400 * @property {Object[]}
2401 */
2402 OO.ui.Dialog.static.actions = [];
2403
2404 /**
2405 * Close dialog when the escape key is pressed.
2406 *
2407 * @static
2408 * @abstract
2409 * @inheritable
2410 * @property {boolean}
2411 */
2412 OO.ui.Dialog.static.escapable = true;
2413
2414 /* Methods */
2415
2416 /**
2417 * Handle frame document key down events.
2418 *
2419 * @param {jQuery.Event} e Key down event
2420 */
2421 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2422 if ( e.which === OO.ui.Keys.ESCAPE ) {
2423 this.close();
2424 e.preventDefault();
2425 e.stopPropagation();
2426 }
2427 };
2428
2429 /**
2430 * Handle action resized events.
2431 *
2432 * @param {OO.ui.ActionWidget} action Action that was resized
2433 */
2434 OO.ui.Dialog.prototype.onActionResize = function () {
2435 // Override in subclass
2436 };
2437
2438 /**
2439 * Handle action click events.
2440 *
2441 * @param {OO.ui.ActionWidget} action Action that was clicked
2442 */
2443 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2444 if ( !this.isPending() ) {
2445 this.currentAction = action;
2446 this.executeAction( action.getAction() );
2447 }
2448 };
2449
2450 /**
2451 * Handle actions change event.
2452 */
2453 OO.ui.Dialog.prototype.onActionsChange = function () {
2454 this.detachActions();
2455 if ( !this.isClosing() ) {
2456 this.attachActions();
2457 }
2458 };
2459
2460 /**
2461 * Get set of actions.
2462 *
2463 * @return {OO.ui.ActionSet}
2464 */
2465 OO.ui.Dialog.prototype.getActions = function () {
2466 return this.actions;
2467 };
2468
2469 /**
2470 * Get a process for taking action.
2471 *
2472 * When you override this method, you can add additional accept steps to the process the parent
2473 * method provides using the 'first' and 'next' methods.
2474 *
2475 * @abstract
2476 * @param {string} [action] Symbolic name of action
2477 * @return {OO.ui.Process} Action process
2478 */
2479 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2480 return new OO.ui.Process()
2481 .next( function () {
2482 if ( !action ) {
2483 // An empty action always closes the dialog without data, which should always be
2484 // safe and make no changes
2485 this.close();
2486 }
2487 }, this );
2488 };
2489
2490 /**
2491 * @inheritdoc
2492 *
2493 * @param {Object} [data] Dialog opening data
2494 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use #static-title
2495 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2496 * action item, omit to use #static-actions
2497 */
2498 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2499 data = data || {};
2500
2501 // Parent method
2502 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2503 .next( function () {
2504 var i, len,
2505 items = [],
2506 config = this.constructor.static,
2507 actions = data.actions !== undefined ? data.actions : config.actions;
2508
2509 this.title.setLabel(
2510 data.title !== undefined ? data.title : this.constructor.static.title
2511 );
2512 for ( i = 0, len = actions.length; i < len; i++ ) {
2513 items.push(
2514 new OO.ui.ActionWidget( $.extend( { $: this.$ }, actions[ i ] ) )
2515 );
2516 }
2517 this.actions.add( items );
2518
2519 if ( this.constructor.static.escapable ) {
2520 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2521 }
2522 }, this );
2523 };
2524
2525 /**
2526 * @inheritdoc
2527 */
2528 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2529 // Parent method
2530 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2531 .first( function () {
2532 if ( this.constructor.static.escapable ) {
2533 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2534 }
2535
2536 this.actions.clear();
2537 this.currentAction = null;
2538 }, this );
2539 };
2540
2541 /**
2542 * @inheritdoc
2543 */
2544 OO.ui.Dialog.prototype.initialize = function () {
2545 // Parent method
2546 OO.ui.Dialog.super.prototype.initialize.call( this );
2547
2548 // Properties
2549 this.title = new OO.ui.LabelWidget( { $: this.$ } );
2550
2551 // Initialization
2552 this.$content.addClass( 'oo-ui-dialog-content' );
2553 this.setPendingElement( this.$head );
2554 };
2555
2556 /**
2557 * Attach action actions.
2558 */
2559 OO.ui.Dialog.prototype.attachActions = function () {
2560 // Remember the list of potentially attached actions
2561 this.attachedActions = this.actions.get();
2562 };
2563
2564 /**
2565 * Detach action actions.
2566 *
2567 * @chainable
2568 */
2569 OO.ui.Dialog.prototype.detachActions = function () {
2570 var i, len;
2571
2572 // Detach all actions that may have been previously attached
2573 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2574 this.attachedActions[ i ].$element.detach();
2575 }
2576 this.attachedActions = [];
2577 };
2578
2579 /**
2580 * Execute an action.
2581 *
2582 * @param {string} action Symbolic name of action to execute
2583 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2584 */
2585 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2586 this.pushPending();
2587 return this.getActionProcess( action ).execute()
2588 .always( this.popPending.bind( this ) );
2589 };
2590
2591 /**
2592 * Collection of windows.
2593 *
2594 * @class
2595 * @extends OO.ui.Element
2596 * @mixins OO.EventEmitter
2597 *
2598 * Managed windows are mutually exclusive. If a window is opened while there is a current window
2599 * already opening or opened, the current window will be closed without data. Empty closing data
2600 * should always result in the window being closed without causing constructive or destructive
2601 * action.
2602 *
2603 * As a window is opened and closed, it passes through several stages and the manager emits several
2604 * corresponding events.
2605 *
2606 * - {@link #openWindow} or {@link OO.ui.Window#open} methods are used to start opening
2607 * - {@link #event-opening} is emitted with `opening` promise
2608 * - {@link #getSetupDelay} is called the returned value is used to time a pause in execution
2609 * - {@link OO.ui.Window#getSetupProcess} method is called on the window and its result executed
2610 * - `setup` progress notification is emitted from opening promise
2611 * - {@link #getReadyDelay} is called the returned value is used to time a pause in execution
2612 * - {@link OO.ui.Window#getReadyProcess} method is called on the window and its result executed
2613 * - `ready` progress notification is emitted from opening promise
2614 * - `opening` promise is resolved with `opened` promise
2615 * - Window is now open
2616 *
2617 * - {@link #closeWindow} or {@link OO.ui.Window#close} methods are used to start closing
2618 * - `opened` promise is resolved with `closing` promise
2619 * - {@link #event-closing} is emitted with `closing` promise
2620 * - {@link #getHoldDelay} is called the returned value is used to time a pause in execution
2621 * - {@link OO.ui.Window#getHoldProcess} method is called on the window and its result executed
2622 * - `hold` progress notification is emitted from opening promise
2623 * - {@link #getTeardownDelay} is called the returned value is used to time a pause in execution
2624 * - {@link OO.ui.Window#getTeardownProcess} method is called on the window and its result executed
2625 * - `teardown` progress notification is emitted from opening promise
2626 * - Closing promise is resolved
2627 * - Window is now closed
2628 *
2629 * @constructor
2630 * @param {Object} [config] Configuration options
2631 * @cfg {boolean} [isolate] Configure managed windows to isolate their content using inline frames
2632 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2633 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2634 */
2635 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2636 // Configuration initialization
2637 config = config || {};
2638
2639 // Parent constructor
2640 OO.ui.WindowManager.super.call( this, config );
2641
2642 // Mixin constructors
2643 OO.EventEmitter.call( this );
2644
2645 // Properties
2646 this.factory = config.factory;
2647 this.modal = config.modal === undefined || !!config.modal;
2648 this.isolate = !!config.isolate;
2649 this.windows = {};
2650 this.opening = null;
2651 this.opened = null;
2652 this.closing = null;
2653 this.preparingToOpen = null;
2654 this.preparingToClose = null;
2655 this.size = null;
2656 this.currentWindow = null;
2657 this.$ariaHidden = null;
2658 this.requestedSize = null;
2659 this.onWindowResizeTimeout = null;
2660 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2661 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2662 this.onWindowMouseWheelHandler = this.onWindowMouseWheel.bind( this );
2663 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2664
2665 // Initialization
2666 this.$element
2667 .addClass( 'oo-ui-windowManager' )
2668 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2669 };
2670
2671 /* Setup */
2672
2673 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2674 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2675
2676 /* Events */
2677
2678 /**
2679 * Window is opening.
2680 *
2681 * Fired when the window begins to be opened.
2682 *
2683 * @event opening
2684 * @param {OO.ui.Window} win Window that's being opened
2685 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2686 * resolved the first argument will be a promise which will be resolved when the window begins
2687 * closing, the second argument will be the opening data; progress notifications will be fired on
2688 * the promise for `setup` and `ready` when those processes are completed respectively.
2689 * @param {Object} data Window opening data
2690 */
2691
2692 /**
2693 * Window is closing.
2694 *
2695 * Fired when the window begins to be closed.
2696 *
2697 * @event closing
2698 * @param {OO.ui.Window} win Window that's being closed
2699 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2700 * is resolved the first argument will be a the closing data; progress notifications will be fired
2701 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2702 * @param {Object} data Window closing data
2703 */
2704
2705 /**
2706 * Window was resized.
2707 *
2708 * @event resize
2709 * @param {OO.ui.Window} win Window that was resized
2710 */
2711
2712 /* Static Properties */
2713
2714 /**
2715 * Map of symbolic size names and CSS properties.
2716 *
2717 * @static
2718 * @inheritable
2719 * @property {Object}
2720 */
2721 OO.ui.WindowManager.static.sizes = {
2722 small: {
2723 width: 300
2724 },
2725 medium: {
2726 width: 500
2727 },
2728 large: {
2729 width: 700
2730 },
2731 larger: {
2732 width: 900
2733 },
2734 full: {
2735 // These can be non-numeric because they are never used in calculations
2736 width: '100%',
2737 height: '100%'
2738 }
2739 };
2740
2741 /**
2742 * Symbolic name of default size.
2743 *
2744 * Default size is used if the window's requested size is not recognized.
2745 *
2746 * @static
2747 * @inheritable
2748 * @property {string}
2749 */
2750 OO.ui.WindowManager.static.defaultSize = 'medium';
2751
2752 /* Methods */
2753
2754 /**
2755 * Handle window resize events.
2756 *
2757 * @param {jQuery.Event} e Window resize event
2758 */
2759 OO.ui.WindowManager.prototype.onWindowResize = function () {
2760 clearTimeout( this.onWindowResizeTimeout );
2761 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2762 };
2763
2764 /**
2765 * Handle window resize events.
2766 *
2767 * @param {jQuery.Event} e Window resize event
2768 */
2769 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2770 if ( this.currentWindow ) {
2771 this.updateWindowSize( this.currentWindow );
2772 }
2773 };
2774
2775 /**
2776 * Handle window mouse wheel events.
2777 *
2778 * @param {jQuery.Event} e Mouse wheel event
2779 */
2780 OO.ui.WindowManager.prototype.onWindowMouseWheel = function () {
2781 // Kill all events in the parent window if the child window is isolated
2782 return !this.shouldIsolate();
2783 };
2784
2785 /**
2786 * Handle document key down events.
2787 *
2788 * @param {jQuery.Event} e Key down event
2789 */
2790 OO.ui.WindowManager.prototype.onDocumentKeyDown = function ( e ) {
2791 switch ( e.which ) {
2792 case OO.ui.Keys.PAGEUP:
2793 case OO.ui.Keys.PAGEDOWN:
2794 case OO.ui.Keys.END:
2795 case OO.ui.Keys.HOME:
2796 case OO.ui.Keys.LEFT:
2797 case OO.ui.Keys.UP:
2798 case OO.ui.Keys.RIGHT:
2799 case OO.ui.Keys.DOWN:
2800 // Kill all events in the parent window if the child window is isolated
2801 return !this.shouldIsolate();
2802 }
2803 };
2804
2805 /**
2806 * Check if window is opening.
2807 *
2808 * @return {boolean} Window is opening
2809 */
2810 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2811 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2812 };
2813
2814 /**
2815 * Check if window is closing.
2816 *
2817 * @return {boolean} Window is closing
2818 */
2819 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2820 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2821 };
2822
2823 /**
2824 * Check if window is opened.
2825 *
2826 * @return {boolean} Window is opened
2827 */
2828 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2829 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2830 };
2831
2832 /**
2833 * Check if window contents should be isolated.
2834 *
2835 * Window content isolation is done using inline frames.
2836 *
2837 * @return {boolean} Window contents should be isolated
2838 */
2839 OO.ui.WindowManager.prototype.shouldIsolate = function () {
2840 return this.isolate;
2841 };
2842
2843 /**
2844 * Check if a window is being managed.
2845 *
2846 * @param {OO.ui.Window} win Window to check
2847 * @return {boolean} Window is being managed
2848 */
2849 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2850 var name;
2851
2852 for ( name in this.windows ) {
2853 if ( this.windows[ name ] === win ) {
2854 return true;
2855 }
2856 }
2857
2858 return false;
2859 };
2860
2861 /**
2862 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2863 *
2864 * @param {OO.ui.Window} win Window being opened
2865 * @param {Object} [data] Window opening data
2866 * @return {number} Milliseconds to wait
2867 */
2868 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2869 return 0;
2870 };
2871
2872 /**
2873 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2874 *
2875 * @param {OO.ui.Window} win Window being opened
2876 * @param {Object} [data] Window opening data
2877 * @return {number} Milliseconds to wait
2878 */
2879 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2880 return 0;
2881 };
2882
2883 /**
2884 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2885 *
2886 * @param {OO.ui.Window} win Window being closed
2887 * @param {Object} [data] Window closing data
2888 * @return {number} Milliseconds to wait
2889 */
2890 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2891 return 0;
2892 };
2893
2894 /**
2895 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2896 *
2897 * @param {OO.ui.Window} win Window being closed
2898 * @param {Object} [data] Window closing data
2899 * @return {number} Milliseconds to wait
2900 */
2901 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2902 return this.modal ? 250 : 0;
2903 };
2904
2905 /**
2906 * Get managed window by symbolic name.
2907 *
2908 * If window is not yet instantiated, it will be instantiated and added automatically.
2909 *
2910 * @param {string} name Symbolic window name
2911 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2912 * @throws {Error} If the symbolic name is unrecognized by the factory
2913 * @throws {Error} If the symbolic name unrecognized as a managed window
2914 */
2915 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2916 var deferred = $.Deferred(),
2917 win = this.windows[ name ];
2918
2919 if ( !( win instanceof OO.ui.Window ) ) {
2920 if ( this.factory ) {
2921 if ( !this.factory.lookup( name ) ) {
2922 deferred.reject( new OO.ui.Error(
2923 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2924 ) );
2925 } else {
2926 win = this.factory.create( name, this, { $: this.$ } );
2927 this.addWindows( [ win ] );
2928 deferred.resolve( win );
2929 }
2930 } else {
2931 deferred.reject( new OO.ui.Error(
2932 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2933 ) );
2934 }
2935 } else {
2936 deferred.resolve( win );
2937 }
2938
2939 return deferred.promise();
2940 };
2941
2942 /**
2943 * Get current window.
2944 *
2945 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2946 */
2947 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2948 return this.currentWindow;
2949 };
2950
2951 /**
2952 * Open a window.
2953 *
2954 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2955 * @param {Object} [data] Window opening data
2956 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2957 * for more details about the `opening` promise
2958 * @fires opening
2959 */
2960 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2961 var manager = this,
2962 preparing = [],
2963 opening = $.Deferred();
2964
2965 // Argument handling
2966 if ( typeof win === 'string' ) {
2967 return this.getWindow( win ).then( function ( win ) {
2968 return manager.openWindow( win, data );
2969 } );
2970 }
2971
2972 // Error handling
2973 if ( !this.hasWindow( win ) ) {
2974 opening.reject( new OO.ui.Error(
2975 'Cannot open window: window is not attached to manager'
2976 ) );
2977 } else if ( this.preparingToOpen || this.opening || this.opened ) {
2978 opening.reject( new OO.ui.Error(
2979 'Cannot open window: another window is opening or open'
2980 ) );
2981 }
2982
2983 // Window opening
2984 if ( opening.state() !== 'rejected' ) {
2985 if ( !win.getManager() ) {
2986 win.setManager( this );
2987 }
2988 preparing.push( win.load() );
2989
2990 if ( this.closing ) {
2991 // If a window is currently closing, wait for it to complete
2992 preparing.push( this.closing );
2993 }
2994
2995 this.preparingToOpen = $.when.apply( $, preparing );
2996 // Ensure handlers get called after preparingToOpen is set
2997 this.preparingToOpen.done( function () {
2998 if ( manager.modal ) {
2999 manager.toggleGlobalEvents( true );
3000 manager.toggleAriaIsolation( true );
3001 }
3002 manager.currentWindow = win;
3003 manager.opening = opening;
3004 manager.preparingToOpen = null;
3005 manager.emit( 'opening', win, opening, data );
3006 setTimeout( function () {
3007 win.setup( data ).then( function () {
3008 manager.updateWindowSize( win );
3009 manager.opening.notify( { state: 'setup' } );
3010 setTimeout( function () {
3011 win.ready( data ).then( function () {
3012 manager.opening.notify( { state: 'ready' } );
3013 manager.opening = null;
3014 manager.opened = $.Deferred();
3015 opening.resolve( manager.opened.promise(), data );
3016 } );
3017 }, manager.getReadyDelay() );
3018 } );
3019 }, manager.getSetupDelay() );
3020 } );
3021 }
3022
3023 return opening.promise();
3024 };
3025
3026 /**
3027 * Close a window.
3028 *
3029 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3030 * @param {Object} [data] Window closing data
3031 * @return {jQuery.Promise} Promise resolved when window is done closing; see {@link #event-closing}
3032 * for more details about the `closing` promise
3033 * @throws {Error} If no window by that name is being managed
3034 * @fires closing
3035 */
3036 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3037 var manager = this,
3038 preparing = [],
3039 closing = $.Deferred(),
3040 opened;
3041
3042 // Argument handling
3043 if ( typeof win === 'string' ) {
3044 win = this.windows[ win ];
3045 } else if ( !this.hasWindow( win ) ) {
3046 win = null;
3047 }
3048
3049 // Error handling
3050 if ( !win ) {
3051 closing.reject( new OO.ui.Error(
3052 'Cannot close window: window is not attached to manager'
3053 ) );
3054 } else if ( win !== this.currentWindow ) {
3055 closing.reject( new OO.ui.Error(
3056 'Cannot close window: window already closed with different data'
3057 ) );
3058 } else if ( this.preparingToClose || this.closing ) {
3059 closing.reject( new OO.ui.Error(
3060 'Cannot close window: window already closing with different data'
3061 ) );
3062 }
3063
3064 // Window closing
3065 if ( closing.state() !== 'rejected' ) {
3066 if ( this.opening ) {
3067 // If the window is currently opening, close it when it's done
3068 preparing.push( this.opening );
3069 }
3070
3071 this.preparingToClose = $.when.apply( $, preparing );
3072 // Ensure handlers get called after preparingToClose is set
3073 this.preparingToClose.done( function () {
3074 manager.closing = closing;
3075 manager.preparingToClose = null;
3076 manager.emit( 'closing', win, closing, data );
3077 opened = manager.opened;
3078 manager.opened = null;
3079 opened.resolve( closing.promise(), data );
3080 setTimeout( function () {
3081 win.hold( data ).then( function () {
3082 closing.notify( { state: 'hold' } );
3083 setTimeout( function () {
3084 win.teardown( data ).then( function () {
3085 closing.notify( { state: 'teardown' } );
3086 if ( manager.modal ) {
3087 manager.toggleGlobalEvents( false );
3088 manager.toggleAriaIsolation( false );
3089 }
3090 manager.closing = null;
3091 manager.currentWindow = null;
3092 closing.resolve( data );
3093 } );
3094 }, manager.getTeardownDelay() );
3095 } );
3096 }, manager.getHoldDelay() );
3097 } );
3098 }
3099
3100 return closing.promise();
3101 };
3102
3103 /**
3104 * Add windows.
3105 *
3106 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
3107 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
3108 * a statically configured symbolic name
3109 */
3110 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3111 var i, len, win, name, list;
3112
3113 if ( $.isArray( windows ) ) {
3114 // Convert to map of windows by looking up symbolic names from static configuration
3115 list = {};
3116 for ( i = 0, len = windows.length; i < len; i++ ) {
3117 name = windows[ i ].constructor.static.name;
3118 if ( typeof name !== 'string' ) {
3119 throw new Error( 'Cannot add window' );
3120 }
3121 list[ name ] = windows[ i ];
3122 }
3123 } else if ( $.isPlainObject( windows ) ) {
3124 list = windows;
3125 }
3126
3127 // Add windows
3128 for ( name in list ) {
3129 win = list[ name ];
3130 this.windows[ name ] = win;
3131 this.$element.append( win.$element );
3132 }
3133 };
3134
3135 /**
3136 * Remove windows.
3137 *
3138 * Windows will be closed before they are removed.
3139 *
3140 * @param {string[]} names Symbolic names of windows to remove
3141 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3142 * @throws {Error} If windows being removed are not being managed
3143 */
3144 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3145 var i, len, win, name, cleanupWindow,
3146 manager = this,
3147 promises = [],
3148 cleanup = function ( name, win ) {
3149 delete manager.windows[ name ];
3150 win.$element.detach();
3151 };
3152
3153 for ( i = 0, len = names.length; i < len; i++ ) {
3154 name = names[ i ];
3155 win = this.windows[ name ];
3156 if ( !win ) {
3157 throw new Error( 'Cannot remove window' );
3158 }
3159 cleanupWindow = cleanup.bind( null, name, win );
3160 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3161 }
3162
3163 return $.when.apply( $, promises );
3164 };
3165
3166 /**
3167 * Remove all windows.
3168 *
3169 * Windows will be closed before they are removed.
3170 *
3171 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3172 */
3173 OO.ui.WindowManager.prototype.clearWindows = function () {
3174 return this.removeWindows( Object.keys( this.windows ) );
3175 };
3176
3177 /**
3178 * Set dialog size.
3179 *
3180 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3181 *
3182 * @chainable
3183 */
3184 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3185 // Bypass for non-current, and thus invisible, windows
3186 if ( win !== this.currentWindow ) {
3187 return;
3188 }
3189
3190 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3191 sizes = this.constructor.static.sizes,
3192 size = win.getSize();
3193
3194 if ( !sizes[ size ] ) {
3195 size = this.constructor.static.defaultSize;
3196 }
3197 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3198 size = 'full';
3199 }
3200
3201 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3202 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3203 win.setDimensions( sizes[ size ] );
3204
3205 this.emit( 'resize', win );
3206
3207 return this;
3208 };
3209
3210 /**
3211 * Bind or unbind global events for scrolling.
3212 *
3213 * @param {boolean} [on] Bind global events
3214 * @chainable
3215 */
3216 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3217 on = on === undefined ? !!this.globalEvents : !!on;
3218
3219 if ( on ) {
3220 if ( !this.globalEvents ) {
3221 this.$( this.getElementDocument() ).on( {
3222 // Prevent scrolling by keys in top-level window
3223 keydown: this.onDocumentKeyDownHandler
3224 } );
3225 this.$( this.getElementWindow() ).on( {
3226 // Prevent scrolling by wheel in top-level window
3227 mousewheel: this.onWindowMouseWheelHandler,
3228 // Start listening for top-level window dimension changes
3229 'orientationchange resize': this.onWindowResizeHandler
3230 } );
3231 // Disable window scrolling in isolated windows
3232 if ( !this.shouldIsolate() ) {
3233 $( this.getElementDocument().body ).css( 'overflow', 'hidden' );
3234 }
3235 this.globalEvents = true;
3236 }
3237 } else if ( this.globalEvents ) {
3238 // Unbind global events
3239 this.$( this.getElementDocument() ).off( {
3240 // Allow scrolling by keys in top-level window
3241 keydown: this.onDocumentKeyDownHandler
3242 } );
3243 this.$( this.getElementWindow() ).off( {
3244 // Allow scrolling by wheel in top-level window
3245 mousewheel: this.onWindowMouseWheelHandler,
3246 // Stop listening for top-level window dimension changes
3247 'orientationchange resize': this.onWindowResizeHandler
3248 } );
3249 if ( !this.shouldIsolate() ) {
3250 $( this.getElementDocument().body ).css( 'overflow', '' );
3251 }
3252 this.globalEvents = false;
3253 }
3254
3255 return this;
3256 };
3257
3258 /**
3259 * Toggle screen reader visibility of content other than the window manager.
3260 *
3261 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3262 * @chainable
3263 */
3264 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3265 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3266
3267 if ( isolate ) {
3268 if ( !this.$ariaHidden ) {
3269 // Hide everything other than the window manager from screen readers
3270 this.$ariaHidden = $( 'body' )
3271 .children()
3272 .not( this.$element.parentsUntil( 'body' ).last() )
3273 .attr( 'aria-hidden', '' );
3274 }
3275 } else if ( this.$ariaHidden ) {
3276 // Restore screen reader visibility
3277 this.$ariaHidden.removeAttr( 'aria-hidden' );
3278 this.$ariaHidden = null;
3279 }
3280
3281 return this;
3282 };
3283
3284 /**
3285 * Destroy window manager.
3286 */
3287 OO.ui.WindowManager.prototype.destroy = function () {
3288 this.toggleGlobalEvents( false );
3289 this.toggleAriaIsolation( false );
3290 this.clearWindows();
3291 this.$element.remove();
3292 };
3293
3294 /**
3295 * @class
3296 *
3297 * @constructor
3298 * @param {string|jQuery} message Description of error
3299 * @param {Object} [config] Configuration options
3300 * @cfg {boolean} [recoverable=true] Error is recoverable
3301 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3302 */
3303 OO.ui.Error = function OoUiElement( message, config ) {
3304 // Configuration initialization
3305 config = config || {};
3306
3307 // Properties
3308 this.message = message instanceof jQuery ? message : String( message );
3309 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3310 this.warning = !!config.warning;
3311 };
3312
3313 /* Setup */
3314
3315 OO.initClass( OO.ui.Error );
3316
3317 /* Methods */
3318
3319 /**
3320 * Check if error can be recovered from.
3321 *
3322 * @return {boolean} Error is recoverable
3323 */
3324 OO.ui.Error.prototype.isRecoverable = function () {
3325 return this.recoverable;
3326 };
3327
3328 /**
3329 * Check if the error is a warning
3330 *
3331 * @return {boolean} Error is warning
3332 */
3333 OO.ui.Error.prototype.isWarning = function () {
3334 return this.warning;
3335 };
3336
3337 /**
3338 * Get error message as DOM nodes.
3339 *
3340 * @return {jQuery} Error message in DOM nodes
3341 */
3342 OO.ui.Error.prototype.getMessage = function () {
3343 return this.message instanceof jQuery ?
3344 this.message.clone() :
3345 $( '<div>' ).text( this.message ).contents();
3346 };
3347
3348 /**
3349 * Get error message as text.
3350 *
3351 * @return {string} Error message
3352 */
3353 OO.ui.Error.prototype.getMessageText = function () {
3354 return this.message instanceof jQuery ? this.message.text() : this.message;
3355 };
3356
3357 /**
3358 * A list of functions, called in sequence.
3359 *
3360 * If a function added to a process returns boolean false the process will stop; if it returns an
3361 * object with a `promise` method the process will use the promise to either continue to the next
3362 * step when the promise is resolved or stop when the promise is rejected.
3363 *
3364 * @class
3365 *
3366 * @constructor
3367 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3368 * call, see #createStep for more information
3369 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3370 * or a promise
3371 * @return {Object} Step object, with `callback` and `context` properties
3372 */
3373 OO.ui.Process = function ( step, context ) {
3374 // Properties
3375 this.steps = [];
3376
3377 // Initialization
3378 if ( step !== undefined ) {
3379 this.next( step, context );
3380 }
3381 };
3382
3383 /* Setup */
3384
3385 OO.initClass( OO.ui.Process );
3386
3387 /* Methods */
3388
3389 /**
3390 * Start the process.
3391 *
3392 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3393 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3394 * process, the remaining steps will not be taken
3395 */
3396 OO.ui.Process.prototype.execute = function () {
3397 var i, len, promise;
3398
3399 /**
3400 * Continue execution.
3401 *
3402 * @ignore
3403 * @param {Array} step A function and the context it should be called in
3404 * @return {Function} Function that continues the process
3405 */
3406 function proceed( step ) {
3407 return function () {
3408 // Execute step in the correct context
3409 var deferred,
3410 result = step.callback.call( step.context );
3411
3412 if ( result === false ) {
3413 // Use rejected promise for boolean false results
3414 return $.Deferred().reject( [] ).promise();
3415 }
3416 if ( typeof result === 'number' ) {
3417 if ( result < 0 ) {
3418 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3419 }
3420 // Use a delayed promise for numbers, expecting them to be in milliseconds
3421 deferred = $.Deferred();
3422 setTimeout( deferred.resolve, result );
3423 return deferred.promise();
3424 }
3425 if ( result instanceof OO.ui.Error ) {
3426 // Use rejected promise for error
3427 return $.Deferred().reject( [ result ] ).promise();
3428 }
3429 if ( $.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3430 // Use rejected promise for list of errors
3431 return $.Deferred().reject( result ).promise();
3432 }
3433 // Duck-type the object to see if it can produce a promise
3434 if ( result && $.isFunction( result.promise ) ) {
3435 // Use a promise generated from the result
3436 return result.promise();
3437 }
3438 // Use resolved promise for other results
3439 return $.Deferred().resolve().promise();
3440 };
3441 }
3442
3443 if ( this.steps.length ) {
3444 // Generate a chain reaction of promises
3445 promise = proceed( this.steps[ 0 ] )();
3446 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3447 promise = promise.then( proceed( this.steps[ i ] ) );
3448 }
3449 } else {
3450 promise = $.Deferred().resolve().promise();
3451 }
3452
3453 return promise;
3454 };
3455
3456 /**
3457 * Create a process step.
3458 *
3459 * @private
3460 * @param {number|jQuery.Promise|Function} step
3461 *
3462 * - Number of milliseconds to wait; or
3463 * - Promise to wait to be resolved; or
3464 * - Function to execute
3465 * - If it returns boolean false the process will stop
3466 * - If it returns an object with a `promise` method the process will use the promise to either
3467 * continue to the next step when the promise is resolved or stop when the promise is rejected
3468 * - If it returns a number, the process will wait for that number of milliseconds before
3469 * proceeding
3470 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3471 * or a promise
3472 * @return {Object} Step object, with `callback` and `context` properties
3473 */
3474 OO.ui.Process.prototype.createStep = function ( step, context ) {
3475 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3476 return {
3477 callback: function () {
3478 return step;
3479 },
3480 context: null
3481 };
3482 }
3483 if ( $.isFunction( step ) ) {
3484 return {
3485 callback: step,
3486 context: context
3487 };
3488 }
3489 throw new Error( 'Cannot create process step: number, promise or function expected' );
3490 };
3491
3492 /**
3493 * Add step to the beginning of the process.
3494 *
3495 * @inheritdoc #createStep
3496 * @return {OO.ui.Process} this
3497 * @chainable
3498 */
3499 OO.ui.Process.prototype.first = function ( step, context ) {
3500 this.steps.unshift( this.createStep( step, context ) );
3501 return this;
3502 };
3503
3504 /**
3505 * Add step to the end of the process.
3506 *
3507 * @inheritdoc #createStep
3508 * @return {OO.ui.Process} this
3509 * @chainable
3510 */
3511 OO.ui.Process.prototype.next = function ( step, context ) {
3512 this.steps.push( this.createStep( step, context ) );
3513 return this;
3514 };
3515
3516 /**
3517 * Factory for tools.
3518 *
3519 * @class
3520 * @extends OO.Factory
3521 * @constructor
3522 */
3523 OO.ui.ToolFactory = function OoUiToolFactory() {
3524 // Parent constructor
3525 OO.ui.ToolFactory.super.call( this );
3526 };
3527
3528 /* Setup */
3529
3530 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3531
3532 /* Methods */
3533
3534 /**
3535 * Get tools from the factory
3536 *
3537 * @param {Array} include Included tools
3538 * @param {Array} exclude Excluded tools
3539 * @param {Array} promote Promoted tools
3540 * @param {Array} demote Demoted tools
3541 * @return {string[]} List of tools
3542 */
3543 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3544 var i, len, included, promoted, demoted,
3545 auto = [],
3546 used = {};
3547
3548 // Collect included and not excluded tools
3549 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3550
3551 // Promotion
3552 promoted = this.extract( promote, used );
3553 demoted = this.extract( demote, used );
3554
3555 // Auto
3556 for ( i = 0, len = included.length; i < len; i++ ) {
3557 if ( !used[ included[ i ] ] ) {
3558 auto.push( included[ i ] );
3559 }
3560 }
3561
3562 return promoted.concat( auto ).concat( demoted );
3563 };
3564
3565 /**
3566 * Get a flat list of names from a list of names or groups.
3567 *
3568 * Tools can be specified in the following ways:
3569 *
3570 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3571 * - All tools in a group: `{ group: 'group-name' }`
3572 * - All tools: `'*'`
3573 *
3574 * @private
3575 * @param {Array|string} collection List of tools
3576 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3577 * names will be added as properties
3578 * @return {string[]} List of extracted names
3579 */
3580 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3581 var i, len, item, name, tool,
3582 names = [];
3583
3584 if ( collection === '*' ) {
3585 for ( name in this.registry ) {
3586 tool = this.registry[ name ];
3587 if (
3588 // Only add tools by group name when auto-add is enabled
3589 tool.static.autoAddToCatchall &&
3590 // Exclude already used tools
3591 ( !used || !used[ name ] )
3592 ) {
3593 names.push( name );
3594 if ( used ) {
3595 used[ name ] = true;
3596 }
3597 }
3598 }
3599 } else if ( $.isArray( collection ) ) {
3600 for ( i = 0, len = collection.length; i < len; i++ ) {
3601 item = collection[ i ];
3602 // Allow plain strings as shorthand for named tools
3603 if ( typeof item === 'string' ) {
3604 item = { name: item };
3605 }
3606 if ( OO.isPlainObject( item ) ) {
3607 if ( item.group ) {
3608 for ( name in this.registry ) {
3609 tool = this.registry[ name ];
3610 if (
3611 // Include tools with matching group
3612 tool.static.group === item.group &&
3613 // Only add tools by group name when auto-add is enabled
3614 tool.static.autoAddToGroup &&
3615 // Exclude already used tools
3616 ( !used || !used[ name ] )
3617 ) {
3618 names.push( name );
3619 if ( used ) {
3620 used[ name ] = true;
3621 }
3622 }
3623 }
3624 // Include tools with matching name and exclude already used tools
3625 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3626 names.push( item.name );
3627 if ( used ) {
3628 used[ item.name ] = true;
3629 }
3630 }
3631 }
3632 }
3633 }
3634 return names;
3635 };
3636
3637 /**
3638 * Factory for tool groups.
3639 *
3640 * @class
3641 * @extends OO.Factory
3642 * @constructor
3643 */
3644 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3645 // Parent constructor
3646 OO.Factory.call( this );
3647
3648 var i, l,
3649 defaultClasses = this.constructor.static.getDefaultClasses();
3650
3651 // Register default toolgroups
3652 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3653 this.register( defaultClasses[ i ] );
3654 }
3655 };
3656
3657 /* Setup */
3658
3659 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3660
3661 /* Static Methods */
3662
3663 /**
3664 * Get a default set of classes to be registered on construction
3665 *
3666 * @return {Function[]} Default classes
3667 */
3668 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3669 return [
3670 OO.ui.BarToolGroup,
3671 OO.ui.ListToolGroup,
3672 OO.ui.MenuToolGroup
3673 ];
3674 };
3675
3676 /**
3677 * Theme logic.
3678 *
3679 * @abstract
3680 * @class
3681 *
3682 * @constructor
3683 * @param {Object} [config] Configuration options
3684 */
3685 OO.ui.Theme = function OoUiTheme( config ) {
3686 // Configuration initialization
3687 config = config || {};
3688 };
3689
3690 /* Setup */
3691
3692 OO.initClass( OO.ui.Theme );
3693
3694 /* Methods */
3695
3696 /**
3697 * Get a list of classes to be applied to a widget.
3698 *
3699 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3700 * otherwise state transitions will not work properly.
3701 *
3702 * @param {OO.ui.Element} element Element for which to get classes
3703 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3704 */
3705 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3706 return { on: [], off: [] };
3707 };
3708
3709 /**
3710 * Update CSS classes provided by the theme.
3711 *
3712 * For elements with theme logic hooks, this should be called any time there's a state change.
3713 *
3714 * @param {OO.ui.Element} element Element for which to update classes
3715 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3716 */
3717 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3718 var classes = this.getElementClasses( element );
3719
3720 element.$element
3721 .removeClass( classes.off.join( ' ' ) )
3722 .addClass( classes.on.join( ' ' ) );
3723 };
3724
3725 /**
3726 * Element supporting "sequential focus navigation" using the 'tabindex' attribute.
3727 *
3728 * @abstract
3729 * @class
3730 *
3731 * @constructor
3732 * @param {Object} [config] Configuration options
3733 * @cfg {jQuery} [$tabIndexed] tabIndexed node, assigned to #$tabIndexed, omit to use #$element
3734 * @cfg {number|Function} [tabIndex=0] Tab index value. Use 0 to use default ordering, use -1 to
3735 * prevent tab focusing. (default: 0)
3736 */
3737 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3738 // Configuration initialization
3739 config = config || {};
3740
3741 // Properties
3742 this.$tabIndexed = null;
3743 this.tabIndex = null;
3744
3745 // Initialization
3746 this.setTabIndex( config.tabIndex || 0 );
3747 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3748 };
3749
3750 /* Setup */
3751
3752 OO.initClass( OO.ui.TabIndexedElement );
3753
3754 /* Methods */
3755
3756 /**
3757 * Set the element with 'tabindex' attribute.
3758 *
3759 * If an element is already set, it will be cleaned up before setting up the new element.
3760 *
3761 * @param {jQuery} $tabIndexed Element to set tab index on
3762 */
3763 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3764 if ( this.$tabIndexed ) {
3765 this.$tabIndexed.removeAttr( 'tabindex' );
3766 }
3767
3768 this.$tabIndexed = $tabIndexed;
3769 if ( this.tabIndex !== null ) {
3770 this.$tabIndexed.attr( 'tabindex', this.tabIndex );
3771 }
3772 };
3773
3774 /**
3775 * Set tab index value.
3776 *
3777 * @param {number|null} tabIndex Tab index value or null for no tabIndex
3778 * @chainable
3779 */
3780 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3781 tabIndex = typeof tabIndex === 'number' && tabIndex >= 0 ? tabIndex : null;
3782
3783 if ( this.tabIndex !== tabIndex ) {
3784 if ( this.$tabIndexed ) {
3785 if ( tabIndex !== null ) {
3786 this.$tabIndexed.attr( 'tabindex', tabIndex );
3787 } else {
3788 this.$tabIndexed.removeAttr( 'tabindex' );
3789 }
3790 }
3791 this.tabIndex = tabIndex;
3792 }
3793
3794 return this;
3795 };
3796
3797 /**
3798 * Get tab index value.
3799 *
3800 * @return {number} Tab index value
3801 */
3802 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3803 return this.tabIndex;
3804 };
3805
3806 /**
3807 * Element with a button.
3808 *
3809 * Buttons are used for controls which can be clicked. They can be configured to use tab indexing
3810 * and access keys for accessibility purposes.
3811 *
3812 * @abstract
3813 * @class
3814 *
3815 * @constructor
3816 * @param {Object} [config] Configuration options
3817 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3818 * @cfg {boolean} [framed=true] Render button with a frame
3819 * @cfg {string} [accessKey] Button's access key
3820 */
3821 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3822 // Configuration initialization
3823 config = config || {};
3824
3825 // Properties
3826 this.$button = config.$button || this.$( '<a>' );
3827 this.framed = null;
3828 this.accessKey = null;
3829 this.active = false;
3830 this.onMouseUpHandler = this.onMouseUp.bind( this );
3831 this.onMouseDownHandler = this.onMouseDown.bind( this );
3832
3833 // Initialization
3834 this.$element.addClass( 'oo-ui-buttonElement' );
3835 this.toggleFramed( config.framed === undefined || config.framed );
3836 this.setAccessKey( config.accessKey );
3837 this.setButtonElement( this.$button );
3838 };
3839
3840 /* Setup */
3841
3842 OO.initClass( OO.ui.ButtonElement );
3843
3844 /* Static Properties */
3845
3846 /**
3847 * Cancel mouse down events.
3848 *
3849 * @static
3850 * @inheritable
3851 * @property {boolean}
3852 */
3853 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
3854
3855 /* Methods */
3856
3857 /**
3858 * Set the button element.
3859 *
3860 * If an element is already set, it will be cleaned up before setting up the new element.
3861 *
3862 * @param {jQuery} $button Element to use as button
3863 */
3864 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
3865 if ( this.$button ) {
3866 this.$button
3867 .removeClass( 'oo-ui-buttonElement-button' )
3868 .removeAttr( 'role accesskey' )
3869 .off( 'mousedown', this.onMouseDownHandler );
3870 }
3871
3872 this.$button = $button
3873 .addClass( 'oo-ui-buttonElement-button' )
3874 .attr( { role: 'button', accesskey: this.accessKey } )
3875 .on( 'mousedown', this.onMouseDownHandler );
3876 };
3877
3878 /**
3879 * Handles mouse down events.
3880 *
3881 * @param {jQuery.Event} e Mouse down event
3882 */
3883 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
3884 if ( this.isDisabled() || e.which !== 1 ) {
3885 return false;
3886 }
3887 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
3888 // Prevent change of focus unless specifically configured otherwise
3889 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3890 return false;
3891 }
3892 };
3893
3894 /**
3895 * Handles mouse up events.
3896 *
3897 * @param {jQuery.Event} e Mouse up event
3898 */
3899 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
3900 if ( this.isDisabled() || e.which !== 1 ) {
3901 return false;
3902 }
3903 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
3904 };
3905
3906 /**
3907 * Check if button has a frame.
3908 *
3909 * @return {boolean} Button is framed
3910 */
3911 OO.ui.ButtonElement.prototype.isFramed = function () {
3912 return this.framed;
3913 };
3914
3915 /**
3916 * Toggle frame.
3917 *
3918 * @param {boolean} [framed] Make button framed, omit to toggle
3919 * @chainable
3920 */
3921 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
3922 framed = framed === undefined ? !this.framed : !!framed;
3923 if ( framed !== this.framed ) {
3924 this.framed = framed;
3925 this.$element
3926 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
3927 .toggleClass( 'oo-ui-buttonElement-framed', framed );
3928 this.updateThemeClasses();
3929 }
3930
3931 return this;
3932 };
3933
3934 /**
3935 * Set access key.
3936 *
3937 * @param {string} accessKey Button's access key, use empty string to remove
3938 * @chainable
3939 */
3940 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
3941 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
3942
3943 if ( this.accessKey !== accessKey ) {
3944 if ( this.$button ) {
3945 if ( accessKey !== null ) {
3946 this.$button.attr( 'accesskey', accessKey );
3947 } else {
3948 this.$button.removeAttr( 'accesskey' );
3949 }
3950 }
3951 this.accessKey = accessKey;
3952 }
3953
3954 return this;
3955 };
3956
3957 /**
3958 * Set active state.
3959 *
3960 * @param {boolean} [value] Make button active
3961 * @chainable
3962 */
3963 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
3964 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
3965 return this;
3966 };
3967
3968 /**
3969 * Element containing a sequence of child elements.
3970 *
3971 * @abstract
3972 * @class
3973 *
3974 * @constructor
3975 * @param {Object} [config] Configuration options
3976 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
3977 */
3978 OO.ui.GroupElement = function OoUiGroupElement( config ) {
3979 // Configuration initialization
3980 config = config || {};
3981
3982 // Properties
3983 this.$group = null;
3984 this.items = [];
3985 this.aggregateItemEvents = {};
3986
3987 // Initialization
3988 this.setGroupElement( config.$group || this.$( '<div>' ) );
3989 };
3990
3991 /* Methods */
3992
3993 /**
3994 * Set the group element.
3995 *
3996 * If an element is already set, items will be moved to the new element.
3997 *
3998 * @param {jQuery} $group Element to use as group
3999 */
4000 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4001 var i, len;
4002
4003 this.$group = $group;
4004 for ( i = 0, len = this.items.length; i < len; i++ ) {
4005 this.$group.append( this.items[ i ].$element );
4006 }
4007 };
4008
4009 /**
4010 * Check if there are no items.
4011 *
4012 * @return {boolean} Group is empty
4013 */
4014 OO.ui.GroupElement.prototype.isEmpty = function () {
4015 return !this.items.length;
4016 };
4017
4018 /**
4019 * Get items.
4020 *
4021 * @return {OO.ui.Element[]} Items
4022 */
4023 OO.ui.GroupElement.prototype.getItems = function () {
4024 return this.items.slice( 0 );
4025 };
4026
4027 /**
4028 * Get an item by its data.
4029 *
4030 * Data is compared by a hash of its value. Only the first item with matching data will be returned.
4031 *
4032 * @param {Object} data Item data to search for
4033 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4034 */
4035 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4036 var i, len, item,
4037 hash = OO.getHash( data );
4038
4039 for ( i = 0, len = this.items.length; i < len; i++ ) {
4040 item = this.items[ i ];
4041 if ( hash === OO.getHash( item.getData() ) ) {
4042 return item;
4043 }
4044 }
4045
4046 return null;
4047 };
4048
4049 /**
4050 * Get items by their data.
4051 *
4052 * Data is compared by a hash of its value. All items with matching data will be returned.
4053 *
4054 * @param {Object} data Item data to search for
4055 * @return {OO.ui.Element[]} Items with equivalent data
4056 */
4057 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4058 var i, len, item,
4059 hash = OO.getHash( data ),
4060 items = [];
4061
4062 for ( i = 0, len = this.items.length; i < len; i++ ) {
4063 item = this.items[ i ];
4064 if ( hash === OO.getHash( item.getData() ) ) {
4065 items.push( item );
4066 }
4067 }
4068
4069 return items;
4070 };
4071
4072 /**
4073 * Add an aggregate item event.
4074 *
4075 * Aggregated events are listened to on each item and then emitted by the group under a new name,
4076 * and with an additional leading parameter containing the item that emitted the original event.
4077 * Other arguments that were emitted from the original event are passed through.
4078 *
4079 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
4080 * event, use null value to remove aggregation
4081 * @throws {Error} If aggregation already exists
4082 */
4083 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4084 var i, len, item, add, remove, itemEvent, groupEvent;
4085
4086 for ( itemEvent in events ) {
4087 groupEvent = events[ itemEvent ];
4088
4089 // Remove existing aggregated event
4090 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4091 // Don't allow duplicate aggregations
4092 if ( groupEvent ) {
4093 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4094 }
4095 // Remove event aggregation from existing items
4096 for ( i = 0, len = this.items.length; i < len; i++ ) {
4097 item = this.items[ i ];
4098 if ( item.connect && item.disconnect ) {
4099 remove = {};
4100 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4101 item.disconnect( this, remove );
4102 }
4103 }
4104 // Prevent future items from aggregating event
4105 delete this.aggregateItemEvents[ itemEvent ];
4106 }
4107
4108 // Add new aggregate event
4109 if ( groupEvent ) {
4110 // Make future items aggregate event
4111 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4112 // Add event aggregation to existing items
4113 for ( i = 0, len = this.items.length; i < len; i++ ) {
4114 item = this.items[ i ];
4115 if ( item.connect && item.disconnect ) {
4116 add = {};
4117 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4118 item.connect( this, add );
4119 }
4120 }
4121 }
4122 }
4123 };
4124
4125 /**
4126 * Add items.
4127 *
4128 * Adding an existing item will move it.
4129 *
4130 * @param {OO.ui.Element[]} items Items
4131 * @param {number} [index] Index to insert items at
4132 * @chainable
4133 */
4134 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4135 var i, len, item, event, events, currentIndex,
4136 itemElements = [];
4137
4138 for ( i = 0, len = items.length; i < len; i++ ) {
4139 item = items[ i ];
4140
4141 // Check if item exists then remove it first, effectively "moving" it
4142 currentIndex = $.inArray( item, this.items );
4143 if ( currentIndex >= 0 ) {
4144 this.removeItems( [ item ] );
4145 // Adjust index to compensate for removal
4146 if ( currentIndex < index ) {
4147 index--;
4148 }
4149 }
4150 // Add the item
4151 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4152 events = {};
4153 for ( event in this.aggregateItemEvents ) {
4154 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4155 }
4156 item.connect( this, events );
4157 }
4158 item.setElementGroup( this );
4159 itemElements.push( item.$element.get( 0 ) );
4160 }
4161
4162 if ( index === undefined || index < 0 || index >= this.items.length ) {
4163 this.$group.append( itemElements );
4164 this.items.push.apply( this.items, items );
4165 } else if ( index === 0 ) {
4166 this.$group.prepend( itemElements );
4167 this.items.unshift.apply( this.items, items );
4168 } else {
4169 this.items[ index ].$element.before( itemElements );
4170 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4171 }
4172
4173 return this;
4174 };
4175
4176 /**
4177 * Remove items.
4178 *
4179 * Items will be detached, not removed, so they can be used later.
4180 *
4181 * @param {OO.ui.Element[]} items Items to remove
4182 * @chainable
4183 */
4184 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4185 var i, len, item, index, remove, itemEvent;
4186
4187 // Remove specific items
4188 for ( i = 0, len = items.length; i < len; i++ ) {
4189 item = items[ i ];
4190 index = $.inArray( item, this.items );
4191 if ( index !== -1 ) {
4192 if (
4193 item.connect && item.disconnect &&
4194 !$.isEmptyObject( this.aggregateItemEvents )
4195 ) {
4196 remove = {};
4197 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4198 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4199 }
4200 item.disconnect( this, remove );
4201 }
4202 item.setElementGroup( null );
4203 this.items.splice( index, 1 );
4204 item.$element.detach();
4205 }
4206 }
4207
4208 return this;
4209 };
4210
4211 /**
4212 * Clear all items.
4213 *
4214 * Items will be detached, not removed, so they can be used later.
4215 *
4216 * @chainable
4217 */
4218 OO.ui.GroupElement.prototype.clearItems = function () {
4219 var i, len, item, remove, itemEvent;
4220
4221 // Remove all items
4222 for ( i = 0, len = this.items.length; i < len; i++ ) {
4223 item = this.items[ i ];
4224 if (
4225 item.connect && item.disconnect &&
4226 !$.isEmptyObject( this.aggregateItemEvents )
4227 ) {
4228 remove = {};
4229 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4230 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4231 }
4232 item.disconnect( this, remove );
4233 }
4234 item.setElementGroup( null );
4235 item.$element.detach();
4236 }
4237
4238 this.items = [];
4239 return this;
4240 };
4241
4242 /**
4243 * A mixin for an element that can be dragged and dropped.
4244 * Use in conjunction with DragGroupWidget
4245 *
4246 * @abstract
4247 * @class
4248 *
4249 * @constructor
4250 */
4251 OO.ui.DraggableElement = function OoUiDraggableElement() {
4252 // Properties
4253 this.index = null;
4254
4255 // Initialize and events
4256 this.$element
4257 .attr( 'draggable', true )
4258 .addClass( 'oo-ui-draggableElement' )
4259 .on( {
4260 dragstart: this.onDragStart.bind( this ),
4261 dragover: this.onDragOver.bind( this ),
4262 dragend: this.onDragEnd.bind( this ),
4263 drop: this.onDrop.bind( this )
4264 } );
4265 };
4266
4267 /* Events */
4268
4269 /**
4270 * @event dragstart
4271 * @param {OO.ui.DraggableElement} item Dragging item
4272 */
4273
4274 /**
4275 * @event dragend
4276 */
4277
4278 /**
4279 * @event drop
4280 */
4281
4282 /* Methods */
4283
4284 /**
4285 * Respond to dragstart event.
4286 * @param {jQuery.Event} event jQuery event
4287 * @fires dragstart
4288 */
4289 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4290 var dataTransfer = e.originalEvent.dataTransfer;
4291 // Define drop effect
4292 dataTransfer.dropEffect = 'none';
4293 dataTransfer.effectAllowed = 'move';
4294 // We must set up a dataTransfer data property or Firefox seems to
4295 // ignore the fact the element is draggable.
4296 try {
4297 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4298 } catch ( err ) {
4299 // The above is only for firefox. No need to set a catch clause
4300 // if it fails, move on.
4301 }
4302 // Add dragging class
4303 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4304 // Emit event
4305 this.emit( 'dragstart', this );
4306 return true;
4307 };
4308
4309 /**
4310 * Respond to dragend event.
4311 * @fires dragend
4312 */
4313 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4314 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4315 this.emit( 'dragend' );
4316 };
4317
4318 /**
4319 * Handle drop event.
4320 * @param {jQuery.Event} event jQuery event
4321 * @fires drop
4322 */
4323 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4324 e.preventDefault();
4325 this.emit( 'drop', e );
4326 };
4327
4328 /**
4329 * In order for drag/drop to work, the dragover event must
4330 * return false and stop propogation.
4331 */
4332 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4333 e.preventDefault();
4334 };
4335
4336 /**
4337 * Set item index.
4338 * Store it in the DOM so we can access from the widget drag event
4339 * @param {number} Item index
4340 */
4341 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4342 if ( this.index !== index ) {
4343 this.index = index;
4344 this.$element.data( 'index', index );
4345 }
4346 };
4347
4348 /**
4349 * Get item index
4350 * @return {number} Item index
4351 */
4352 OO.ui.DraggableElement.prototype.getIndex = function () {
4353 return this.index;
4354 };
4355
4356 /**
4357 * Element containing a sequence of child elements that can be dragged
4358 * and dropped.
4359 *
4360 * @abstract
4361 * @class
4362 *
4363 * @constructor
4364 * @param {Object} [config] Configuration options
4365 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
4366 * @cfg {string} [orientation] Item orientation, 'horizontal' or 'vertical'. Defaults to 'vertical'
4367 */
4368 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4369 // Configuration initialization
4370 config = config || {};
4371
4372 // Parent constructor
4373 OO.ui.GroupElement.call( this, config );
4374
4375 // Properties
4376 this.orientation = config.orientation || 'vertical';
4377 this.dragItem = null;
4378 this.itemDragOver = null;
4379 this.itemKeys = {};
4380 this.sideInsertion = '';
4381
4382 // Events
4383 this.aggregate( {
4384 dragstart: 'itemDragStart',
4385 dragend: 'itemDragEnd',
4386 drop: 'itemDrop'
4387 } );
4388 this.connect( this, {
4389 itemDragStart: 'onItemDragStart',
4390 itemDrop: 'onItemDrop',
4391 itemDragEnd: 'onItemDragEnd'
4392 } );
4393 this.$element.on( {
4394 dragover: $.proxy( this.onDragOver, this ),
4395 dragleave: $.proxy( this.onDragLeave, this )
4396 } );
4397
4398 // Initialize
4399 if ( $.isArray( config.items ) ) {
4400 this.addItems( config.items );
4401 }
4402 this.$placeholder = $( '<div>' )
4403 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4404 this.$element
4405 .addClass( 'oo-ui-draggableGroupElement' )
4406 .append( this.$status )
4407 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4408 .prepend( this.$placeholder );
4409 };
4410
4411 /* Setup */
4412 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4413
4414 /* Events */
4415
4416 /**
4417 * @event reorder
4418 * @param {OO.ui.DraggableElement} item Reordered item
4419 * @param {number} [newIndex] New index for the item
4420 */
4421
4422 /* Methods */
4423
4424 /**
4425 * Respond to item drag start event
4426 * @param {OO.ui.DraggableElement} item Dragged item
4427 */
4428 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4429 var i, len;
4430
4431 // Map the index of each object
4432 for ( i = 0, len = this.items.length; i < len; i++ ) {
4433 this.items[ i ].setIndex( i );
4434 }
4435
4436 if ( this.orientation === 'horizontal' ) {
4437 // Set the height of the indicator
4438 this.$placeholder.css( {
4439 height: item.$element.outerHeight(),
4440 width: 2
4441 } );
4442 } else {
4443 // Set the width of the indicator
4444 this.$placeholder.css( {
4445 height: 2,
4446 width: item.$element.outerWidth()
4447 } );
4448 }
4449 this.setDragItem( item );
4450 };
4451
4452 /**
4453 * Respond to item drag end event
4454 */
4455 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4456 this.unsetDragItem();
4457 return false;
4458 };
4459
4460 /**
4461 * Handle drop event and switch the order of the items accordingly
4462 * @param {OO.ui.DraggableElement} item Dropped item
4463 * @fires reorder
4464 */
4465 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4466 var toIndex = item.getIndex();
4467 // Check if the dropped item is from the current group
4468 // TODO: Figure out a way to configure a list of legally droppable
4469 // elements even if they are not yet in the list
4470 if ( this.getDragItem() ) {
4471 // If the insertion point is 'after', the insertion index
4472 // is shifted to the right (or to the left in RTL, hence 'after')
4473 if ( this.sideInsertion === 'after' ) {
4474 toIndex++;
4475 }
4476 // Emit change event
4477 this.emit( 'reorder', this.getDragItem(), toIndex );
4478 }
4479 // Return false to prevent propogation
4480 return false;
4481 };
4482
4483 /**
4484 * Handle dragleave event.
4485 */
4486 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4487 // This means the item was dragged outside the widget
4488 this.$placeholder
4489 .css( 'left', 0 )
4490 .hide();
4491 };
4492
4493 /**
4494 * Respond to dragover event
4495 * @param {jQuery.Event} event Event details
4496 */
4497 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4498 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4499 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4500 clientX = e.originalEvent.clientX,
4501 clientY = e.originalEvent.clientY;
4502
4503 // Get the OptionWidget item we are dragging over
4504 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4505 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4506 if ( $optionWidget[ 0 ] ) {
4507 itemOffset = $optionWidget.offset();
4508 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4509 itemPosition = $optionWidget.position();
4510 itemIndex = $optionWidget.data( 'index' );
4511 }
4512
4513 if (
4514 itemOffset &&
4515 this.isDragging() &&
4516 itemIndex !== this.getDragItem().getIndex()
4517 ) {
4518 if ( this.orientation === 'horizontal' ) {
4519 // Calculate where the mouse is relative to the item width
4520 itemSize = itemBoundingRect.width;
4521 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4522 dragPosition = clientX;
4523 // Which side of the item we hover over will dictate
4524 // where the placeholder will appear, on the left or
4525 // on the right
4526 cssOutput = {
4527 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4528 top: itemPosition.top
4529 };
4530 } else {
4531 // Calculate where the mouse is relative to the item height
4532 itemSize = itemBoundingRect.height;
4533 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4534 dragPosition = clientY;
4535 // Which side of the item we hover over will dictate
4536 // where the placeholder will appear, on the top or
4537 // on the bottom
4538 cssOutput = {
4539 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4540 left: itemPosition.left
4541 };
4542 }
4543 // Store whether we are before or after an item to rearrange
4544 // For horizontal layout, we need to account for RTL, as this is flipped
4545 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4546 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4547 } else {
4548 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4549 }
4550 // Add drop indicator between objects
4551 if ( this.sideInsertion ) {
4552 this.$placeholder
4553 .css( cssOutput )
4554 .show();
4555 } else {
4556 this.$placeholder
4557 .css( {
4558 left: 0,
4559 top: 0
4560 } )
4561 .hide();
4562 }
4563 } else {
4564 // This means the item was dragged outside the widget
4565 this.$placeholder
4566 .css( 'left', 0 )
4567 .hide();
4568 }
4569 // Prevent default
4570 e.preventDefault();
4571 };
4572
4573 /**
4574 * Set a dragged item
4575 * @param {OO.ui.DraggableElement} item Dragged item
4576 */
4577 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4578 this.dragItem = item;
4579 };
4580
4581 /**
4582 * Unset the current dragged item
4583 */
4584 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4585 this.dragItem = null;
4586 this.itemDragOver = null;
4587 this.$placeholder.hide();
4588 this.sideInsertion = '';
4589 };
4590
4591 /**
4592 * Get the current dragged item
4593 * @return {OO.ui.DraggableElement|null} item Dragged item or null if no item is dragged
4594 */
4595 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4596 return this.dragItem;
4597 };
4598
4599 /**
4600 * Check if there's an item being dragged.
4601 * @return {Boolean} Item is being dragged
4602 */
4603 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4604 return this.getDragItem() !== null;
4605 };
4606
4607 /**
4608 * Element containing an icon.
4609 *
4610 * Icons are graphics, about the size of normal text. They can be used to aid the user in locating
4611 * a control or convey information in a more space efficient way. Icons should rarely be used
4612 * without labels; such as in a toolbar where space is at a premium or within a context where the
4613 * meaning is very clear to the user.
4614 *
4615 * @abstract
4616 * @class
4617 *
4618 * @constructor
4619 * @param {Object} [config] Configuration options
4620 * @cfg {jQuery} [$icon] Icon node, assigned to #$icon, omit to use a generated `<span>`
4621 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
4622 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4623 * language
4624 * @cfg {string} [iconTitle] Icon title text or a function that returns text
4625 */
4626 OO.ui.IconElement = function OoUiIconElement( config ) {
4627 // Configuration initialization
4628 config = config || {};
4629
4630 // Properties
4631 this.$icon = null;
4632 this.icon = null;
4633 this.iconTitle = null;
4634
4635 // Initialization
4636 this.setIcon( config.icon || this.constructor.static.icon );
4637 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4638 this.setIconElement( config.$icon || this.$( '<span>' ) );
4639 };
4640
4641 /* Setup */
4642
4643 OO.initClass( OO.ui.IconElement );
4644
4645 /* Static Properties */
4646
4647 /**
4648 * Icon.
4649 *
4650 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
4651 *
4652 * For i18n purposes, this property can be an object containing a `default` icon name property and
4653 * additional icon names keyed by language code.
4654 *
4655 * Example of i18n icon definition:
4656 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4657 *
4658 * @static
4659 * @inheritable
4660 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
4661 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4662 * language
4663 */
4664 OO.ui.IconElement.static.icon = null;
4665
4666 /**
4667 * Icon title.
4668 *
4669 * @static
4670 * @inheritable
4671 * @property {string|Function|null} Icon title text, a function that returns text or null for no
4672 * icon title
4673 */
4674 OO.ui.IconElement.static.iconTitle = null;
4675
4676 /* Methods */
4677
4678 /**
4679 * Set the icon element.
4680 *
4681 * If an element is already set, it will be cleaned up before setting up the new element.
4682 *
4683 * @param {jQuery} $icon Element to use as icon
4684 */
4685 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
4686 if ( this.$icon ) {
4687 this.$icon
4688 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
4689 .removeAttr( 'title' );
4690 }
4691
4692 this.$icon = $icon
4693 .addClass( 'oo-ui-iconElement-icon' )
4694 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
4695 if ( this.iconTitle !== null ) {
4696 this.$icon.attr( 'title', this.iconTitle );
4697 }
4698 };
4699
4700 /**
4701 * Set icon name.
4702 *
4703 * @param {Object|string|null} icon Symbolic icon name, or map of icon names keyed by language ID;
4704 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4705 * language, use null to remove icon
4706 * @chainable
4707 */
4708 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
4709 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
4710 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
4711
4712 if ( this.icon !== icon ) {
4713 if ( this.$icon ) {
4714 if ( this.icon !== null ) {
4715 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
4716 }
4717 if ( icon !== null ) {
4718 this.$icon.addClass( 'oo-ui-icon-' + icon );
4719 }
4720 }
4721 this.icon = icon;
4722 }
4723
4724 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
4725 this.updateThemeClasses();
4726
4727 return this;
4728 };
4729
4730 /**
4731 * Set icon title.
4732 *
4733 * @param {string|Function|null} icon Icon title text, a function that returns text or null
4734 * for no icon title
4735 * @chainable
4736 */
4737 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
4738 iconTitle = typeof iconTitle === 'function' ||
4739 ( typeof iconTitle === 'string' && iconTitle.length ) ?
4740 OO.ui.resolveMsg( iconTitle ) : null;
4741
4742 if ( this.iconTitle !== iconTitle ) {
4743 this.iconTitle = iconTitle;
4744 if ( this.$icon ) {
4745 if ( this.iconTitle !== null ) {
4746 this.$icon.attr( 'title', iconTitle );
4747 } else {
4748 this.$icon.removeAttr( 'title' );
4749 }
4750 }
4751 }
4752
4753 return this;
4754 };
4755
4756 /**
4757 * Get icon name.
4758 *
4759 * @return {string} Icon name
4760 */
4761 OO.ui.IconElement.prototype.getIcon = function () {
4762 return this.icon;
4763 };
4764
4765 /**
4766 * Get icon title.
4767 *
4768 * @return {string} Icon title text
4769 */
4770 OO.ui.IconElement.prototype.getIconTitle = function () {
4771 return this.iconTitle;
4772 };
4773
4774 /**
4775 * Element containing an indicator.
4776 *
4777 * Indicators are graphics, smaller than normal text. They can be used to describe unique status or
4778 * behavior. Indicators should only be used in exceptional cases; such as a button that opens a menu
4779 * instead of performing an action directly, or an item in a list which has errors that need to be
4780 * resolved.
4781 *
4782 * @abstract
4783 * @class
4784 *
4785 * @constructor
4786 * @param {Object} [config] Configuration options
4787 * @cfg {jQuery} [$indicator] Indicator node, assigned to #$indicator, omit to use a generated
4788 * `<span>`
4789 * @cfg {string} [indicator] Symbolic indicator name
4790 * @cfg {string} [indicatorTitle] Indicator title text or a function that returns text
4791 */
4792 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
4793 // Configuration initialization
4794 config = config || {};
4795
4796 // Properties
4797 this.$indicator = null;
4798 this.indicator = null;
4799 this.indicatorTitle = null;
4800
4801 // Initialization
4802 this.setIndicator( config.indicator || this.constructor.static.indicator );
4803 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4804 this.setIndicatorElement( config.$indicator || this.$( '<span>' ) );
4805 };
4806
4807 /* Setup */
4808
4809 OO.initClass( OO.ui.IndicatorElement );
4810
4811 /* Static Properties */
4812
4813 /**
4814 * indicator.
4815 *
4816 * @static
4817 * @inheritable
4818 * @property {string|null} Symbolic indicator name
4819 */
4820 OO.ui.IndicatorElement.static.indicator = null;
4821
4822 /**
4823 * Indicator title.
4824 *
4825 * @static
4826 * @inheritable
4827 * @property {string|Function|null} Indicator title text, a function that returns text or null for no
4828 * indicator title
4829 */
4830 OO.ui.IndicatorElement.static.indicatorTitle = null;
4831
4832 /* Methods */
4833
4834 /**
4835 * Set the indicator element.
4836 *
4837 * If an element is already set, it will be cleaned up before setting up the new element.
4838 *
4839 * @param {jQuery} $indicator Element to use as indicator
4840 */
4841 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
4842 if ( this.$indicator ) {
4843 this.$indicator
4844 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
4845 .removeAttr( 'title' );
4846 }
4847
4848 this.$indicator = $indicator
4849 .addClass( 'oo-ui-indicatorElement-indicator' )
4850 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
4851 if ( this.indicatorTitle !== null ) {
4852 this.$indicator.attr( 'title', this.indicatorTitle );
4853 }
4854 };
4855
4856 /**
4857 * Set indicator name.
4858 *
4859 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4860 * @chainable
4861 */
4862 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
4863 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
4864
4865 if ( this.indicator !== indicator ) {
4866 if ( this.$indicator ) {
4867 if ( this.indicator !== null ) {
4868 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4869 }
4870 if ( indicator !== null ) {
4871 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4872 }
4873 }
4874 this.indicator = indicator;
4875 }
4876
4877 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
4878 this.updateThemeClasses();
4879
4880 return this;
4881 };
4882
4883 /**
4884 * Set indicator title.
4885 *
4886 * @param {string|Function|null} indicator Indicator title text, a function that returns text or
4887 * null for no indicator title
4888 * @chainable
4889 */
4890 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4891 indicatorTitle = typeof indicatorTitle === 'function' ||
4892 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
4893 OO.ui.resolveMsg( indicatorTitle ) : null;
4894
4895 if ( this.indicatorTitle !== indicatorTitle ) {
4896 this.indicatorTitle = indicatorTitle;
4897 if ( this.$indicator ) {
4898 if ( this.indicatorTitle !== null ) {
4899 this.$indicator.attr( 'title', indicatorTitle );
4900 } else {
4901 this.$indicator.removeAttr( 'title' );
4902 }
4903 }
4904 }
4905
4906 return this;
4907 };
4908
4909 /**
4910 * Get indicator name.
4911 *
4912 * @return {string} Symbolic name of indicator
4913 */
4914 OO.ui.IndicatorElement.prototype.getIndicator = function () {
4915 return this.indicator;
4916 };
4917
4918 /**
4919 * Get indicator title.
4920 *
4921 * @return {string} Indicator title text
4922 */
4923 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
4924 return this.indicatorTitle;
4925 };
4926
4927 /**
4928 * Element containing a label.
4929 *
4930 * @abstract
4931 * @class
4932 *
4933 * @constructor
4934 * @param {Object} [config] Configuration options
4935 * @cfg {jQuery} [$label] Label node, assigned to #$label, omit to use a generated `<span>`
4936 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
4937 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
4938 */
4939 OO.ui.LabelElement = function OoUiLabelElement( config ) {
4940 // Configuration initialization
4941 config = config || {};
4942
4943 // Properties
4944 this.$label = null;
4945 this.label = null;
4946 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
4947
4948 // Initialization
4949 this.setLabel( config.label || this.constructor.static.label );
4950 this.setLabelElement( config.$label || this.$( '<span>' ) );
4951 };
4952
4953 /* Setup */
4954
4955 OO.initClass( OO.ui.LabelElement );
4956
4957 /* Events */
4958
4959 /**
4960 * @event labelChange
4961 * @param {string} value
4962 */
4963
4964 /* Static Properties */
4965
4966 /**
4967 * Label.
4968 *
4969 * @static
4970 * @inheritable
4971 * @property {string|Function|null} Label text; a function that returns nodes or text; or null for
4972 * no label
4973 */
4974 OO.ui.LabelElement.static.label = null;
4975
4976 /* Methods */
4977
4978 /**
4979 * Set the label element.
4980 *
4981 * If an element is already set, it will be cleaned up before setting up the new element.
4982 *
4983 * @param {jQuery} $label Element to use as label
4984 */
4985 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
4986 if ( this.$label ) {
4987 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
4988 }
4989
4990 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
4991 this.setLabelContent( this.label );
4992 };
4993
4994 /**
4995 * Set the label.
4996 *
4997 * An empty string will result in the label being hidden. A string containing only whitespace will
4998 * be converted to a single `&nbsp;`.
4999 *
5000 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5001 * text; or null for no label
5002 * @chainable
5003 */
5004 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5005 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5006 label = ( typeof label === 'string' && label.length ) || label instanceof jQuery ? label : null;
5007
5008 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5009
5010 if ( this.label !== label ) {
5011 if ( this.$label ) {
5012 this.setLabelContent( label );
5013 }
5014 this.label = label;
5015 this.emit( 'labelChange' );
5016 }
5017
5018 return this;
5019 };
5020
5021 /**
5022 * Get the label.
5023 *
5024 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5025 * text; or null for no label
5026 */
5027 OO.ui.LabelElement.prototype.getLabel = function () {
5028 return this.label;
5029 };
5030
5031 /**
5032 * Fit the label.
5033 *
5034 * @chainable
5035 */
5036 OO.ui.LabelElement.prototype.fitLabel = function () {
5037 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5038 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5039 }
5040
5041 return this;
5042 };
5043
5044 /**
5045 * Set the content of the label.
5046 *
5047 * Do not call this method until after the label element has been set by #setLabelElement.
5048 *
5049 * @private
5050 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5051 * text; or null for no label
5052 */
5053 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5054 if ( typeof label === 'string' ) {
5055 if ( label.match( /^\s*$/ ) ) {
5056 // Convert whitespace only string to a single non-breaking space
5057 this.$label.html( '&nbsp;' );
5058 } else {
5059 this.$label.text( label );
5060 }
5061 } else if ( label instanceof jQuery ) {
5062 this.$label.empty().append( label );
5063 } else {
5064 this.$label.empty();
5065 }
5066 };
5067
5068 /**
5069 * Mixin that adds a menu showing suggested values for a OO.ui.TextInputWidget.
5070 *
5071 * Subclasses that set the value of #lookupInput from #onLookupMenuItemChoose should
5072 * be aware that this will cause new suggestions to be looked up for the new value. If this is
5073 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
5074 *
5075 * @class
5076 * @abstract
5077 *
5078 * @constructor
5079 * @param {Object} [config] Configuration options
5080 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
5081 * @cfg {jQuery} [$container=this.$element] Element to render menu under
5082 */
5083 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5084 // Configuration initialization
5085 config = config || {};
5086
5087 // Properties
5088 this.$overlay = config.$overlay || this.$element;
5089 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5090 $: OO.ui.Element.static.getJQuery( this.$overlay ),
5091 $container: config.$container
5092 } );
5093 this.lookupCache = {};
5094 this.lookupQuery = null;
5095 this.lookupRequest = null;
5096 this.lookupsDisabled = false;
5097 this.lookupInputFocused = false;
5098
5099 // Events
5100 this.$input.on( {
5101 focus: this.onLookupInputFocus.bind( this ),
5102 blur: this.onLookupInputBlur.bind( this ),
5103 mousedown: this.onLookupInputMouseDown.bind( this )
5104 } );
5105 this.connect( this, { change: 'onLookupInputChange' } );
5106 this.lookupMenu.connect( this, {
5107 toggle: 'onLookupMenuToggle',
5108 choose: 'onLookupMenuItemChoose'
5109 } );
5110
5111 // Initialization
5112 this.$element.addClass( 'oo-ui-lookupElement' );
5113 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5114 this.$overlay.append( this.lookupMenu.$element );
5115 };
5116
5117 /* Methods */
5118
5119 /**
5120 * Handle input focus event.
5121 *
5122 * @param {jQuery.Event} e Input focus event
5123 */
5124 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5125 this.lookupInputFocused = true;
5126 this.populateLookupMenu();
5127 };
5128
5129 /**
5130 * Handle input blur event.
5131 *
5132 * @param {jQuery.Event} e Input blur event
5133 */
5134 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5135 this.closeLookupMenu();
5136 this.lookupInputFocused = false;
5137 };
5138
5139 /**
5140 * Handle input mouse down event.
5141 *
5142 * @param {jQuery.Event} e Input mouse down event
5143 */
5144 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5145 // Only open the menu if the input was already focused.
5146 // This way we allow the user to open the menu again after closing it with Esc
5147 // by clicking in the input. Opening (and populating) the menu when initially
5148 // clicking into the input is handled by the focus handler.
5149 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5150 this.populateLookupMenu();
5151 }
5152 };
5153
5154 /**
5155 * Handle input change event.
5156 *
5157 * @param {string} value New input value
5158 */
5159 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5160 if ( this.lookupInputFocused ) {
5161 this.populateLookupMenu();
5162 }
5163 };
5164
5165 /**
5166 * Handle the lookup menu being shown/hidden.
5167 *
5168 * @param {boolean} visible Whether the lookup menu is now visible.
5169 */
5170 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5171 if ( !visible ) {
5172 // When the menu is hidden, abort any active request and clear the menu.
5173 // This has to be done here in addition to closeLookupMenu(), because
5174 // MenuSelectWidget will close itself when the user presses Esc.
5175 this.abortLookupRequest();
5176 this.lookupMenu.clearItems();
5177 }
5178 };
5179
5180 /**
5181 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5182 *
5183 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5184 */
5185 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5186 if ( item ) {
5187 this.setValue( item.getData() );
5188 }
5189 };
5190
5191 /**
5192 * Get lookup menu.
5193 *
5194 * @return {OO.ui.TextInputMenuSelectWidget}
5195 */
5196 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5197 return this.lookupMenu;
5198 };
5199
5200 /**
5201 * Disable or re-enable lookups.
5202 *
5203 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5204 *
5205 * @param {boolean} disabled Disable lookups
5206 */
5207 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5208 this.lookupsDisabled = !!disabled;
5209 };
5210
5211 /**
5212 * Open the menu. If there are no entries in the menu, this does nothing.
5213 *
5214 * @chainable
5215 */
5216 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5217 if ( !this.lookupMenu.isEmpty() ) {
5218 this.lookupMenu.toggle( true );
5219 }
5220 return this;
5221 };
5222
5223 /**
5224 * Close the menu, empty it, and abort any pending request.
5225 *
5226 * @chainable
5227 */
5228 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5229 this.lookupMenu.toggle( false );
5230 this.abortLookupRequest();
5231 this.lookupMenu.clearItems();
5232 return this;
5233 };
5234
5235 /**
5236 * Request menu items based on the input's current value, and when they arrive,
5237 * populate the menu with these items and show the menu.
5238 *
5239 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5240 *
5241 * @chainable
5242 */
5243 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5244 var widget = this,
5245 value = this.getValue();
5246
5247 if ( this.lookupsDisabled ) {
5248 return;
5249 }
5250
5251 // If the input is empty, clear the menu
5252 if ( value === '' ) {
5253 this.closeLookupMenu();
5254 // Skip population if there is already a request pending for the current value
5255 } else if ( value !== this.lookupQuery ) {
5256 this.getLookupMenuItems()
5257 .done( function ( items ) {
5258 widget.lookupMenu.clearItems();
5259 if ( items.length ) {
5260 widget.lookupMenu
5261 .addItems( items )
5262 .toggle( true );
5263 widget.initializeLookupMenuSelection();
5264 } else {
5265 widget.lookupMenu.toggle( false );
5266 }
5267 } )
5268 .fail( function () {
5269 widget.lookupMenu.clearItems();
5270 } );
5271 }
5272
5273 return this;
5274 };
5275
5276 /**
5277 * Select and highlight the first selectable item in the menu.
5278 *
5279 * @chainable
5280 */
5281 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5282 if ( !this.lookupMenu.getSelectedItem() ) {
5283 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5284 }
5285 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5286 };
5287
5288 /**
5289 * Get lookup menu items for the current query.
5290 *
5291 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5292 * the done event. If the request was aborted to make way for a subsequent request, this promise
5293 * will not be rejected: it will remain pending forever.
5294 */
5295 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5296 var widget = this,
5297 value = this.getValue(),
5298 deferred = $.Deferred(),
5299 ourRequest;
5300
5301 this.abortLookupRequest();
5302 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5303 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5304 } else {
5305 this.pushPending();
5306 this.lookupQuery = value;
5307 ourRequest = this.lookupRequest = this.getLookupRequest();
5308 ourRequest
5309 .always( function () {
5310 // We need to pop pending even if this is an old request, otherwise
5311 // the widget will remain pending forever.
5312 // TODO: this assumes that an aborted request will fail or succeed soon after
5313 // being aborted, or at least eventually. It would be nice if we could popPending()
5314 // at abort time, but only if we knew that we hadn't already called popPending()
5315 // for that request.
5316 widget.popPending();
5317 } )
5318 .done( function ( data ) {
5319 // If this is an old request (and aborting it somehow caused it to still succeed),
5320 // ignore its success completely
5321 if ( ourRequest === widget.lookupRequest ) {
5322 widget.lookupQuery = null;
5323 widget.lookupRequest = null;
5324 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( data );
5325 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5326 }
5327 } )
5328 .fail( function () {
5329 // If this is an old request (or a request failing because it's being aborted),
5330 // ignore its failure completely
5331 if ( ourRequest === widget.lookupRequest ) {
5332 widget.lookupQuery = null;
5333 widget.lookupRequest = null;
5334 deferred.reject();
5335 }
5336 } );
5337 }
5338 return deferred.promise();
5339 };
5340
5341 /**
5342 * Abort the currently pending lookup request, if any.
5343 */
5344 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5345 var oldRequest = this.lookupRequest;
5346 if ( oldRequest ) {
5347 // First unset this.lookupRequest to the fail handler will notice
5348 // that the request is no longer current
5349 this.lookupRequest = null;
5350 this.lookupQuery = null;
5351 oldRequest.abort();
5352 }
5353 };
5354
5355 /**
5356 * Get a new request object of the current lookup query value.
5357 *
5358 * @abstract
5359 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5360 */
5361 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5362 // Stub, implemented in subclass
5363 return null;
5364 };
5365
5366 /**
5367 * Pre-process data returned by the request from #getLookupRequest.
5368 *
5369 * The return value of this function will be cached, and any further queries for the given value
5370 * will use the cache rather than doing API requests.
5371 *
5372 * @abstract
5373 * @param {Mixed} data Response from server
5374 * @return {Mixed} Cached result data
5375 */
5376 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5377 // Stub, implemented in subclass
5378 return [];
5379 };
5380
5381 /**
5382 * Get a list of menu option widgets from the (possibly cached) data returned by
5383 * #getLookupCacheDataFromResponse.
5384 *
5385 * @abstract
5386 * @param {Mixed} data Cached result data, usually an array
5387 * @return {OO.ui.MenuOptionWidget[]} Menu items
5388 */
5389 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5390 // Stub, implemented in subclass
5391 return [];
5392 };
5393
5394 /**
5395 * Element containing an OO.ui.PopupWidget object.
5396 *
5397 * @abstract
5398 * @class
5399 *
5400 * @constructor
5401 * @param {Object} [config] Configuration options
5402 * @cfg {Object} [popup] Configuration to pass to popup
5403 * @cfg {boolean} [autoClose=true] Popup auto-closes when it loses focus
5404 */
5405 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5406 // Configuration initialization
5407 config = config || {};
5408
5409 // Properties
5410 this.popup = new OO.ui.PopupWidget( $.extend(
5411 { autoClose: true },
5412 config.popup,
5413 { $: this.$, $autoCloseIgnore: this.$element }
5414 ) );
5415 };
5416
5417 /* Methods */
5418
5419 /**
5420 * Get popup.
5421 *
5422 * @return {OO.ui.PopupWidget} Popup widget
5423 */
5424 OO.ui.PopupElement.prototype.getPopup = function () {
5425 return this.popup;
5426 };
5427
5428 /**
5429 * Element with named flags that can be added, removed, listed and checked.
5430 *
5431 * A flag, when set, adds a CSS class on the `$element` by combining `oo-ui-flaggedElement-` with
5432 * the flag name. Flags are primarily useful for styling.
5433 *
5434 * @abstract
5435 * @class
5436 *
5437 * @constructor
5438 * @param {Object} [config] Configuration options
5439 * @cfg {string|string[]} [flags] Flags describing importance and functionality, e.g. 'primary',
5440 * 'safe', 'progressive', 'destructive' or 'constructive'
5441 * @cfg {jQuery} [$flagged] Flagged node, assigned to #$flagged, omit to use #$element
5442 */
5443 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5444 // Configuration initialization
5445 config = config || {};
5446
5447 // Properties
5448 this.flags = {};
5449 this.$flagged = null;
5450
5451 // Initialization
5452 this.setFlags( config.flags );
5453 this.setFlaggedElement( config.$flagged || this.$element );
5454 };
5455
5456 /* Events */
5457
5458 /**
5459 * @event flag
5460 * @param {Object.<string,boolean>} changes Object keyed by flag name containing boolean
5461 * added/removed properties
5462 */
5463
5464 /* Methods */
5465
5466 /**
5467 * Set the flagged element.
5468 *
5469 * If an element is already set, it will be cleaned up before setting up the new element.
5470 *
5471 * @param {jQuery} $flagged Element to add flags to
5472 */
5473 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5474 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5475 return 'oo-ui-flaggedElement-' + flag;
5476 } ).join( ' ' );
5477
5478 if ( this.$flagged ) {
5479 this.$flagged.removeClass( classNames );
5480 }
5481
5482 this.$flagged = $flagged.addClass( classNames );
5483 };
5484
5485 /**
5486 * Check if a flag is set.
5487 *
5488 * @param {string} flag Name of flag
5489 * @return {boolean} Has flag
5490 */
5491 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5492 return flag in this.flags;
5493 };
5494
5495 /**
5496 * Get the names of all flags set.
5497 *
5498 * @return {string[]} Flag names
5499 */
5500 OO.ui.FlaggedElement.prototype.getFlags = function () {
5501 return Object.keys( this.flags );
5502 };
5503
5504 /**
5505 * Clear all flags.
5506 *
5507 * @chainable
5508 * @fires flag
5509 */
5510 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5511 var flag, className,
5512 changes = {},
5513 remove = [],
5514 classPrefix = 'oo-ui-flaggedElement-';
5515
5516 for ( flag in this.flags ) {
5517 className = classPrefix + flag;
5518 changes[ flag ] = false;
5519 delete this.flags[ flag ];
5520 remove.push( className );
5521 }
5522
5523 if ( this.$flagged ) {
5524 this.$flagged.removeClass( remove.join( ' ' ) );
5525 }
5526
5527 this.updateThemeClasses();
5528 this.emit( 'flag', changes );
5529
5530 return this;
5531 };
5532
5533 /**
5534 * Add one or more flags.
5535 *
5536 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
5537 * keyed by flag name containing boolean set/remove instructions.
5538 * @chainable
5539 * @fires flag
5540 */
5541 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5542 var i, len, flag, className,
5543 changes = {},
5544 add = [],
5545 remove = [],
5546 classPrefix = 'oo-ui-flaggedElement-';
5547
5548 if ( typeof flags === 'string' ) {
5549 className = classPrefix + flags;
5550 // Set
5551 if ( !this.flags[ flags ] ) {
5552 this.flags[ flags ] = true;
5553 add.push( className );
5554 }
5555 } else if ( $.isArray( flags ) ) {
5556 for ( i = 0, len = flags.length; i < len; i++ ) {
5557 flag = flags[ i ];
5558 className = classPrefix + flag;
5559 // Set
5560 if ( !this.flags[ flag ] ) {
5561 changes[ flag ] = true;
5562 this.flags[ flag ] = true;
5563 add.push( className );
5564 }
5565 }
5566 } else if ( OO.isPlainObject( flags ) ) {
5567 for ( flag in flags ) {
5568 className = classPrefix + flag;
5569 if ( flags[ flag ] ) {
5570 // Set
5571 if ( !this.flags[ flag ] ) {
5572 changes[ flag ] = true;
5573 this.flags[ flag ] = true;
5574 add.push( className );
5575 }
5576 } else {
5577 // Remove
5578 if ( this.flags[ flag ] ) {
5579 changes[ flag ] = false;
5580 delete this.flags[ flag ];
5581 remove.push( className );
5582 }
5583 }
5584 }
5585 }
5586
5587 if ( this.$flagged ) {
5588 this.$flagged
5589 .addClass( add.join( ' ' ) )
5590 .removeClass( remove.join( ' ' ) );
5591 }
5592
5593 this.updateThemeClasses();
5594 this.emit( 'flag', changes );
5595
5596 return this;
5597 };
5598
5599 /**
5600 * Element with a title.
5601 *
5602 * Titles are rendered by the browser and are made visible when hovering the element. Titles are
5603 * not visible on touch devices.
5604 *
5605 * @abstract
5606 * @class
5607 *
5608 * @constructor
5609 * @param {Object} [config] Configuration options
5610 * @cfg {jQuery} [$titled] Titled node, assigned to #$titled, omit to use #$element
5611 * @cfg {string|Function} [title] Title text or a function that returns text. If not provided, the
5612 * static property 'title' is used.
5613 */
5614 OO.ui.TitledElement = function OoUiTitledElement( config ) {
5615 // Configuration initialization
5616 config = config || {};
5617
5618 // Properties
5619 this.$titled = null;
5620 this.title = null;
5621
5622 // Initialization
5623 this.setTitle( config.title || this.constructor.static.title );
5624 this.setTitledElement( config.$titled || this.$element );
5625 };
5626
5627 /* Setup */
5628
5629 OO.initClass( OO.ui.TitledElement );
5630
5631 /* Static Properties */
5632
5633 /**
5634 * Title.
5635 *
5636 * @static
5637 * @inheritable
5638 * @property {string|Function} Title text or a function that returns text
5639 */
5640 OO.ui.TitledElement.static.title = null;
5641
5642 /* Methods */
5643
5644 /**
5645 * Set the titled element.
5646 *
5647 * If an element is already set, it will be cleaned up before setting up the new element.
5648 *
5649 * @param {jQuery} $titled Element to set title on
5650 */
5651 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
5652 if ( this.$titled ) {
5653 this.$titled.removeAttr( 'title' );
5654 }
5655
5656 this.$titled = $titled;
5657 if ( this.title ) {
5658 this.$titled.attr( 'title', this.title );
5659 }
5660 };
5661
5662 /**
5663 * Set title.
5664 *
5665 * @param {string|Function|null} title Title text, a function that returns text or null for no title
5666 * @chainable
5667 */
5668 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
5669 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
5670
5671 if ( this.title !== title ) {
5672 if ( this.$titled ) {
5673 if ( title !== null ) {
5674 this.$titled.attr( 'title', title );
5675 } else {
5676 this.$titled.removeAttr( 'title' );
5677 }
5678 }
5679 this.title = title;
5680 }
5681
5682 return this;
5683 };
5684
5685 /**
5686 * Get title.
5687 *
5688 * @return {string} Title string
5689 */
5690 OO.ui.TitledElement.prototype.getTitle = function () {
5691 return this.title;
5692 };
5693
5694 /**
5695 * Element that can be automatically clipped to visible boundaries.
5696 *
5697 * Whenever the element's natural height changes, you have to call
5698 * #clip to make sure it's still clipping correctly.
5699 *
5700 * @abstract
5701 * @class
5702 *
5703 * @constructor
5704 * @param {Object} [config] Configuration options
5705 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
5706 */
5707 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
5708 // Configuration initialization
5709 config = config || {};
5710
5711 // Properties
5712 this.$clippable = null;
5713 this.clipping = false;
5714 this.clippedHorizontally = false;
5715 this.clippedVertically = false;
5716 this.$clippableContainer = null;
5717 this.$clippableScroller = null;
5718 this.$clippableWindow = null;
5719 this.idealWidth = null;
5720 this.idealHeight = null;
5721 this.onClippableContainerScrollHandler = this.clip.bind( this );
5722 this.onClippableWindowResizeHandler = this.clip.bind( this );
5723
5724 // Initialization
5725 this.setClippableElement( config.$clippable || this.$element );
5726 };
5727
5728 /* Methods */
5729
5730 /**
5731 * Set clippable element.
5732 *
5733 * If an element is already set, it will be cleaned up before setting up the new element.
5734 *
5735 * @param {jQuery} $clippable Element to make clippable
5736 */
5737 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
5738 if ( this.$clippable ) {
5739 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
5740 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
5741 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5742 }
5743
5744 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
5745 this.clip();
5746 };
5747
5748 /**
5749 * Toggle clipping.
5750 *
5751 * Do not turn clipping on until after the element is attached to the DOM and visible.
5752 *
5753 * @param {boolean} [clipping] Enable clipping, omit to toggle
5754 * @chainable
5755 */
5756 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
5757 clipping = clipping === undefined ? !this.clipping : !!clipping;
5758
5759 if ( this.clipping !== clipping ) {
5760 this.clipping = clipping;
5761 if ( clipping ) {
5762 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
5763 // If the clippable container is the root, we have to listen to scroll events and check
5764 // jQuery.scrollTop on the window because of browser inconsistencies
5765 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
5766 this.$( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
5767 this.$clippableContainer;
5768 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
5769 this.$clippableWindow = this.$( this.getElementWindow() )
5770 .on( 'resize', this.onClippableWindowResizeHandler );
5771 // Initial clip after visible
5772 this.clip();
5773 } else {
5774 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
5775 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5776
5777 this.$clippableContainer = null;
5778 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
5779 this.$clippableScroller = null;
5780 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
5781 this.$clippableWindow = null;
5782 }
5783 }
5784
5785 return this;
5786 };
5787
5788 /**
5789 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
5790 *
5791 * @return {boolean} Element will be clipped to the visible area
5792 */
5793 OO.ui.ClippableElement.prototype.isClipping = function () {
5794 return this.clipping;
5795 };
5796
5797 /**
5798 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
5799 *
5800 * @return {boolean} Part of the element is being clipped
5801 */
5802 OO.ui.ClippableElement.prototype.isClipped = function () {
5803 return this.clippedHorizontally || this.clippedVertically;
5804 };
5805
5806 /**
5807 * Check if the right of the element is being clipped by the nearest scrollable container.
5808 *
5809 * @return {boolean} Part of the element is being clipped
5810 */
5811 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
5812 return this.clippedHorizontally;
5813 };
5814
5815 /**
5816 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5817 *
5818 * @return {boolean} Part of the element is being clipped
5819 */
5820 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
5821 return this.clippedVertically;
5822 };
5823
5824 /**
5825 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
5826 *
5827 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5828 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5829 */
5830 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
5831 this.idealWidth = width;
5832 this.idealHeight = height;
5833
5834 if ( !this.clipping ) {
5835 // Update dimensions
5836 this.$clippable.css( { width: width, height: height } );
5837 }
5838 // While clipping, idealWidth and idealHeight are not considered
5839 };
5840
5841 /**
5842 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
5843 * the element's natural height changes.
5844 *
5845 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5846 * overlapped by, the visible area of the nearest scrollable container.
5847 *
5848 * @chainable
5849 */
5850 OO.ui.ClippableElement.prototype.clip = function () {
5851 if ( !this.clipping ) {
5852 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
5853 return this;
5854 }
5855
5856 var buffer = 7, // Chosen by fair dice roll
5857 cOffset = this.$clippable.offset(),
5858 $container = this.$clippableContainer.is( 'html, body' ) ?
5859 this.$clippableWindow : this.$clippableContainer,
5860 ccOffset = $container.offset() || { top: 0, left: 0 },
5861 ccHeight = $container.innerHeight() - buffer,
5862 ccWidth = $container.innerWidth() - buffer,
5863 cHeight = this.$clippable.outerHeight() + buffer,
5864 cWidth = this.$clippable.outerWidth() + buffer,
5865 scrollTop = this.$clippableScroller.scrollTop(),
5866 scrollLeft = this.$clippableScroller.scrollLeft(),
5867 desiredWidth = cOffset.left < 0 ?
5868 cWidth + cOffset.left :
5869 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
5870 desiredHeight = cOffset.top < 0 ?
5871 cHeight + cOffset.top :
5872 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
5873 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
5874 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
5875 clipWidth = desiredWidth < naturalWidth,
5876 clipHeight = desiredHeight < naturalHeight;
5877
5878 if ( clipWidth ) {
5879 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
5880 } else {
5881 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
5882 }
5883 if ( clipHeight ) {
5884 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
5885 } else {
5886 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
5887 }
5888
5889 // If we stopped clipping in at least one of the dimensions
5890 if ( !clipWidth || !clipHeight ) {
5891 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5892 }
5893
5894 this.clippedHorizontally = clipWidth;
5895 this.clippedVertically = clipHeight;
5896
5897 return this;
5898 };
5899
5900 /**
5901 * Generic toolbar tool.
5902 *
5903 * @abstract
5904 * @class
5905 * @extends OO.ui.Widget
5906 * @mixins OO.ui.IconElement
5907 * @mixins OO.ui.FlaggedElement
5908 *
5909 * @constructor
5910 * @param {OO.ui.ToolGroup} toolGroup
5911 * @param {Object} [config] Configuration options
5912 * @cfg {string|Function} [title] Title text or a function that returns text
5913 */
5914 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
5915 // Configuration initialization
5916 config = config || {};
5917
5918 // Parent constructor
5919 OO.ui.Tool.super.call( this, config );
5920
5921 // Mixin constructors
5922 OO.ui.IconElement.call( this, config );
5923 OO.ui.FlaggedElement.call( this, config );
5924
5925 // Properties
5926 this.toolGroup = toolGroup;
5927 this.toolbar = this.toolGroup.getToolbar();
5928 this.active = false;
5929 this.$title = this.$( '<span>' );
5930 this.$accel = this.$( '<span>' );
5931 this.$link = this.$( '<a>' );
5932 this.title = null;
5933
5934 // Events
5935 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
5936
5937 // Initialization
5938 this.$title.addClass( 'oo-ui-tool-title' );
5939 this.$accel
5940 .addClass( 'oo-ui-tool-accel' )
5941 .prop( {
5942 // This may need to be changed if the key names are ever localized,
5943 // but for now they are essentially written in English
5944 dir: 'ltr',
5945 lang: 'en'
5946 } );
5947 this.$link
5948 .addClass( 'oo-ui-tool-link' )
5949 .append( this.$icon, this.$title, this.$accel )
5950 .prop( 'tabIndex', 0 )
5951 .attr( 'role', 'button' );
5952 this.$element
5953 .data( 'oo-ui-tool', this )
5954 .addClass(
5955 'oo-ui-tool ' + 'oo-ui-tool-name-' +
5956 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
5957 )
5958 .append( this.$link );
5959 this.setTitle( config.title || this.constructor.static.title );
5960 };
5961
5962 /* Setup */
5963
5964 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
5965 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
5966 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
5967
5968 /* Events */
5969
5970 /**
5971 * @event select
5972 */
5973
5974 /* Static Properties */
5975
5976 /**
5977 * @static
5978 * @inheritdoc
5979 */
5980 OO.ui.Tool.static.tagName = 'span';
5981
5982 /**
5983 * Symbolic name of tool.
5984 *
5985 * @abstract
5986 * @static
5987 * @inheritable
5988 * @property {string}
5989 */
5990 OO.ui.Tool.static.name = '';
5991
5992 /**
5993 * Tool group.
5994 *
5995 * @abstract
5996 * @static
5997 * @inheritable
5998 * @property {string}
5999 */
6000 OO.ui.Tool.static.group = '';
6001
6002 /**
6003 * Tool title.
6004 *
6005 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6006 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6007 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6008 * appended to the title if the tool is part of a bar tool group.
6009 *
6010 * @abstract
6011 * @static
6012 * @inheritable
6013 * @property {string|Function} Title text or a function that returns text
6014 */
6015 OO.ui.Tool.static.title = '';
6016
6017 /**
6018 * Tool can be automatically added to catch-all groups.
6019 *
6020 * @static
6021 * @inheritable
6022 * @property {boolean}
6023 */
6024 OO.ui.Tool.static.autoAddToCatchall = true;
6025
6026 /**
6027 * Tool can be automatically added to named groups.
6028 *
6029 * @static
6030 * @property {boolean}
6031 * @inheritable
6032 */
6033 OO.ui.Tool.static.autoAddToGroup = true;
6034
6035 /**
6036 * Check if this tool is compatible with given data.
6037 *
6038 * @static
6039 * @inheritable
6040 * @param {Mixed} data Data to check
6041 * @return {boolean} Tool can be used with data
6042 */
6043 OO.ui.Tool.static.isCompatibleWith = function () {
6044 return false;
6045 };
6046
6047 /* Methods */
6048
6049 /**
6050 * Handle the toolbar state being updated.
6051 *
6052 * This is an abstract method that must be overridden in a concrete subclass.
6053 *
6054 * @abstract
6055 */
6056 OO.ui.Tool.prototype.onUpdateState = function () {
6057 throw new Error(
6058 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6059 );
6060 };
6061
6062 /**
6063 * Handle the tool being selected.
6064 *
6065 * This is an abstract method that must be overridden in a concrete subclass.
6066 *
6067 * @abstract
6068 */
6069 OO.ui.Tool.prototype.onSelect = function () {
6070 throw new Error(
6071 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6072 );
6073 };
6074
6075 /**
6076 * Check if the button is active.
6077 *
6078 * @return {boolean} Button is active
6079 */
6080 OO.ui.Tool.prototype.isActive = function () {
6081 return this.active;
6082 };
6083
6084 /**
6085 * Make the button appear active or inactive.
6086 *
6087 * @param {boolean} state Make button appear active
6088 */
6089 OO.ui.Tool.prototype.setActive = function ( state ) {
6090 this.active = !!state;
6091 if ( this.active ) {
6092 this.$element.addClass( 'oo-ui-tool-active' );
6093 } else {
6094 this.$element.removeClass( 'oo-ui-tool-active' );
6095 }
6096 };
6097
6098 /**
6099 * Get the tool title.
6100 *
6101 * @param {string|Function} title Title text or a function that returns text
6102 * @chainable
6103 */
6104 OO.ui.Tool.prototype.setTitle = function ( title ) {
6105 this.title = OO.ui.resolveMsg( title );
6106 this.updateTitle();
6107 return this;
6108 };
6109
6110 /**
6111 * Get the tool title.
6112 *
6113 * @return {string} Title text
6114 */
6115 OO.ui.Tool.prototype.getTitle = function () {
6116 return this.title;
6117 };
6118
6119 /**
6120 * Get the tool's symbolic name.
6121 *
6122 * @return {string} Symbolic name of tool
6123 */
6124 OO.ui.Tool.prototype.getName = function () {
6125 return this.constructor.static.name;
6126 };
6127
6128 /**
6129 * Update the title.
6130 */
6131 OO.ui.Tool.prototype.updateTitle = function () {
6132 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6133 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6134 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6135 tooltipParts = [];
6136
6137 this.$title.text( this.title );
6138 this.$accel.text( accel );
6139
6140 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6141 tooltipParts.push( this.title );
6142 }
6143 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6144 tooltipParts.push( accel );
6145 }
6146 if ( tooltipParts.length ) {
6147 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6148 } else {
6149 this.$link.removeAttr( 'title' );
6150 }
6151 };
6152
6153 /**
6154 * Destroy tool.
6155 */
6156 OO.ui.Tool.prototype.destroy = function () {
6157 this.toolbar.disconnect( this );
6158 this.$element.remove();
6159 };
6160
6161 /**
6162 * Collection of tool groups.
6163 *
6164 * @class
6165 * @extends OO.ui.Element
6166 * @mixins OO.EventEmitter
6167 * @mixins OO.ui.GroupElement
6168 *
6169 * @constructor
6170 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6171 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6172 * @param {Object} [config] Configuration options
6173 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6174 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6175 */
6176 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6177 // Configuration initialization
6178 config = config || {};
6179
6180 // Parent constructor
6181 OO.ui.Toolbar.super.call( this, config );
6182
6183 // Mixin constructors
6184 OO.EventEmitter.call( this );
6185 OO.ui.GroupElement.call( this, config );
6186
6187 // Properties
6188 this.toolFactory = toolFactory;
6189 this.toolGroupFactory = toolGroupFactory;
6190 this.groups = [];
6191 this.tools = {};
6192 this.$bar = this.$( '<div>' );
6193 this.$actions = this.$( '<div>' );
6194 this.initialized = false;
6195
6196 // Events
6197 this.$element
6198 .add( this.$bar ).add( this.$group ).add( this.$actions )
6199 .on( 'mousedown touchstart', this.onPointerDown.bind( this ) );
6200
6201 // Initialization
6202 this.$group.addClass( 'oo-ui-toolbar-tools' );
6203 if ( config.actions ) {
6204 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6205 }
6206 this.$bar
6207 .addClass( 'oo-ui-toolbar-bar' )
6208 .append( this.$group, '<div style="clear:both"></div>' );
6209 if ( config.shadow ) {
6210 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6211 }
6212 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6213 };
6214
6215 /* Setup */
6216
6217 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6218 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6219 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6220
6221 /* Methods */
6222
6223 /**
6224 * Get the tool factory.
6225 *
6226 * @return {OO.ui.ToolFactory} Tool factory
6227 */
6228 OO.ui.Toolbar.prototype.getToolFactory = function () {
6229 return this.toolFactory;
6230 };
6231
6232 /**
6233 * Get the tool group factory.
6234 *
6235 * @return {OO.Factory} Tool group factory
6236 */
6237 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6238 return this.toolGroupFactory;
6239 };
6240
6241 /**
6242 * Handles mouse down events.
6243 *
6244 * @param {jQuery.Event} e Mouse down event
6245 */
6246 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6247 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
6248 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6249 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6250 return false;
6251 }
6252 };
6253
6254 /**
6255 * Sets up handles and preloads required information for the toolbar to work.
6256 * This must be called after it is attached to a visible document and before doing anything else.
6257 */
6258 OO.ui.Toolbar.prototype.initialize = function () {
6259 this.initialized = true;
6260 };
6261
6262 /**
6263 * Setup toolbar.
6264 *
6265 * Tools can be specified in the following ways:
6266 *
6267 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6268 * - All tools in a group: `{ group: 'group-name' }`
6269 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6270 *
6271 * @param {Object.<string,Array>} groups List of tool group configurations
6272 * @param {Array|string} [groups.include] Tools to include
6273 * @param {Array|string} [groups.exclude] Tools to exclude
6274 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6275 * @param {Array|string} [groups.demote] Tools to demote to the end
6276 */
6277 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6278 var i, len, type, group,
6279 items = [],
6280 defaultType = 'bar';
6281
6282 // Cleanup previous groups
6283 this.reset();
6284
6285 // Build out new groups
6286 for ( i = 0, len = groups.length; i < len; i++ ) {
6287 group = groups[ i ];
6288 if ( group.include === '*' ) {
6289 // Apply defaults to catch-all groups
6290 if ( group.type === undefined ) {
6291 group.type = 'list';
6292 }
6293 if ( group.label === undefined ) {
6294 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6295 }
6296 }
6297 // Check type has been registered
6298 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6299 items.push(
6300 this.getToolGroupFactory().create( type, this, $.extend( { $: this.$ }, group ) )
6301 );
6302 }
6303 this.addItems( items );
6304 };
6305
6306 /**
6307 * Remove all tools and groups from the toolbar.
6308 */
6309 OO.ui.Toolbar.prototype.reset = function () {
6310 var i, len;
6311
6312 this.groups = [];
6313 this.tools = {};
6314 for ( i = 0, len = this.items.length; i < len; i++ ) {
6315 this.items[ i ].destroy();
6316 }
6317 this.clearItems();
6318 };
6319
6320 /**
6321 * Destroys toolbar, removing event handlers and DOM elements.
6322 *
6323 * Call this whenever you are done using a toolbar.
6324 */
6325 OO.ui.Toolbar.prototype.destroy = function () {
6326 this.reset();
6327 this.$element.remove();
6328 };
6329
6330 /**
6331 * Check if tool has not been used yet.
6332 *
6333 * @param {string} name Symbolic name of tool
6334 * @return {boolean} Tool is available
6335 */
6336 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6337 return !this.tools[ name ];
6338 };
6339
6340 /**
6341 * Prevent tool from being used again.
6342 *
6343 * @param {OO.ui.Tool} tool Tool to reserve
6344 */
6345 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6346 this.tools[ tool.getName() ] = tool;
6347 };
6348
6349 /**
6350 * Allow tool to be used again.
6351 *
6352 * @param {OO.ui.Tool} tool Tool to release
6353 */
6354 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6355 delete this.tools[ tool.getName() ];
6356 };
6357
6358 /**
6359 * Get accelerator label for tool.
6360 *
6361 * This is a stub that should be overridden to provide access to accelerator information.
6362 *
6363 * @param {string} name Symbolic name of tool
6364 * @return {string|undefined} Tool accelerator label if available
6365 */
6366 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6367 return undefined;
6368 };
6369
6370 /**
6371 * Collection of tools.
6372 *
6373 * Tools can be specified in the following ways:
6374 *
6375 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6376 * - All tools in a group: `{ group: 'group-name' }`
6377 * - All tools: `'*'`
6378 *
6379 * @abstract
6380 * @class
6381 * @extends OO.ui.Widget
6382 * @mixins OO.ui.GroupElement
6383 *
6384 * @constructor
6385 * @param {OO.ui.Toolbar} toolbar
6386 * @param {Object} [config] Configuration options
6387 * @cfg {Array|string} [include=[]] List of tools to include
6388 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6389 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6390 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6391 */
6392 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6393 // Configuration initialization
6394 config = config || {};
6395
6396 // Parent constructor
6397 OO.ui.ToolGroup.super.call( this, config );
6398
6399 // Mixin constructors
6400 OO.ui.GroupElement.call( this, config );
6401
6402 // Properties
6403 this.toolbar = toolbar;
6404 this.tools = {};
6405 this.pressed = null;
6406 this.autoDisabled = false;
6407 this.include = config.include || [];
6408 this.exclude = config.exclude || [];
6409 this.promote = config.promote || [];
6410 this.demote = config.demote || [];
6411 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6412
6413 // Events
6414 this.$element.on( {
6415 'mousedown touchstart': this.onPointerDown.bind( this ),
6416 'mouseup touchend': this.onPointerUp.bind( this ),
6417 mouseover: this.onMouseOver.bind( this ),
6418 mouseout: this.onMouseOut.bind( this )
6419 } );
6420 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6421 this.aggregate( { disable: 'itemDisable' } );
6422 this.connect( this, { itemDisable: 'updateDisabled' } );
6423
6424 // Initialization
6425 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6426 this.$element
6427 .addClass( 'oo-ui-toolGroup' )
6428 .append( this.$group );
6429 this.populate();
6430 };
6431
6432 /* Setup */
6433
6434 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6435 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6436
6437 /* Events */
6438
6439 /**
6440 * @event update
6441 */
6442
6443 /* Static Properties */
6444
6445 /**
6446 * Show labels in tooltips.
6447 *
6448 * @static
6449 * @inheritable
6450 * @property {boolean}
6451 */
6452 OO.ui.ToolGroup.static.titleTooltips = false;
6453
6454 /**
6455 * Show acceleration labels in tooltips.
6456 *
6457 * @static
6458 * @inheritable
6459 * @property {boolean}
6460 */
6461 OO.ui.ToolGroup.static.accelTooltips = false;
6462
6463 /**
6464 * Automatically disable the toolgroup when all tools are disabled
6465 *
6466 * @static
6467 * @inheritable
6468 * @property {boolean}
6469 */
6470 OO.ui.ToolGroup.static.autoDisable = true;
6471
6472 /* Methods */
6473
6474 /**
6475 * @inheritdoc
6476 */
6477 OO.ui.ToolGroup.prototype.isDisabled = function () {
6478 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6479 };
6480
6481 /**
6482 * @inheritdoc
6483 */
6484 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6485 var i, item, allDisabled = true;
6486
6487 if ( this.constructor.static.autoDisable ) {
6488 for ( i = this.items.length - 1; i >= 0; i-- ) {
6489 item = this.items[ i ];
6490 if ( !item.isDisabled() ) {
6491 allDisabled = false;
6492 break;
6493 }
6494 }
6495 this.autoDisabled = allDisabled;
6496 }
6497 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6498 };
6499
6500 /**
6501 * Handle mouse down events.
6502 *
6503 * @param {jQuery.Event} e Mouse down event
6504 */
6505 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6506 // e.which is 0 for touch events, 1 for left mouse button
6507 if ( !this.isDisabled() && e.which <= 1 ) {
6508 this.pressed = this.getTargetTool( e );
6509 if ( this.pressed ) {
6510 this.pressed.setActive( true );
6511 this.getElementDocument().addEventListener(
6512 'mouseup', this.onCapturedMouseUpHandler, true
6513 );
6514 }
6515 }
6516 return false;
6517 };
6518
6519 /**
6520 * Handle captured mouse up events.
6521 *
6522 * @param {Event} e Mouse up event
6523 */
6524 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6525 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
6526 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6527 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6528 this.onPointerUp( e );
6529 };
6530
6531 /**
6532 * Handle mouse up events.
6533 *
6534 * @param {jQuery.Event} e Mouse up event
6535 */
6536 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
6537 var tool = this.getTargetTool( e );
6538
6539 // e.which is 0 for touch events, 1 for left mouse button
6540 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === tool ) {
6541 this.pressed.onSelect();
6542 }
6543
6544 this.pressed = null;
6545 return false;
6546 };
6547
6548 /**
6549 * Handle mouse over events.
6550 *
6551 * @param {jQuery.Event} e Mouse over event
6552 */
6553 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
6554 var tool = this.getTargetTool( e );
6555
6556 if ( this.pressed && this.pressed === tool ) {
6557 this.pressed.setActive( true );
6558 }
6559 };
6560
6561 /**
6562 * Handle mouse out events.
6563 *
6564 * @param {jQuery.Event} e Mouse out event
6565 */
6566 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
6567 var tool = this.getTargetTool( e );
6568
6569 if ( this.pressed && this.pressed === tool ) {
6570 this.pressed.setActive( false );
6571 }
6572 };
6573
6574 /**
6575 * Get the closest tool to a jQuery.Event.
6576 *
6577 * Only tool links are considered, which prevents other elements in the tool such as popups from
6578 * triggering tool group interactions.
6579 *
6580 * @private
6581 * @param {jQuery.Event} e
6582 * @return {OO.ui.Tool|null} Tool, `null` if none was found
6583 */
6584 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
6585 var tool,
6586 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
6587
6588 if ( $item.length ) {
6589 tool = $item.parent().data( 'oo-ui-tool' );
6590 }
6591
6592 return tool && !tool.isDisabled() ? tool : null;
6593 };
6594
6595 /**
6596 * Handle tool registry register events.
6597 *
6598 * If a tool is registered after the group is created, we must repopulate the list to account for:
6599 *
6600 * - a tool being added that may be included
6601 * - a tool already included being overridden
6602 *
6603 * @param {string} name Symbolic name of tool
6604 */
6605 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
6606 this.populate();
6607 };
6608
6609 /**
6610 * Get the toolbar this group is in.
6611 *
6612 * @return {OO.ui.Toolbar} Toolbar of group
6613 */
6614 OO.ui.ToolGroup.prototype.getToolbar = function () {
6615 return this.toolbar;
6616 };
6617
6618 /**
6619 * Add and remove tools based on configuration.
6620 */
6621 OO.ui.ToolGroup.prototype.populate = function () {
6622 var i, len, name, tool,
6623 toolFactory = this.toolbar.getToolFactory(),
6624 names = {},
6625 add = [],
6626 remove = [],
6627 list = this.toolbar.getToolFactory().getTools(
6628 this.include, this.exclude, this.promote, this.demote
6629 );
6630
6631 // Build a list of needed tools
6632 for ( i = 0, len = list.length; i < len; i++ ) {
6633 name = list[ i ];
6634 if (
6635 // Tool exists
6636 toolFactory.lookup( name ) &&
6637 // Tool is available or is already in this group
6638 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
6639 ) {
6640 tool = this.tools[ name ];
6641 if ( !tool ) {
6642 // Auto-initialize tools on first use
6643 this.tools[ name ] = tool = toolFactory.create( name, this );
6644 tool.updateTitle();
6645 }
6646 this.toolbar.reserveTool( tool );
6647 add.push( tool );
6648 names[ name ] = true;
6649 }
6650 }
6651 // Remove tools that are no longer needed
6652 for ( name in this.tools ) {
6653 if ( !names[ name ] ) {
6654 this.tools[ name ].destroy();
6655 this.toolbar.releaseTool( this.tools[ name ] );
6656 remove.push( this.tools[ name ] );
6657 delete this.tools[ name ];
6658 }
6659 }
6660 if ( remove.length ) {
6661 this.removeItems( remove );
6662 }
6663 // Update emptiness state
6664 if ( add.length ) {
6665 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
6666 } else {
6667 this.$element.addClass( 'oo-ui-toolGroup-empty' );
6668 }
6669 // Re-add tools (moving existing ones to new locations)
6670 this.addItems( add );
6671 // Disabled state may depend on items
6672 this.updateDisabled();
6673 };
6674
6675 /**
6676 * Destroy tool group.
6677 */
6678 OO.ui.ToolGroup.prototype.destroy = function () {
6679 var name;
6680
6681 this.clearItems();
6682 this.toolbar.getToolFactory().disconnect( this );
6683 for ( name in this.tools ) {
6684 this.toolbar.releaseTool( this.tools[ name ] );
6685 this.tools[ name ].disconnect( this ).destroy();
6686 delete this.tools[ name ];
6687 }
6688 this.$element.remove();
6689 };
6690
6691 /**
6692 * Dialog for showing a message.
6693 *
6694 * User interface:
6695 * - Registers two actions by default (safe and primary).
6696 * - Renders action widgets in the footer.
6697 *
6698 * @class
6699 * @extends OO.ui.Dialog
6700 *
6701 * @constructor
6702 * @param {Object} [config] Configuration options
6703 */
6704 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
6705 // Parent constructor
6706 OO.ui.MessageDialog.super.call( this, config );
6707
6708 // Properties
6709 this.verticalActionLayout = null;
6710
6711 // Initialization
6712 this.$element.addClass( 'oo-ui-messageDialog' );
6713 };
6714
6715 /* Inheritance */
6716
6717 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
6718
6719 /* Static Properties */
6720
6721 OO.ui.MessageDialog.static.name = 'message';
6722
6723 OO.ui.MessageDialog.static.size = 'small';
6724
6725 OO.ui.MessageDialog.static.verbose = false;
6726
6727 /**
6728 * Dialog title.
6729 *
6730 * A confirmation dialog's title should describe what the progressive action will do. An alert
6731 * dialog's title should describe what event occurred.
6732 *
6733 * @static
6734 * inheritable
6735 * @property {jQuery|string|Function|null}
6736 */
6737 OO.ui.MessageDialog.static.title = null;
6738
6739 /**
6740 * A confirmation dialog's message should describe the consequences of the progressive action. An
6741 * alert dialog's message should describe why the event occurred.
6742 *
6743 * @static
6744 * inheritable
6745 * @property {jQuery|string|Function|null}
6746 */
6747 OO.ui.MessageDialog.static.message = null;
6748
6749 OO.ui.MessageDialog.static.actions = [
6750 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
6751 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
6752 ];
6753
6754 /* Methods */
6755
6756 /**
6757 * @inheritdoc
6758 */
6759 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
6760 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
6761
6762 // Events
6763 this.manager.connect( this, {
6764 resize: 'onResize'
6765 } );
6766
6767 return this;
6768 };
6769
6770 /**
6771 * @inheritdoc
6772 */
6773 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
6774 this.fitActions();
6775 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
6776 };
6777
6778 /**
6779 * Handle window resized events.
6780 */
6781 OO.ui.MessageDialog.prototype.onResize = function () {
6782 var dialog = this;
6783 dialog.fitActions();
6784 // Wait for CSS transition to finish and do it again :(
6785 setTimeout( function () {
6786 dialog.fitActions();
6787 }, 300 );
6788 };
6789
6790 /**
6791 * Toggle action layout between vertical and horizontal.
6792 *
6793 * @param {boolean} [value] Layout actions vertically, omit to toggle
6794 * @chainable
6795 */
6796 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
6797 value = value === undefined ? !this.verticalActionLayout : !!value;
6798
6799 if ( value !== this.verticalActionLayout ) {
6800 this.verticalActionLayout = value;
6801 this.$actions
6802 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
6803 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
6804 }
6805
6806 return this;
6807 };
6808
6809 /**
6810 * @inheritdoc
6811 */
6812 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
6813 if ( action ) {
6814 return new OO.ui.Process( function () {
6815 this.close( { action: action } );
6816 }, this );
6817 }
6818 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
6819 };
6820
6821 /**
6822 * @inheritdoc
6823 *
6824 * @param {Object} [data] Dialog opening data
6825 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
6826 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
6827 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
6828 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
6829 * action item
6830 */
6831 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
6832 data = data || {};
6833
6834 // Parent method
6835 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
6836 .next( function () {
6837 this.title.setLabel(
6838 data.title !== undefined ? data.title : this.constructor.static.title
6839 );
6840 this.message.setLabel(
6841 data.message !== undefined ? data.message : this.constructor.static.message
6842 );
6843 this.message.$element.toggleClass(
6844 'oo-ui-messageDialog-message-verbose',
6845 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
6846 );
6847 }, this );
6848 };
6849
6850 /**
6851 * @inheritdoc
6852 */
6853 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
6854 var bodyHeight, oldOverflow,
6855 $scrollable = this.container.$element;
6856
6857 oldOverflow = $scrollable[ 0 ].style.overflow;
6858 $scrollable[ 0 ].style.overflow = 'hidden';
6859
6860 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
6861
6862 bodyHeight = this.text.$element.outerHeight( true );
6863 $scrollable[ 0 ].style.overflow = oldOverflow;
6864
6865 return bodyHeight;
6866 };
6867
6868 /**
6869 * @inheritdoc
6870 */
6871 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
6872 var $scrollable = this.container.$element;
6873 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
6874
6875 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
6876 // Need to do it after transition completes (250ms), add 50ms just in case.
6877 setTimeout( function () {
6878 var oldOverflow = $scrollable[ 0 ].style.overflow;
6879 $scrollable[ 0 ].style.overflow = 'hidden';
6880
6881 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
6882
6883 $scrollable[ 0 ].style.overflow = oldOverflow;
6884 }, 300 );
6885
6886 return this;
6887 };
6888
6889 /**
6890 * @inheritdoc
6891 */
6892 OO.ui.MessageDialog.prototype.initialize = function () {
6893 // Parent method
6894 OO.ui.MessageDialog.super.prototype.initialize.call( this );
6895
6896 // Properties
6897 this.$actions = this.$( '<div>' );
6898 this.container = new OO.ui.PanelLayout( {
6899 $: this.$, scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
6900 } );
6901 this.text = new OO.ui.PanelLayout( {
6902 $: this.$, padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
6903 } );
6904 this.message = new OO.ui.LabelWidget( {
6905 $: this.$, classes: [ 'oo-ui-messageDialog-message' ]
6906 } );
6907
6908 // Initialization
6909 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
6910 this.$content.addClass( 'oo-ui-messageDialog-content' );
6911 this.container.$element.append( this.text.$element );
6912 this.text.$element.append( this.title.$element, this.message.$element );
6913 this.$body.append( this.container.$element );
6914 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
6915 this.$foot.append( this.$actions );
6916 };
6917
6918 /**
6919 * @inheritdoc
6920 */
6921 OO.ui.MessageDialog.prototype.attachActions = function () {
6922 var i, len, other, special, others;
6923
6924 // Parent method
6925 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
6926
6927 special = this.actions.getSpecial();
6928 others = this.actions.getOthers();
6929 if ( special.safe ) {
6930 this.$actions.append( special.safe.$element );
6931 special.safe.toggleFramed( false );
6932 }
6933 if ( others.length ) {
6934 for ( i = 0, len = others.length; i < len; i++ ) {
6935 other = others[ i ];
6936 this.$actions.append( other.$element );
6937 other.toggleFramed( false );
6938 }
6939 }
6940 if ( special.primary ) {
6941 this.$actions.append( special.primary.$element );
6942 special.primary.toggleFramed( false );
6943 }
6944
6945 if ( !this.isOpening() ) {
6946 // If the dialog is currently opening, this will be called automatically soon.
6947 // This also calls #fitActions.
6948 this.updateSize();
6949 }
6950 };
6951
6952 /**
6953 * Fit action actions into columns or rows.
6954 *
6955 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
6956 */
6957 OO.ui.MessageDialog.prototype.fitActions = function () {
6958 var i, len, action,
6959 previous = this.verticalActionLayout,
6960 actions = this.actions.get();
6961
6962 // Detect clipping
6963 this.toggleVerticalActionLayout( false );
6964 for ( i = 0, len = actions.length; i < len; i++ ) {
6965 action = actions[ i ];
6966 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
6967 this.toggleVerticalActionLayout( true );
6968 break;
6969 }
6970 }
6971
6972 if ( this.verticalActionLayout !== previous ) {
6973 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
6974 // We changed the layout, window height might need to be updated.
6975 this.updateSize();
6976 }
6977 };
6978
6979 /**
6980 * Navigation dialog window.
6981 *
6982 * Logic:
6983 * - Show and hide errors.
6984 * - Retry an action.
6985 *
6986 * User interface:
6987 * - Renders header with dialog title and one action widget on either side
6988 * (a 'safe' button on the left, and a 'primary' button on the right, both of
6989 * which close the dialog).
6990 * - Displays any action widgets in the footer (none by default).
6991 * - Ability to dismiss errors.
6992 *
6993 * Subclass responsibilities:
6994 * - Register a 'safe' action.
6995 * - Register a 'primary' action.
6996 * - Add content to the dialog.
6997 *
6998 * @abstract
6999 * @class
7000 * @extends OO.ui.Dialog
7001 *
7002 * @constructor
7003 * @param {Object} [config] Configuration options
7004 */
7005 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7006 // Parent constructor
7007 OO.ui.ProcessDialog.super.call( this, config );
7008
7009 // Initialization
7010 this.$element.addClass( 'oo-ui-processDialog' );
7011 };
7012
7013 /* Setup */
7014
7015 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7016
7017 /* Methods */
7018
7019 /**
7020 * Handle dismiss button click events.
7021 *
7022 * Hides errors.
7023 */
7024 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7025 this.hideErrors();
7026 };
7027
7028 /**
7029 * Handle retry button click events.
7030 *
7031 * Hides errors and then tries again.
7032 */
7033 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7034 this.hideErrors();
7035 this.executeAction( this.currentAction.getAction() );
7036 };
7037
7038 /**
7039 * @inheritdoc
7040 */
7041 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7042 if ( this.actions.isSpecial( action ) ) {
7043 this.fitLabel();
7044 }
7045 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7046 };
7047
7048 /**
7049 * @inheritdoc
7050 */
7051 OO.ui.ProcessDialog.prototype.initialize = function () {
7052 // Parent method
7053 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7054
7055 // Properties
7056 this.$navigation = this.$( '<div>' );
7057 this.$location = this.$( '<div>' );
7058 this.$safeActions = this.$( '<div>' );
7059 this.$primaryActions = this.$( '<div>' );
7060 this.$otherActions = this.$( '<div>' );
7061 this.dismissButton = new OO.ui.ButtonWidget( {
7062 $: this.$,
7063 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7064 } );
7065 this.retryButton = new OO.ui.ButtonWidget( { $: this.$ } );
7066 this.$errors = this.$( '<div>' );
7067 this.$errorsTitle = this.$( '<div>' );
7068
7069 // Events
7070 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7071 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7072
7073 // Initialization
7074 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7075 this.$location
7076 .append( this.title.$element )
7077 .addClass( 'oo-ui-processDialog-location' );
7078 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7079 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7080 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7081 this.$errorsTitle
7082 .addClass( 'oo-ui-processDialog-errors-title' )
7083 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7084 this.$errors
7085 .addClass( 'oo-ui-processDialog-errors' )
7086 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7087 this.$content
7088 .addClass( 'oo-ui-processDialog-content' )
7089 .append( this.$errors );
7090 this.$navigation
7091 .addClass( 'oo-ui-processDialog-navigation' )
7092 .append( this.$safeActions, this.$location, this.$primaryActions );
7093 this.$head.append( this.$navigation );
7094 this.$foot.append( this.$otherActions );
7095 };
7096
7097 /**
7098 * @inheritdoc
7099 */
7100 OO.ui.ProcessDialog.prototype.attachActions = function () {
7101 var i, len, other, special, others;
7102
7103 // Parent method
7104 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7105
7106 special = this.actions.getSpecial();
7107 others = this.actions.getOthers();
7108 if ( special.primary ) {
7109 this.$primaryActions.append( special.primary.$element );
7110 special.primary.toggleFramed( true );
7111 }
7112 if ( others.length ) {
7113 for ( i = 0, len = others.length; i < len; i++ ) {
7114 other = others[ i ];
7115 this.$otherActions.append( other.$element );
7116 other.toggleFramed( true );
7117 }
7118 }
7119 if ( special.safe ) {
7120 this.$safeActions.append( special.safe.$element );
7121 special.safe.toggleFramed( true );
7122 }
7123
7124 this.fitLabel();
7125 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7126 };
7127
7128 /**
7129 * @inheritdoc
7130 */
7131 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7132 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7133 .fail( this.showErrors.bind( this ) );
7134 };
7135
7136 /**
7137 * Fit label between actions.
7138 *
7139 * @chainable
7140 */
7141 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7142 var width = Math.max(
7143 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7144 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7145 );
7146 this.$location.css( { paddingLeft: width, paddingRight: width } );
7147
7148 return this;
7149 };
7150
7151 /**
7152 * Handle errors that occurred during accept or reject processes.
7153 *
7154 * @param {OO.ui.Error[]} errors Errors to be handled
7155 */
7156 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7157 var i, len, $item,
7158 items = [],
7159 recoverable = true,
7160 warning = false;
7161
7162 for ( i = 0, len = errors.length; i < len; i++ ) {
7163 if ( !errors[ i ].isRecoverable() ) {
7164 recoverable = false;
7165 }
7166 if ( errors[ i ].isWarning() ) {
7167 warning = true;
7168 }
7169 $item = this.$( '<div>' )
7170 .addClass( 'oo-ui-processDialog-error' )
7171 .append( errors[ i ].getMessage() );
7172 items.push( $item[ 0 ] );
7173 }
7174 this.$errorItems = this.$( items );
7175 if ( recoverable ) {
7176 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
7177 } else {
7178 this.currentAction.setDisabled( true );
7179 }
7180 if ( warning ) {
7181 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7182 } else {
7183 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7184 }
7185 this.retryButton.toggle( recoverable );
7186 this.$errorsTitle.after( this.$errorItems );
7187 this.$errors.show().scrollTop( 0 );
7188 };
7189
7190 /**
7191 * Hide errors.
7192 */
7193 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7194 this.$errors.hide();
7195 this.$errorItems.remove();
7196 this.$errorItems = null;
7197 };
7198
7199 /**
7200 * Layout containing a series of pages.
7201 *
7202 * @class
7203 * @extends OO.ui.Layout
7204 *
7205 * @constructor
7206 * @param {Object} [config] Configuration options
7207 * @cfg {boolean} [continuous=false] Show all pages, one after another
7208 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
7209 * @cfg {boolean} [outlined=false] Show an outline
7210 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
7211 */
7212 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
7213 // Configuration initialization
7214 config = config || {};
7215
7216 // Parent constructor
7217 OO.ui.BookletLayout.super.call( this, config );
7218
7219 // Properties
7220 this.currentPageName = null;
7221 this.pages = {};
7222 this.ignoreFocus = false;
7223 this.stackLayout = new OO.ui.StackLayout( { $: this.$, continuous: !!config.continuous } );
7224 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
7225 this.outlineVisible = false;
7226 this.outlined = !!config.outlined;
7227 if ( this.outlined ) {
7228 this.editable = !!config.editable;
7229 this.outlineControlsWidget = null;
7230 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget( { $: this.$ } );
7231 this.outlinePanel = new OO.ui.PanelLayout( { $: this.$, scrollable: true } );
7232 this.gridLayout = new OO.ui.GridLayout(
7233 [ this.outlinePanel, this.stackLayout ],
7234 { $: this.$, widths: [ 1, 2 ] }
7235 );
7236 this.outlineVisible = true;
7237 if ( this.editable ) {
7238 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
7239 this.outlineSelectWidget, { $: this.$ }
7240 );
7241 }
7242 }
7243
7244 // Events
7245 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
7246 if ( this.outlined ) {
7247 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
7248 }
7249 if ( this.autoFocus ) {
7250 // Event 'focus' does not bubble, but 'focusin' does
7251 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
7252 }
7253
7254 // Initialization
7255 this.$element.addClass( 'oo-ui-bookletLayout' );
7256 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
7257 if ( this.outlined ) {
7258 this.outlinePanel.$element
7259 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
7260 .append( this.outlineSelectWidget.$element );
7261 if ( this.editable ) {
7262 this.outlinePanel.$element
7263 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
7264 .append( this.outlineControlsWidget.$element );
7265 }
7266 this.$element.append( this.gridLayout.$element );
7267 } else {
7268 this.$element.append( this.stackLayout.$element );
7269 }
7270 };
7271
7272 /* Setup */
7273
7274 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
7275
7276 /* Events */
7277
7278 /**
7279 * @event set
7280 * @param {OO.ui.PageLayout} page Current page
7281 */
7282
7283 /**
7284 * @event add
7285 * @param {OO.ui.PageLayout[]} page Added pages
7286 * @param {number} index Index pages were added at
7287 */
7288
7289 /**
7290 * @event remove
7291 * @param {OO.ui.PageLayout[]} pages Removed pages
7292 */
7293
7294 /* Methods */
7295
7296 /**
7297 * Handle stack layout focus.
7298 *
7299 * @param {jQuery.Event} e Focusin event
7300 */
7301 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
7302 var name, $target;
7303
7304 // Find the page that an element was focused within
7305 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
7306 for ( name in this.pages ) {
7307 // Check for page match, exclude current page to find only page changes
7308 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
7309 this.setPage( name );
7310 break;
7311 }
7312 }
7313 };
7314
7315 /**
7316 * Handle stack layout set events.
7317 *
7318 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
7319 */
7320 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
7321 var layout = this;
7322 if ( page ) {
7323 page.scrollElementIntoView( { complete: function () {
7324 if ( layout.autoFocus ) {
7325 layout.focus();
7326 }
7327 } } );
7328 }
7329 };
7330
7331 /**
7332 * Focus the first input in the current page.
7333 *
7334 * If no page is selected, the first selectable page will be selected.
7335 * If the focus is already in an element on the current page, nothing will happen.
7336 */
7337 OO.ui.BookletLayout.prototype.focus = function () {
7338 var $input, page = this.stackLayout.getCurrentItem();
7339 if ( !page && this.outlined ) {
7340 this.selectFirstSelectablePage();
7341 page = this.stackLayout.getCurrentItem();
7342 }
7343 if ( !page ) {
7344 return;
7345 }
7346 // Only change the focus if is not already in the current page
7347 if ( !page.$element.find( ':focus' ).length ) {
7348 $input = page.$element.find( ':input:first' );
7349 if ( $input.length ) {
7350 $input[ 0 ].focus();
7351 }
7352 }
7353 };
7354
7355 /**
7356 * Handle outline widget select events.
7357 *
7358 * @param {OO.ui.OptionWidget|null} item Selected item
7359 */
7360 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
7361 if ( item ) {
7362 this.setPage( item.getData() );
7363 }
7364 };
7365
7366 /**
7367 * Check if booklet has an outline.
7368 *
7369 * @return {boolean}
7370 */
7371 OO.ui.BookletLayout.prototype.isOutlined = function () {
7372 return this.outlined;
7373 };
7374
7375 /**
7376 * Check if booklet has editing controls.
7377 *
7378 * @return {boolean}
7379 */
7380 OO.ui.BookletLayout.prototype.isEditable = function () {
7381 return this.editable;
7382 };
7383
7384 /**
7385 * Check if booklet has a visible outline.
7386 *
7387 * @return {boolean}
7388 */
7389 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
7390 return this.outlined && this.outlineVisible;
7391 };
7392
7393 /**
7394 * Hide or show the outline.
7395 *
7396 * @param {boolean} [show] Show outline, omit to invert current state
7397 * @chainable
7398 */
7399 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
7400 if ( this.outlined ) {
7401 show = show === undefined ? !this.outlineVisible : !!show;
7402 this.outlineVisible = show;
7403 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
7404 }
7405
7406 return this;
7407 };
7408
7409 /**
7410 * Get the outline widget.
7411 *
7412 * @param {OO.ui.PageLayout} page Page to be selected
7413 * @return {OO.ui.PageLayout|null} Closest page to another
7414 */
7415 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
7416 var next, prev, level,
7417 pages = this.stackLayout.getItems(),
7418 index = $.inArray( page, pages );
7419
7420 if ( index !== -1 ) {
7421 next = pages[ index + 1 ];
7422 prev = pages[ index - 1 ];
7423 // Prefer adjacent pages at the same level
7424 if ( this.outlined ) {
7425 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
7426 if (
7427 prev &&
7428 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
7429 ) {
7430 return prev;
7431 }
7432 if (
7433 next &&
7434 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
7435 ) {
7436 return next;
7437 }
7438 }
7439 }
7440 return prev || next || null;
7441 };
7442
7443 /**
7444 * Get the outline widget.
7445 *
7446 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
7447 */
7448 OO.ui.BookletLayout.prototype.getOutline = function () {
7449 return this.outlineSelectWidget;
7450 };
7451
7452 /**
7453 * Get the outline controls widget. If the outline is not editable, null is returned.
7454 *
7455 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
7456 */
7457 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
7458 return this.outlineControlsWidget;
7459 };
7460
7461 /**
7462 * Get a page by name.
7463 *
7464 * @param {string} name Symbolic name of page
7465 * @return {OO.ui.PageLayout|undefined} Page, if found
7466 */
7467 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
7468 return this.pages[ name ];
7469 };
7470
7471 /**
7472 * Get the current page name.
7473 *
7474 * @return {string|null} Current page name
7475 */
7476 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
7477 return this.currentPageName;
7478 };
7479
7480 /**
7481 * Add a page to the layout.
7482 *
7483 * When pages are added with the same names as existing pages, the existing pages will be
7484 * automatically removed before the new pages are added.
7485 *
7486 * @param {OO.ui.PageLayout[]} pages Pages to add
7487 * @param {number} index Index to insert pages after
7488 * @fires add
7489 * @chainable
7490 */
7491 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
7492 var i, len, name, page, item, currentIndex,
7493 stackLayoutPages = this.stackLayout.getItems(),
7494 remove = [],
7495 items = [];
7496
7497 // Remove pages with same names
7498 for ( i = 0, len = pages.length; i < len; i++ ) {
7499 page = pages[ i ];
7500 name = page.getName();
7501
7502 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
7503 // Correct the insertion index
7504 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
7505 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
7506 index--;
7507 }
7508 remove.push( this.pages[ name ] );
7509 }
7510 }
7511 if ( remove.length ) {
7512 this.removePages( remove );
7513 }
7514
7515 // Add new pages
7516 for ( i = 0, len = pages.length; i < len; i++ ) {
7517 page = pages[ i ];
7518 name = page.getName();
7519 this.pages[ page.getName() ] = page;
7520 if ( this.outlined ) {
7521 item = new OO.ui.OutlineOptionWidget( { $: this.$, data: name } );
7522 page.setOutlineItem( item );
7523 items.push( item );
7524 }
7525 }
7526
7527 if ( this.outlined && items.length ) {
7528 this.outlineSelectWidget.addItems( items, index );
7529 this.selectFirstSelectablePage();
7530 }
7531 this.stackLayout.addItems( pages, index );
7532 this.emit( 'add', pages, index );
7533
7534 return this;
7535 };
7536
7537 /**
7538 * Remove a page from the layout.
7539 *
7540 * @fires remove
7541 * @chainable
7542 */
7543 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
7544 var i, len, name, page,
7545 items = [];
7546
7547 for ( i = 0, len = pages.length; i < len; i++ ) {
7548 page = pages[ i ];
7549 name = page.getName();
7550 delete this.pages[ name ];
7551 if ( this.outlined ) {
7552 items.push( this.outlineSelectWidget.getItemFromData( name ) );
7553 page.setOutlineItem( null );
7554 }
7555 }
7556 if ( this.outlined && items.length ) {
7557 this.outlineSelectWidget.removeItems( items );
7558 this.selectFirstSelectablePage();
7559 }
7560 this.stackLayout.removeItems( pages );
7561 this.emit( 'remove', pages );
7562
7563 return this;
7564 };
7565
7566 /**
7567 * Clear all pages from the layout.
7568 *
7569 * @fires remove
7570 * @chainable
7571 */
7572 OO.ui.BookletLayout.prototype.clearPages = function () {
7573 var i, len,
7574 pages = this.stackLayout.getItems();
7575
7576 this.pages = {};
7577 this.currentPageName = null;
7578 if ( this.outlined ) {
7579 this.outlineSelectWidget.clearItems();
7580 for ( i = 0, len = pages.length; i < len; i++ ) {
7581 pages[ i ].setOutlineItem( null );
7582 }
7583 }
7584 this.stackLayout.clearItems();
7585
7586 this.emit( 'remove', pages );
7587
7588 return this;
7589 };
7590
7591 /**
7592 * Set the current page by name.
7593 *
7594 * @fires set
7595 * @param {string} name Symbolic name of page
7596 */
7597 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
7598 var selectedItem,
7599 $focused,
7600 page = this.pages[ name ];
7601
7602 if ( name !== this.currentPageName ) {
7603 if ( this.outlined ) {
7604 selectedItem = this.outlineSelectWidget.getSelectedItem();
7605 if ( selectedItem && selectedItem.getData() !== name ) {
7606 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
7607 }
7608 }
7609 if ( page ) {
7610 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
7611 this.pages[ this.currentPageName ].setActive( false );
7612 // Blur anything focused if the next page doesn't have anything focusable - this
7613 // is not needed if the next page has something focusable because once it is focused
7614 // this blur happens automatically
7615 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
7616 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
7617 if ( $focused.length ) {
7618 $focused[ 0 ].blur();
7619 }
7620 }
7621 }
7622 this.currentPageName = name;
7623 this.stackLayout.setItem( page );
7624 page.setActive( true );
7625 this.emit( 'set', page );
7626 }
7627 }
7628 };
7629
7630 /**
7631 * Select the first selectable page.
7632 *
7633 * @chainable
7634 */
7635 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
7636 if ( !this.outlineSelectWidget.getSelectedItem() ) {
7637 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
7638 }
7639
7640 return this;
7641 };
7642
7643 /**
7644 * Layout made of a field and optional label.
7645 *
7646 * Available label alignment modes include:
7647 * - left: Label is before the field and aligned away from it, best for when the user will be
7648 * scanning for a specific label in a form with many fields
7649 * - right: Label is before the field and aligned toward it, best for forms the user is very
7650 * familiar with and will tab through field checking quickly to verify which field they are in
7651 * - top: Label is before the field and above it, best for when the user will need to fill out all
7652 * fields from top to bottom in a form with few fields
7653 * - inline: Label is after the field and aligned toward it, best for small boolean fields like
7654 * checkboxes or radio buttons
7655 *
7656 * @class
7657 * @extends OO.ui.Layout
7658 * @mixins OO.ui.LabelElement
7659 *
7660 * @constructor
7661 * @param {OO.ui.Widget} fieldWidget Field widget
7662 * @param {Object} [config] Configuration options
7663 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7664 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7665 */
7666 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7667 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7668
7669 // Configuration initialization
7670 config = $.extend( { align: 'left' }, config );
7671
7672 // Properties (must be set before parent constructor, which calls #getTagName)
7673 this.fieldWidget = fieldWidget;
7674
7675 // Parent constructor
7676 OO.ui.FieldLayout.super.call( this, config );
7677
7678 // Mixin constructors
7679 OO.ui.LabelElement.call( this, config );
7680
7681 // Properties
7682 this.$field = this.$( '<div>' );
7683 this.$body = this.$( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7684 this.align = null;
7685 if ( config.help ) {
7686 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7687 $: this.$,
7688 classes: [ 'oo-ui-fieldLayout-help' ],
7689 framed: false,
7690 icon: 'info'
7691 } );
7692
7693 this.popupButtonWidget.getPopup().$body.append(
7694 this.$( '<div>' )
7695 .text( config.help )
7696 .addClass( 'oo-ui-fieldLayout-help-content' )
7697 );
7698 this.$help = this.popupButtonWidget.$element;
7699 } else {
7700 this.$help = this.$( [] );
7701 }
7702
7703 // Events
7704 if ( hasInputWidget ) {
7705 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7706 }
7707 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7708
7709 // Initialization
7710 this.$element
7711 .addClass( 'oo-ui-fieldLayout' )
7712 .append( this.$help, this.$body );
7713 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7714 this.$field
7715 .addClass( 'oo-ui-fieldLayout-field' )
7716 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7717 .append( this.fieldWidget.$element );
7718
7719 this.setAlignment( config.align );
7720 };
7721
7722 /* Setup */
7723
7724 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7725 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7726
7727 /* Methods */
7728
7729 /**
7730 * Handle field disable events.
7731 *
7732 * @param {boolean} value Field is disabled
7733 */
7734 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7735 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7736 };
7737
7738 /**
7739 * Handle label mouse click events.
7740 *
7741 * @param {jQuery.Event} e Mouse click event
7742 */
7743 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7744 this.fieldWidget.simulateLabelClick();
7745 return false;
7746 };
7747
7748 /**
7749 * Get the field.
7750 *
7751 * @return {OO.ui.Widget} Field widget
7752 */
7753 OO.ui.FieldLayout.prototype.getField = function () {
7754 return this.fieldWidget;
7755 };
7756
7757 /**
7758 * Set the field alignment mode.
7759 *
7760 * @private
7761 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7762 * @chainable
7763 */
7764 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7765 if ( value !== this.align ) {
7766 // Default to 'left'
7767 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7768 value = 'left';
7769 }
7770 // Reorder elements
7771 if ( value === 'inline' ) {
7772 this.$body.append( this.$field, this.$label );
7773 } else {
7774 this.$body.append( this.$label, this.$field );
7775 }
7776 // Set classes. The following classes can be used here:
7777 // * oo-ui-fieldLayout-align-left
7778 // * oo-ui-fieldLayout-align-right
7779 // * oo-ui-fieldLayout-align-top
7780 // * oo-ui-fieldLayout-align-inline
7781 if ( this.align ) {
7782 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7783 }
7784 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7785 this.align = value;
7786 }
7787
7788 return this;
7789 };
7790
7791 /**
7792 * Layout made of a field, a button, and an optional label.
7793 *
7794 * @class
7795 * @extends OO.ui.FieldLayout
7796 *
7797 * @constructor
7798 * @param {OO.ui.Widget} fieldWidget Field widget
7799 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7800 * @param {Object} [config] Configuration options
7801 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7802 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7803 */
7804 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
7805 // Configuration initialization
7806 config = $.extend( { align: 'left' }, config );
7807
7808 // Properties (must be set before parent constructor, which calls #getTagName)
7809 this.fieldWidget = fieldWidget;
7810 this.buttonWidget = buttonWidget;
7811
7812 // Parent constructor
7813 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
7814
7815 // Mixin constructors
7816 OO.ui.LabelElement.call( this, config );
7817
7818 // Properties
7819 this.$button = this.$( '<div>' )
7820 .addClass( 'oo-ui-actionFieldLayout-button' )
7821 .append( this.buttonWidget.$element );
7822
7823 this.$input = this.$( '<div>' )
7824 .addClass( 'oo-ui-actionFieldLayout-input' )
7825 .append( this.fieldWidget.$element );
7826
7827 this.$field
7828 .addClass( 'oo-ui-actionFieldLayout' )
7829 .append( this.$input, this.$button );
7830 };
7831
7832 /* Setup */
7833
7834 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
7835
7836 /**
7837 * Layout made of a fieldset and optional legend.
7838 *
7839 * Just add OO.ui.FieldLayout items.
7840 *
7841 * @class
7842 * @extends OO.ui.Layout
7843 * @mixins OO.ui.IconElement
7844 * @mixins OO.ui.LabelElement
7845 * @mixins OO.ui.GroupElement
7846 *
7847 * @constructor
7848 * @param {Object} [config] Configuration options
7849 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7850 */
7851 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
7852 // Configuration initialization
7853 config = config || {};
7854
7855 // Parent constructor
7856 OO.ui.FieldsetLayout.super.call( this, config );
7857
7858 // Mixin constructors
7859 OO.ui.IconElement.call( this, config );
7860 OO.ui.LabelElement.call( this, config );
7861 OO.ui.GroupElement.call( this, config );
7862
7863 if ( config.help ) {
7864 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7865 $: this.$,
7866 classes: [ 'oo-ui-fieldsetLayout-help' ],
7867 framed: false,
7868 icon: 'info'
7869 } );
7870
7871 this.popupButtonWidget.getPopup().$body.append(
7872 this.$( '<div>' )
7873 .text( config.help )
7874 .addClass( 'oo-ui-fieldsetLayout-help-content' )
7875 );
7876 this.$help = this.popupButtonWidget.$element;
7877 } else {
7878 this.$help = this.$( [] );
7879 }
7880
7881 // Initialization
7882 this.$element
7883 .addClass( 'oo-ui-fieldsetLayout' )
7884 .prepend( this.$help, this.$icon, this.$label, this.$group );
7885 if ( $.isArray( config.items ) ) {
7886 this.addItems( config.items );
7887 }
7888 };
7889
7890 /* Setup */
7891
7892 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
7893 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
7894 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
7895 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
7896
7897 /**
7898 * Layout with an HTML form.
7899 *
7900 * @class
7901 * @extends OO.ui.Layout
7902 *
7903 * @constructor
7904 * @param {Object} [config] Configuration options
7905 * @cfg {string} [method] HTML form `method` attribute
7906 * @cfg {string} [action] HTML form `action` attribute
7907 * @cfg {string} [enctype] HTML form `enctype` attribute
7908 */
7909 OO.ui.FormLayout = function OoUiFormLayout( config ) {
7910 // Configuration initialization
7911 config = config || {};
7912
7913 // Parent constructor
7914 OO.ui.FormLayout.super.call( this, config );
7915
7916 // Events
7917 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
7918
7919 // Initialization
7920 this.$element
7921 .addClass( 'oo-ui-formLayout' )
7922 .attr( {
7923 method: config.method,
7924 action: config.action,
7925 enctype: config.enctype
7926 } );
7927 };
7928
7929 /* Setup */
7930
7931 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
7932
7933 /* Events */
7934
7935 /**
7936 * @event submit
7937 */
7938
7939 /* Static Properties */
7940
7941 OO.ui.FormLayout.static.tagName = 'form';
7942
7943 /* Methods */
7944
7945 /**
7946 * Handle form submit events.
7947 *
7948 * @param {jQuery.Event} e Submit event
7949 * @fires submit
7950 */
7951 OO.ui.FormLayout.prototype.onFormSubmit = function () {
7952 this.emit( 'submit' );
7953 return false;
7954 };
7955
7956 /**
7957 * Layout made of proportionally sized columns and rows.
7958 *
7959 * @class
7960 * @extends OO.ui.Layout
7961 *
7962 * @constructor
7963 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
7964 * @param {Object} [config] Configuration options
7965 * @cfg {number[]} [widths] Widths of columns as ratios
7966 * @cfg {number[]} [heights] Heights of rows as ratios
7967 */
7968 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
7969 var i, len, widths;
7970
7971 // Configuration initialization
7972 config = config || {};
7973
7974 // Parent constructor
7975 OO.ui.GridLayout.super.call( this, config );
7976
7977 // Properties
7978 this.panels = [];
7979 this.widths = [];
7980 this.heights = [];
7981
7982 // Initialization
7983 this.$element.addClass( 'oo-ui-gridLayout' );
7984 for ( i = 0, len = panels.length; i < len; i++ ) {
7985 this.panels.push( panels[ i ] );
7986 this.$element.append( panels[ i ].$element );
7987 }
7988 if ( config.widths || config.heights ) {
7989 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
7990 } else {
7991 // Arrange in columns by default
7992 widths = this.panels.map( function () { return 1; } );
7993 this.layout( widths, [ 1 ] );
7994 }
7995 };
7996
7997 /* Setup */
7998
7999 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
8000
8001 /* Events */
8002
8003 /**
8004 * @event layout
8005 */
8006
8007 /**
8008 * @event update
8009 */
8010
8011 /* Methods */
8012
8013 /**
8014 * Set grid dimensions.
8015 *
8016 * @param {number[]} widths Widths of columns as ratios
8017 * @param {number[]} heights Heights of rows as ratios
8018 * @fires layout
8019 * @throws {Error} If grid is not large enough to fit all panels
8020 */
8021 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
8022 var x, y,
8023 xd = 0,
8024 yd = 0,
8025 cols = widths.length,
8026 rows = heights.length;
8027
8028 // Verify grid is big enough to fit panels
8029 if ( cols * rows < this.panels.length ) {
8030 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
8031 }
8032
8033 // Sum up denominators
8034 for ( x = 0; x < cols; x++ ) {
8035 xd += widths[ x ];
8036 }
8037 for ( y = 0; y < rows; y++ ) {
8038 yd += heights[ y ];
8039 }
8040 // Store factors
8041 this.widths = [];
8042 this.heights = [];
8043 for ( x = 0; x < cols; x++ ) {
8044 this.widths[ x ] = widths[ x ] / xd;
8045 }
8046 for ( y = 0; y < rows; y++ ) {
8047 this.heights[ y ] = heights[ y ] / yd;
8048 }
8049 // Synchronize view
8050 this.update();
8051 this.emit( 'layout' );
8052 };
8053
8054 /**
8055 * Update panel positions and sizes.
8056 *
8057 * @fires update
8058 */
8059 OO.ui.GridLayout.prototype.update = function () {
8060 var x, y, panel, width, height, dimensions,
8061 i = 0,
8062 top = 0,
8063 left = 0,
8064 cols = this.widths.length,
8065 rows = this.heights.length;
8066
8067 for ( y = 0; y < rows; y++ ) {
8068 height = this.heights[ y ];
8069 for ( x = 0; x < cols; x++ ) {
8070 width = this.widths[ x ];
8071 panel = this.panels[ i ];
8072 dimensions = {
8073 width: ( width * 100 ) + '%',
8074 height: ( height * 100 ) + '%',
8075 top: ( top * 100 ) + '%'
8076 };
8077 // If RTL, reverse:
8078 if ( OO.ui.Element.static.getDir( this.$.context ) === 'rtl' ) {
8079 dimensions.right = ( left * 100 ) + '%';
8080 } else {
8081 dimensions.left = ( left * 100 ) + '%';
8082 }
8083 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
8084 if ( width === 0 || height === 0 ) {
8085 dimensions.visibility = 'hidden';
8086 } else {
8087 dimensions.visibility = '';
8088 }
8089 panel.$element.css( dimensions );
8090 i++;
8091 left += width;
8092 }
8093 top += height;
8094 left = 0;
8095 }
8096
8097 this.emit( 'update' );
8098 };
8099
8100 /**
8101 * Get a panel at a given position.
8102 *
8103 * The x and y position is affected by the current grid layout.
8104 *
8105 * @param {number} x Horizontal position
8106 * @param {number} y Vertical position
8107 * @return {OO.ui.PanelLayout} The panel at the given position
8108 */
8109 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
8110 return this.panels[ ( x * this.widths.length ) + y ];
8111 };
8112
8113 /**
8114 * Layout with a content and menu area.
8115 *
8116 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8117 * all remaining space.
8118 *
8119 * @class
8120 * @extends OO.ui.Layout
8121 *
8122 * @constructor
8123 * @param {Object} [config] Configuration options
8124 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8125 * @cfg {boolean} [showMenu=true] Show menu
8126 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
8127 * @cfg {boolean} [collapse] Collapse the menu out of view
8128 */
8129 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8130 var positions = this.constructor.static.menuPositions;
8131
8132 // Configuration initialization
8133 config = config || {};
8134
8135 // Parent constructor
8136 OO.ui.MenuLayout.super.call( this, config );
8137
8138 // Properties
8139 this.showMenu = config.showMenu !== false;
8140 this.menuSize = config.menuSize || '18em';
8141 this.menuPosition = positions[ config.menuPosition ] || positions.before;
8142
8143 /**
8144 * Menu DOM node
8145 *
8146 * @property {jQuery}
8147 */
8148 this.$menu = this.$( '<div>' );
8149 /**
8150 * Content DOM node
8151 *
8152 * @property {jQuery}
8153 */
8154 this.$content = this.$( '<div>' );
8155
8156 // Events
8157 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
8158
8159 // Initialization
8160 this.toggleMenu( this.showMenu );
8161 this.$menu
8162 .addClass( 'oo-ui-menuLayout-menu' )
8163 .css( this.menuPosition.sizeProperty, this.menuSize );
8164 this.$content.addClass( 'oo-ui-menuLayout-content' );
8165 this.$element
8166 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
8167 .append( this.$content, this.$menu );
8168 };
8169
8170 /* Setup */
8171
8172 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8173
8174 /* Static Properties */
8175
8176 OO.ui.MenuLayout.static.menuPositions = {
8177 top: {
8178 sizeProperty: 'height',
8179 positionProperty: 'top',
8180 className: 'oo-ui-menuLayout-top'
8181 },
8182 after: {
8183 sizeProperty: 'width',
8184 positionProperty: 'right',
8185 rtlPositionProperty: 'left',
8186 className: 'oo-ui-menuLayout-after'
8187 },
8188 bottom: {
8189 sizeProperty: 'height',
8190 positionProperty: 'bottom',
8191 className: 'oo-ui-menuLayout-bottom'
8192 },
8193 before: {
8194 sizeProperty: 'width',
8195 positionProperty: 'left',
8196 rtlPositionProperty: 'right',
8197 className: 'oo-ui-menuLayout-before'
8198 }
8199 };
8200
8201 /* Methods */
8202
8203 /**
8204 * Handle DOM attachment events
8205 */
8206 OO.ui.MenuLayout.prototype.onElementAttach = function () {
8207 // getPositionProperty won't know about directionality until the layout is attached
8208 if ( this.showMenu ) {
8209 this.$content.css( this.getPositionProperty(), this.menuSize );
8210 }
8211 };
8212
8213 /**
8214 * Toggle menu.
8215 *
8216 * @param {boolean} showMenu Show menu, omit to toggle
8217 * @chainable
8218 */
8219 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8220 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8221
8222 if ( this.showMenu !== showMenu ) {
8223 this.showMenu = showMenu;
8224 this.updateSizes();
8225 }
8226
8227 return this;
8228 };
8229
8230 /**
8231 * Check if menu is visible
8232 *
8233 * @return {boolean} Menu is visible
8234 */
8235 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8236 return this.showMenu;
8237 };
8238
8239 /**
8240 * Set menu size.
8241 *
8242 * @param {number|string} size Size of menu in pixels or any CSS unit
8243 * @chainable
8244 */
8245 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
8246 this.menuSize = size;
8247 this.updateSizes();
8248
8249 return this;
8250 };
8251
8252 /**
8253 * Update menu and content CSS based on current menu size and visibility
8254 */
8255 OO.ui.MenuLayout.prototype.updateSizes = function () {
8256 if ( this.showMenu ) {
8257 this.$menu
8258 .css( this.menuPosition.sizeProperty, this.menuSize )
8259 .css( 'overflow', '' );
8260 this.$content.css( this.getPositionProperty(), this.menuSize );
8261 } else {
8262 this.$menu
8263 .css( this.menuPosition.sizeProperty, 0 )
8264 .css( 'overflow', 'hidden' );
8265 this.$content.css( this.getPositionProperty(), 0 );
8266 }
8267 };
8268
8269 /**
8270 * Get menu size.
8271 *
8272 * @return {number|string} Menu size
8273 */
8274 OO.ui.MenuLayout.prototype.getMenuSize = function () {
8275 return this.menuSize;
8276 };
8277
8278 /**
8279 * Set menu position.
8280 *
8281 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8282 * @throws {Error} If position value is not supported
8283 * @chainable
8284 */
8285 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8286 var positionProperty, positions = this.constructor.static.menuPositions;
8287
8288 if ( !positions[ position ] ) {
8289 throw new Error( 'Cannot set position; unsupported position value: ' + position );
8290 }
8291
8292 positionProperty = this.getPositionProperty();
8293 this.$menu.css( this.menuPosition.sizeProperty, '' );
8294 this.$content.css( positionProperty, '' );
8295 this.$element.removeClass( this.menuPosition.className );
8296
8297 this.menuPosition = positions[ position ];
8298
8299 this.updateSizes();
8300 this.$element.addClass( this.menuPosition.className );
8301
8302 return this;
8303 };
8304
8305 /**
8306 * Get menu position.
8307 *
8308 * @return {string} Menu position
8309 */
8310 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8311 return this.menuPosition;
8312 };
8313
8314 /**
8315 * Get the menu position property.
8316 *
8317 * @return {string} Menu position CSS property
8318 */
8319 OO.ui.MenuLayout.prototype.getPositionProperty = function () {
8320 if ( this.menuPosition.rtlPositionProperty && this.$element.css( 'direction' ) === 'rtl' ) {
8321 return this.menuPosition.rtlPositionProperty;
8322 } else {
8323 return this.menuPosition.positionProperty;
8324 }
8325 };
8326
8327 /**
8328 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
8329 *
8330 * @class
8331 * @extends OO.ui.Layout
8332 *
8333 * @constructor
8334 * @param {Object} [config] Configuration options
8335 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8336 * @cfg {boolean} [padded=false] Pad the content from the edges
8337 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
8338 */
8339 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8340 // Configuration initialization
8341 config = $.extend( {
8342 scrollable: false,
8343 padded: false,
8344 expanded: true
8345 }, config );
8346
8347 // Parent constructor
8348 OO.ui.PanelLayout.super.call( this, config );
8349
8350 // Initialization
8351 this.$element.addClass( 'oo-ui-panelLayout' );
8352 if ( config.scrollable ) {
8353 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8354 }
8355 if ( config.padded ) {
8356 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8357 }
8358 if ( config.expanded ) {
8359 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8360 }
8361 };
8362
8363 /* Setup */
8364
8365 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8366
8367 /**
8368 * Page within an booklet layout.
8369 *
8370 * @class
8371 * @extends OO.ui.PanelLayout
8372 *
8373 * @constructor
8374 * @param {string} name Unique symbolic name of page
8375 * @param {Object} [config] Configuration options
8376 */
8377 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8378 // Configuration initialization
8379 config = $.extend( { scrollable: true }, config );
8380
8381 // Parent constructor
8382 OO.ui.PageLayout.super.call( this, config );
8383
8384 // Properties
8385 this.name = name;
8386 this.outlineItem = null;
8387 this.active = false;
8388
8389 // Initialization
8390 this.$element.addClass( 'oo-ui-pageLayout' );
8391 };
8392
8393 /* Setup */
8394
8395 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
8396
8397 /* Events */
8398
8399 /**
8400 * @event active
8401 * @param {boolean} active Page is active
8402 */
8403
8404 /* Methods */
8405
8406 /**
8407 * Get page name.
8408 *
8409 * @return {string} Symbolic name of page
8410 */
8411 OO.ui.PageLayout.prototype.getName = function () {
8412 return this.name;
8413 };
8414
8415 /**
8416 * Check if page is active.
8417 *
8418 * @return {boolean} Page is active
8419 */
8420 OO.ui.PageLayout.prototype.isActive = function () {
8421 return this.active;
8422 };
8423
8424 /**
8425 * Get outline item.
8426 *
8427 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8428 */
8429 OO.ui.PageLayout.prototype.getOutlineItem = function () {
8430 return this.outlineItem;
8431 };
8432
8433 /**
8434 * Set outline item.
8435 *
8436 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8437 * outline item as desired; this method is called for setting (with an object) and unsetting
8438 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8439 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8440 *
8441 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8442 * @chainable
8443 */
8444 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
8445 this.outlineItem = outlineItem || null;
8446 if ( outlineItem ) {
8447 this.setupOutlineItem();
8448 }
8449 return this;
8450 };
8451
8452 /**
8453 * Setup outline item.
8454 *
8455 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8456 *
8457 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8458 * @chainable
8459 */
8460 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
8461 return this;
8462 };
8463
8464 /**
8465 * Set page active state.
8466 *
8467 * @param {boolean} Page is active
8468 * @fires active
8469 */
8470 OO.ui.PageLayout.prototype.setActive = function ( active ) {
8471 active = !!active;
8472
8473 if ( active !== this.active ) {
8474 this.active = active;
8475 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
8476 this.emit( 'active', this.active );
8477 }
8478 };
8479
8480 /**
8481 * Layout containing a series of mutually exclusive pages.
8482 *
8483 * @class
8484 * @extends OO.ui.PanelLayout
8485 * @mixins OO.ui.GroupElement
8486 *
8487 * @constructor
8488 * @param {Object} [config] Configuration options
8489 * @cfg {boolean} [continuous=false] Show all pages, one after another
8490 * @cfg {OO.ui.Layout[]} [items] Layouts to add
8491 */
8492 OO.ui.StackLayout = function OoUiStackLayout( config ) {
8493 // Configuration initialization
8494 config = $.extend( { scrollable: true }, config );
8495
8496 // Parent constructor
8497 OO.ui.StackLayout.super.call( this, config );
8498
8499 // Mixin constructors
8500 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8501
8502 // Properties
8503 this.currentItem = null;
8504 this.continuous = !!config.continuous;
8505
8506 // Initialization
8507 this.$element.addClass( 'oo-ui-stackLayout' );
8508 if ( this.continuous ) {
8509 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
8510 }
8511 if ( $.isArray( config.items ) ) {
8512 this.addItems( config.items );
8513 }
8514 };
8515
8516 /* Setup */
8517
8518 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
8519 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
8520
8521 /* Events */
8522
8523 /**
8524 * @event set
8525 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
8526 */
8527
8528 /* Methods */
8529
8530 /**
8531 * Get the current item.
8532 *
8533 * @return {OO.ui.Layout|null}
8534 */
8535 OO.ui.StackLayout.prototype.getCurrentItem = function () {
8536 return this.currentItem;
8537 };
8538
8539 /**
8540 * Unset the current item.
8541 *
8542 * @private
8543 * @param {OO.ui.StackLayout} layout
8544 * @fires set
8545 */
8546 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
8547 var prevItem = this.currentItem;
8548 if ( prevItem === null ) {
8549 return;
8550 }
8551
8552 this.currentItem = null;
8553 this.emit( 'set', null );
8554 };
8555
8556 /**
8557 * Add items.
8558 *
8559 * Adding an existing item (by value) will move it.
8560 *
8561 * @param {OO.ui.Layout[]} items Items to add
8562 * @param {number} [index] Index to insert items after
8563 * @chainable
8564 */
8565 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
8566 // Mixin method
8567 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
8568
8569 if ( !this.currentItem && items.length ) {
8570 this.setItem( items[ 0 ] );
8571 }
8572
8573 return this;
8574 };
8575
8576 /**
8577 * Remove items.
8578 *
8579 * Items will be detached, not removed, so they can be used later.
8580 *
8581 * @param {OO.ui.Layout[]} items Items to remove
8582 * @chainable
8583 * @fires set
8584 */
8585 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
8586 // Mixin method
8587 OO.ui.GroupElement.prototype.removeItems.call( this, items );
8588
8589 if ( $.inArray( this.currentItem, items ) !== -1 ) {
8590 if ( this.items.length ) {
8591 this.setItem( this.items[ 0 ] );
8592 } else {
8593 this.unsetCurrentItem();
8594 }
8595 }
8596
8597 return this;
8598 };
8599
8600 /**
8601 * Clear all items.
8602 *
8603 * Items will be detached, not removed, so they can be used later.
8604 *
8605 * @chainable
8606 * @fires set
8607 */
8608 OO.ui.StackLayout.prototype.clearItems = function () {
8609 this.unsetCurrentItem();
8610 OO.ui.GroupElement.prototype.clearItems.call( this );
8611
8612 return this;
8613 };
8614
8615 /**
8616 * Show item.
8617 *
8618 * Any currently shown item will be hidden.
8619 *
8620 * FIXME: If the passed item to show has not been added in the items list, then
8621 * this method drops it and unsets the current item.
8622 *
8623 * @param {OO.ui.Layout} item Item to show
8624 * @chainable
8625 * @fires set
8626 */
8627 OO.ui.StackLayout.prototype.setItem = function ( item ) {
8628 var i, len;
8629
8630 if ( item !== this.currentItem ) {
8631 if ( !this.continuous ) {
8632 for ( i = 0, len = this.items.length; i < len; i++ ) {
8633 this.items[ i ].$element.css( 'display', '' );
8634 }
8635 }
8636 if ( $.inArray( item, this.items ) !== -1 ) {
8637 if ( !this.continuous ) {
8638 item.$element.css( 'display', 'block' );
8639 }
8640 this.currentItem = item;
8641 this.emit( 'set', item );
8642 } else {
8643 this.unsetCurrentItem();
8644 }
8645 }
8646
8647 return this;
8648 };
8649
8650 /**
8651 * Horizontal bar layout of tools as icon buttons.
8652 *
8653 * @class
8654 * @extends OO.ui.ToolGroup
8655 *
8656 * @constructor
8657 * @param {OO.ui.Toolbar} toolbar
8658 * @param {Object} [config] Configuration options
8659 */
8660 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
8661 // Parent constructor
8662 OO.ui.BarToolGroup.super.call( this, toolbar, config );
8663
8664 // Initialization
8665 this.$element.addClass( 'oo-ui-barToolGroup' );
8666 };
8667
8668 /* Setup */
8669
8670 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
8671
8672 /* Static Properties */
8673
8674 OO.ui.BarToolGroup.static.titleTooltips = true;
8675
8676 OO.ui.BarToolGroup.static.accelTooltips = true;
8677
8678 OO.ui.BarToolGroup.static.name = 'bar';
8679
8680 /**
8681 * Popup list of tools with an icon and optional label.
8682 *
8683 * @abstract
8684 * @class
8685 * @extends OO.ui.ToolGroup
8686 * @mixins OO.ui.IconElement
8687 * @mixins OO.ui.IndicatorElement
8688 * @mixins OO.ui.LabelElement
8689 * @mixins OO.ui.TitledElement
8690 * @mixins OO.ui.ClippableElement
8691 *
8692 * @constructor
8693 * @param {OO.ui.Toolbar} toolbar
8694 * @param {Object} [config] Configuration options
8695 * @cfg {string} [header] Text to display at the top of the pop-up
8696 */
8697 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
8698 // Configuration initialization
8699 config = config || {};
8700
8701 // Parent constructor
8702 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
8703
8704 // Mixin constructors
8705 OO.ui.IconElement.call( this, config );
8706 OO.ui.IndicatorElement.call( this, config );
8707 OO.ui.LabelElement.call( this, config );
8708 OO.ui.TitledElement.call( this, config );
8709 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
8710
8711 // Properties
8712 this.active = false;
8713 this.dragging = false;
8714 this.onBlurHandler = this.onBlur.bind( this );
8715 this.$handle = this.$( '<span>' );
8716
8717 // Events
8718 this.$handle.on( {
8719 'mousedown touchstart': this.onHandlePointerDown.bind( this ),
8720 'mouseup touchend': this.onHandlePointerUp.bind( this )
8721 } );
8722
8723 // Initialization
8724 this.$handle
8725 .addClass( 'oo-ui-popupToolGroup-handle' )
8726 .append( this.$icon, this.$label, this.$indicator );
8727 // If the pop-up should have a header, add it to the top of the toolGroup.
8728 // Note: If this feature is useful for other widgets, we could abstract it into an
8729 // OO.ui.HeaderedElement mixin constructor.
8730 if ( config.header !== undefined ) {
8731 this.$group
8732 .prepend( this.$( '<span>' )
8733 .addClass( 'oo-ui-popupToolGroup-header' )
8734 .text( config.header )
8735 );
8736 }
8737 this.$element
8738 .addClass( 'oo-ui-popupToolGroup' )
8739 .prepend( this.$handle );
8740 };
8741
8742 /* Setup */
8743
8744 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
8745 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
8746 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
8747 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
8748 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
8749 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
8750
8751 /* Static Properties */
8752
8753 /* Methods */
8754
8755 /**
8756 * @inheritdoc
8757 */
8758 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
8759 // Parent method
8760 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
8761
8762 if ( this.isDisabled() && this.isElementAttached() ) {
8763 this.setActive( false );
8764 }
8765 };
8766
8767 /**
8768 * Handle focus being lost.
8769 *
8770 * The event is actually generated from a mouseup, so it is not a normal blur event object.
8771 *
8772 * @param {jQuery.Event} e Mouse up event
8773 */
8774 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
8775 // Only deactivate when clicking outside the dropdown element
8776 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
8777 this.setActive( false );
8778 }
8779 };
8780
8781 /**
8782 * @inheritdoc
8783 */
8784 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
8785 // e.which is 0 for touch events, 1 for left mouse button
8786 // Only close toolgroup when a tool was actually selected
8787 // FIXME: this duplicates logic from the parent class
8788 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
8789 this.setActive( false );
8790 }
8791 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
8792 };
8793
8794 /**
8795 * Handle mouse up events.
8796 *
8797 * @param {jQuery.Event} e Mouse up event
8798 */
8799 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
8800 return false;
8801 };
8802
8803 /**
8804 * Handle mouse down events.
8805 *
8806 * @param {jQuery.Event} e Mouse down event
8807 */
8808 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
8809 // e.which is 0 for touch events, 1 for left mouse button
8810 if ( !this.isDisabled() && e.which <= 1 ) {
8811 this.setActive( !this.active );
8812 }
8813 return false;
8814 };
8815
8816 /**
8817 * Switch into active mode.
8818 *
8819 * When active, mouseup events anywhere in the document will trigger deactivation.
8820 */
8821 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
8822 value = !!value;
8823 if ( this.active !== value ) {
8824 this.active = value;
8825 if ( value ) {
8826 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
8827
8828 // Try anchoring the popup to the left first
8829 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
8830 this.toggleClipping( true );
8831 if ( this.isClippedHorizontally() ) {
8832 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
8833 this.toggleClipping( false );
8834 this.$element
8835 .removeClass( 'oo-ui-popupToolGroup-left' )
8836 .addClass( 'oo-ui-popupToolGroup-right' );
8837 this.toggleClipping( true );
8838 }
8839 } else {
8840 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
8841 this.$element.removeClass(
8842 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
8843 );
8844 this.toggleClipping( false );
8845 }
8846 }
8847 };
8848
8849 /**
8850 * Drop down list layout of tools as labeled icon buttons.
8851 *
8852 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
8853 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
8854 * may want to use the 'promote' and 'demote' configuration options to achieve this.
8855 *
8856 * @class
8857 * @extends OO.ui.PopupToolGroup
8858 *
8859 * @constructor
8860 * @param {OO.ui.Toolbar} toolbar
8861 * @param {Object} [config] Configuration options
8862 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
8863 * shown.
8864 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
8865 * allowed to be collapsed.
8866 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
8867 */
8868 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
8869 // Configuration initialization
8870 config = config || {};
8871
8872 // Properties (must be set before parent constructor, which calls #populate)
8873 this.allowCollapse = config.allowCollapse;
8874 this.forceExpand = config.forceExpand;
8875 this.expanded = config.expanded !== undefined ? config.expanded : false;
8876 this.collapsibleTools = [];
8877
8878 // Parent constructor
8879 OO.ui.ListToolGroup.super.call( this, toolbar, config );
8880
8881 // Initialization
8882 this.$element.addClass( 'oo-ui-listToolGroup' );
8883 };
8884
8885 /* Setup */
8886
8887 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
8888
8889 /* Static Properties */
8890
8891 OO.ui.ListToolGroup.static.accelTooltips = true;
8892
8893 OO.ui.ListToolGroup.static.name = 'list';
8894
8895 /* Methods */
8896
8897 /**
8898 * @inheritdoc
8899 */
8900 OO.ui.ListToolGroup.prototype.populate = function () {
8901 var i, len, allowCollapse = [];
8902
8903 OO.ui.ListToolGroup.super.prototype.populate.call( this );
8904
8905 // Update the list of collapsible tools
8906 if ( this.allowCollapse !== undefined ) {
8907 allowCollapse = this.allowCollapse;
8908 } else if ( this.forceExpand !== undefined ) {
8909 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
8910 }
8911
8912 this.collapsibleTools = [];
8913 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
8914 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
8915 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
8916 }
8917 }
8918
8919 // Keep at the end, even when tools are added
8920 this.$group.append( this.getExpandCollapseTool().$element );
8921
8922 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
8923
8924 // Calling jQuery's .hide() and then .show() on a detached element caches the default value of its
8925 // 'display' attribute and restores it, and the tool uses a <span> and can be hidden and re-shown.
8926 // Is this a jQuery bug? http://jsfiddle.net/gtj4hu3h/
8927 if ( this.getExpandCollapseTool().$element.css( 'display' ) === 'inline' ) {
8928 this.getExpandCollapseTool().$element.css( 'display', 'block' );
8929 }
8930
8931 this.updateCollapsibleState();
8932 };
8933
8934 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
8935 if ( this.expandCollapseTool === undefined ) {
8936 var ExpandCollapseTool = function () {
8937 ExpandCollapseTool.super.apply( this, arguments );
8938 };
8939
8940 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
8941
8942 ExpandCollapseTool.prototype.onSelect = function () {
8943 this.toolGroup.expanded = !this.toolGroup.expanded;
8944 this.toolGroup.updateCollapsibleState();
8945 this.setActive( false );
8946 };
8947 ExpandCollapseTool.prototype.onUpdateState = function () {
8948 // Do nothing. Tool interface requires an implementation of this function.
8949 };
8950
8951 ExpandCollapseTool.static.name = 'more-fewer';
8952
8953 this.expandCollapseTool = new ExpandCollapseTool( this );
8954 }
8955 return this.expandCollapseTool;
8956 };
8957
8958 /**
8959 * @inheritdoc
8960 */
8961 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
8962 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
8963
8964 // Do not close the popup when the user wants to show more/fewer tools
8965 if ( this.$( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
8966 // Prevent the popup list from being hidden
8967 this.setActive( true );
8968 }
8969
8970 return ret;
8971 };
8972
8973 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
8974 var i, len;
8975
8976 this.getExpandCollapseTool()
8977 .setIcon( this.expanded ? 'collapse' : 'expand' )
8978 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
8979
8980 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
8981 this.collapsibleTools[ i ].toggle( this.expanded );
8982 }
8983 };
8984
8985 /**
8986 * Drop down menu layout of tools as selectable menu items.
8987 *
8988 * @class
8989 * @extends OO.ui.PopupToolGroup
8990 *
8991 * @constructor
8992 * @param {OO.ui.Toolbar} toolbar
8993 * @param {Object} [config] Configuration options
8994 */
8995 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
8996 // Configuration initialization
8997 config = config || {};
8998
8999 // Parent constructor
9000 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9001
9002 // Events
9003 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9004
9005 // Initialization
9006 this.$element.addClass( 'oo-ui-menuToolGroup' );
9007 };
9008
9009 /* Setup */
9010
9011 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9012
9013 /* Static Properties */
9014
9015 OO.ui.MenuToolGroup.static.accelTooltips = true;
9016
9017 OO.ui.MenuToolGroup.static.name = 'menu';
9018
9019 /* Methods */
9020
9021 /**
9022 * Handle the toolbar state being updated.
9023 *
9024 * When the state changes, the title of each active item in the menu will be joined together and
9025 * used as a label for the group. The label will be empty if none of the items are active.
9026 */
9027 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9028 var name,
9029 labelTexts = [];
9030
9031 for ( name in this.tools ) {
9032 if ( this.tools[ name ].isActive() ) {
9033 labelTexts.push( this.tools[ name ].getTitle() );
9034 }
9035 }
9036
9037 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9038 };
9039
9040 /**
9041 * Tool that shows a popup when selected.
9042 *
9043 * @abstract
9044 * @class
9045 * @extends OO.ui.Tool
9046 * @mixins OO.ui.PopupElement
9047 *
9048 * @constructor
9049 * @param {OO.ui.Toolbar} toolbar
9050 * @param {Object} [config] Configuration options
9051 */
9052 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
9053 // Parent constructor
9054 OO.ui.PopupTool.super.call( this, toolbar, config );
9055
9056 // Mixin constructors
9057 OO.ui.PopupElement.call( this, config );
9058
9059 // Initialization
9060 this.$element
9061 .addClass( 'oo-ui-popupTool' )
9062 .append( this.popup.$element );
9063 };
9064
9065 /* Setup */
9066
9067 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9068 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9069
9070 /* Methods */
9071
9072 /**
9073 * Handle the tool being selected.
9074 *
9075 * @inheritdoc
9076 */
9077 OO.ui.PopupTool.prototype.onSelect = function () {
9078 if ( !this.isDisabled() ) {
9079 this.popup.toggle();
9080 }
9081 this.setActive( false );
9082 return false;
9083 };
9084
9085 /**
9086 * Handle the toolbar state being updated.
9087 *
9088 * @inheritdoc
9089 */
9090 OO.ui.PopupTool.prototype.onUpdateState = function () {
9091 this.setActive( false );
9092 };
9093
9094 /**
9095 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9096 *
9097 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9098 *
9099 * @abstract
9100 * @class
9101 * @extends OO.ui.GroupElement
9102 *
9103 * @constructor
9104 * @param {Object} [config] Configuration options
9105 */
9106 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9107 // Parent constructor
9108 OO.ui.GroupWidget.super.call( this, config );
9109 };
9110
9111 /* Setup */
9112
9113 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9114
9115 /* Methods */
9116
9117 /**
9118 * Set the disabled state of the widget.
9119 *
9120 * This will also update the disabled state of child widgets.
9121 *
9122 * @param {boolean} disabled Disable widget
9123 * @chainable
9124 */
9125 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9126 var i, len;
9127
9128 // Parent method
9129 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9130 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9131
9132 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9133 if ( this.items ) {
9134 for ( i = 0, len = this.items.length; i < len; i++ ) {
9135 this.items[ i ].updateDisabled();
9136 }
9137 }
9138
9139 return this;
9140 };
9141
9142 /**
9143 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9144 *
9145 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9146 * allows bidirectional communication.
9147 *
9148 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9149 *
9150 * @abstract
9151 * @class
9152 *
9153 * @constructor
9154 */
9155 OO.ui.ItemWidget = function OoUiItemWidget() {
9156 //
9157 };
9158
9159 /* Methods */
9160
9161 /**
9162 * Check if widget is disabled.
9163 *
9164 * Checks parent if present, making disabled state inheritable.
9165 *
9166 * @return {boolean} Widget is disabled
9167 */
9168 OO.ui.ItemWidget.prototype.isDisabled = function () {
9169 return this.disabled ||
9170 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9171 };
9172
9173 /**
9174 * Set group element is in.
9175 *
9176 * @param {OO.ui.GroupElement|null} group Group element, null if none
9177 * @chainable
9178 */
9179 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
9180 // Parent method
9181 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9182 OO.ui.Element.prototype.setElementGroup.call( this, group );
9183
9184 // Initialize item disabled states
9185 this.updateDisabled();
9186
9187 return this;
9188 };
9189
9190 /**
9191 * Mixin that adds a menu showing suggested values for a text input.
9192 *
9193 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
9194 *
9195 * Subclasses that set the value of #lookupInput from their `choose` or `select` handler should
9196 * be aware that this will cause new suggestions to be looked up for the new value. If this is
9197 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
9198 *
9199 * @class
9200 * @abstract
9201 * @deprecated Use LookupElement instead.
9202 *
9203 * @constructor
9204 * @param {OO.ui.TextInputWidget} input Input widget
9205 * @param {Object} [config] Configuration options
9206 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
9207 * @cfg {jQuery} [$container=input.$element] Element to render menu under
9208 */
9209 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
9210 // Configuration initialization
9211 config = config || {};
9212
9213 // Properties
9214 this.lookupInput = input;
9215 this.$overlay = config.$overlay || this.$element;
9216 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
9217 $: OO.ui.Element.static.getJQuery( this.$overlay ),
9218 input: this.lookupInput,
9219 $container: config.$container
9220 } );
9221 this.lookupCache = {};
9222 this.lookupQuery = null;
9223 this.lookupRequest = null;
9224 this.lookupsDisabled = false;
9225 this.lookupInputFocused = false;
9226
9227 // Events
9228 this.lookupInput.$input.on( {
9229 focus: this.onLookupInputFocus.bind( this ),
9230 blur: this.onLookupInputBlur.bind( this ),
9231 mousedown: this.onLookupInputMouseDown.bind( this )
9232 } );
9233 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
9234 this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle' } );
9235
9236 // Initialization
9237 this.$element.addClass( 'oo-ui-lookupWidget' );
9238 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
9239 this.$overlay.append( this.lookupMenu.$element );
9240 };
9241
9242 /* Methods */
9243
9244 /**
9245 * Handle input focus event.
9246 *
9247 * @param {jQuery.Event} e Input focus event
9248 */
9249 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
9250 this.lookupInputFocused = true;
9251 this.populateLookupMenu();
9252 };
9253
9254 /**
9255 * Handle input blur event.
9256 *
9257 * @param {jQuery.Event} e Input blur event
9258 */
9259 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
9260 this.closeLookupMenu();
9261 this.lookupInputFocused = false;
9262 };
9263
9264 /**
9265 * Handle input mouse down event.
9266 *
9267 * @param {jQuery.Event} e Input mouse down event
9268 */
9269 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
9270 // Only open the menu if the input was already focused.
9271 // This way we allow the user to open the menu again after closing it with Esc
9272 // by clicking in the input. Opening (and populating) the menu when initially
9273 // clicking into the input is handled by the focus handler.
9274 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
9275 this.populateLookupMenu();
9276 }
9277 };
9278
9279 /**
9280 * Handle input change event.
9281 *
9282 * @param {string} value New input value
9283 */
9284 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
9285 if ( this.lookupInputFocused ) {
9286 this.populateLookupMenu();
9287 }
9288 };
9289
9290 /**
9291 * Handle the lookup menu being shown/hidden.
9292 * @param {boolean} visible Whether the lookup menu is now visible.
9293 */
9294 OO.ui.LookupInputWidget.prototype.onLookupMenuToggle = function ( visible ) {
9295 if ( !visible ) {
9296 // When the menu is hidden, abort any active request and clear the menu.
9297 // This has to be done here in addition to closeLookupMenu(), because
9298 // MenuSelectWidget will close itself when the user presses Esc.
9299 this.abortLookupRequest();
9300 this.lookupMenu.clearItems();
9301 }
9302 };
9303
9304 /**
9305 * Get lookup menu.
9306 *
9307 * @return {OO.ui.TextInputMenuSelectWidget}
9308 */
9309 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
9310 return this.lookupMenu;
9311 };
9312
9313 /**
9314 * Disable or re-enable lookups.
9315 *
9316 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
9317 *
9318 * @param {boolean} disabled Disable lookups
9319 */
9320 OO.ui.LookupInputWidget.prototype.setLookupsDisabled = function ( disabled ) {
9321 this.lookupsDisabled = !!disabled;
9322 };
9323
9324 /**
9325 * Open the menu. If there are no entries in the menu, this does nothing.
9326 *
9327 * @chainable
9328 */
9329 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
9330 if ( !this.lookupMenu.isEmpty() ) {
9331 this.lookupMenu.toggle( true );
9332 }
9333 return this;
9334 };
9335
9336 /**
9337 * Close the menu, empty it, and abort any pending request.
9338 *
9339 * @chainable
9340 */
9341 OO.ui.LookupInputWidget.prototype.closeLookupMenu = function () {
9342 this.lookupMenu.toggle( false );
9343 this.abortLookupRequest();
9344 this.lookupMenu.clearItems();
9345 return this;
9346 };
9347
9348 /**
9349 * Request menu items based on the input's current value, and when they arrive,
9350 * populate the menu with these items and show the menu.
9351 *
9352 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
9353 *
9354 * @chainable
9355 */
9356 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
9357 var widget = this,
9358 value = this.lookupInput.getValue();
9359
9360 if ( this.lookupsDisabled ) {
9361 return;
9362 }
9363
9364 // If the input is empty, clear the menu
9365 if ( value === '' ) {
9366 this.closeLookupMenu();
9367 // Skip population if there is already a request pending for the current value
9368 } else if ( value !== this.lookupQuery ) {
9369 this.getLookupMenuItems()
9370 .done( function ( items ) {
9371 widget.lookupMenu.clearItems();
9372 if ( items.length ) {
9373 widget.lookupMenu
9374 .addItems( items )
9375 .toggle( true );
9376 widget.initializeLookupMenuSelection();
9377 } else {
9378 widget.lookupMenu.toggle( false );
9379 }
9380 } )
9381 .fail( function () {
9382 widget.lookupMenu.clearItems();
9383 } );
9384 }
9385
9386 return this;
9387 };
9388
9389 /**
9390 * Select and highlight the first selectable item in the menu.
9391 *
9392 * @chainable
9393 */
9394 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
9395 if ( !this.lookupMenu.getSelectedItem() ) {
9396 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
9397 }
9398 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
9399 };
9400
9401 /**
9402 * Get lookup menu items for the current query.
9403 *
9404 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
9405 * of the done event. If the request was aborted to make way for a subsequent request,
9406 * this promise will not be rejected: it will remain pending forever.
9407 */
9408 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
9409 var widget = this,
9410 value = this.lookupInput.getValue(),
9411 deferred = $.Deferred(),
9412 ourRequest;
9413
9414 this.abortLookupRequest();
9415 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
9416 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[ value ] ) );
9417 } else {
9418 this.lookupInput.pushPending();
9419 this.lookupQuery = value;
9420 ourRequest = this.lookupRequest = this.getLookupRequest();
9421 ourRequest
9422 .always( function () {
9423 // We need to pop pending even if this is an old request, otherwise
9424 // the widget will remain pending forever.
9425 // TODO: this assumes that an aborted request will fail or succeed soon after
9426 // being aborted, or at least eventually. It would be nice if we could popPending()
9427 // at abort time, but only if we knew that we hadn't already called popPending()
9428 // for that request.
9429 widget.lookupInput.popPending();
9430 } )
9431 .done( function ( data ) {
9432 // If this is an old request (and aborting it somehow caused it to still succeed),
9433 // ignore its success completely
9434 if ( ourRequest === widget.lookupRequest ) {
9435 widget.lookupQuery = null;
9436 widget.lookupRequest = null;
9437 widget.lookupCache[ value ] = widget.getLookupCacheItemFromData( data );
9438 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[ value ] ) );
9439 }
9440 } )
9441 .fail( function () {
9442 // If this is an old request (or a request failing because it's being aborted),
9443 // ignore its failure completely
9444 if ( ourRequest === widget.lookupRequest ) {
9445 widget.lookupQuery = null;
9446 widget.lookupRequest = null;
9447 deferred.reject();
9448 }
9449 } );
9450 }
9451 return deferred.promise();
9452 };
9453
9454 /**
9455 * Abort the currently pending lookup request, if any.
9456 */
9457 OO.ui.LookupInputWidget.prototype.abortLookupRequest = function () {
9458 var oldRequest = this.lookupRequest;
9459 if ( oldRequest ) {
9460 // First unset this.lookupRequest to the fail handler will notice
9461 // that the request is no longer current
9462 this.lookupRequest = null;
9463 this.lookupQuery = null;
9464 oldRequest.abort();
9465 }
9466 };
9467
9468 /**
9469 * Get a new request object of the current lookup query value.
9470 *
9471 * @abstract
9472 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
9473 */
9474 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
9475 // Stub, implemented in subclass
9476 return null;
9477 };
9478
9479 /**
9480 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
9481 *
9482 * @abstract
9483 * @param {Mixed} data Cached result data, usually an array
9484 * @return {OO.ui.MenuOptionWidget[]} Menu items
9485 */
9486 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
9487 // Stub, implemented in subclass
9488 return [];
9489 };
9490
9491 /**
9492 * Get lookup cache item from server response data.
9493 *
9494 * @abstract
9495 * @param {Mixed} data Response from server
9496 * @return {Mixed} Cached result data
9497 */
9498 OO.ui.LookupInputWidget.prototype.getLookupCacheItemFromData = function () {
9499 // Stub, implemented in subclass
9500 return [];
9501 };
9502
9503 /**
9504 * Set of controls for an OO.ui.OutlineSelectWidget.
9505 *
9506 * Controls include moving items up and down, removing items, and adding different kinds of items.
9507 *
9508 * @class
9509 * @extends OO.ui.Widget
9510 * @mixins OO.ui.GroupElement
9511 * @mixins OO.ui.IconElement
9512 *
9513 * @constructor
9514 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9515 * @param {Object} [config] Configuration options
9516 */
9517 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9518 // Configuration initialization
9519 config = $.extend( { icon: 'add' }, config );
9520
9521 // Parent constructor
9522 OO.ui.OutlineControlsWidget.super.call( this, config );
9523
9524 // Mixin constructors
9525 OO.ui.GroupElement.call( this, config );
9526 OO.ui.IconElement.call( this, config );
9527
9528 // Properties
9529 this.outline = outline;
9530 this.$movers = this.$( '<div>' );
9531 this.upButton = new OO.ui.ButtonWidget( {
9532 $: this.$,
9533 framed: false,
9534 icon: 'collapse',
9535 title: OO.ui.msg( 'ooui-outline-control-move-up' )
9536 } );
9537 this.downButton = new OO.ui.ButtonWidget( {
9538 $: this.$,
9539 framed: false,
9540 icon: 'expand',
9541 title: OO.ui.msg( 'ooui-outline-control-move-down' )
9542 } );
9543 this.removeButton = new OO.ui.ButtonWidget( {
9544 $: this.$,
9545 framed: false,
9546 icon: 'remove',
9547 title: OO.ui.msg( 'ooui-outline-control-remove' )
9548 } );
9549
9550 // Events
9551 outline.connect( this, {
9552 select: 'onOutlineChange',
9553 add: 'onOutlineChange',
9554 remove: 'onOutlineChange'
9555 } );
9556 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
9557 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
9558 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
9559
9560 // Initialization
9561 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
9562 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
9563 this.$movers
9564 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9565 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
9566 this.$element.append( this.$icon, this.$group, this.$movers );
9567 };
9568
9569 /* Setup */
9570
9571 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
9572 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
9573 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
9574
9575 /* Events */
9576
9577 /**
9578 * @event move
9579 * @param {number} places Number of places to move
9580 */
9581
9582 /**
9583 * @event remove
9584 */
9585
9586 /* Methods */
9587
9588 /**
9589 * Handle outline change events.
9590 */
9591 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
9592 var i, len, firstMovable, lastMovable,
9593 items = this.outline.getItems(),
9594 selectedItem = this.outline.getSelectedItem(),
9595 movable = selectedItem && selectedItem.isMovable(),
9596 removable = selectedItem && selectedItem.isRemovable();
9597
9598 if ( movable ) {
9599 i = -1;
9600 len = items.length;
9601 while ( ++i < len ) {
9602 if ( items[ i ].isMovable() ) {
9603 firstMovable = items[ i ];
9604 break;
9605 }
9606 }
9607 i = len;
9608 while ( i-- ) {
9609 if ( items[ i ].isMovable() ) {
9610 lastMovable = items[ i ];
9611 break;
9612 }
9613 }
9614 }
9615 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
9616 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
9617 this.removeButton.setDisabled( !removable );
9618 };
9619
9620 /**
9621 * Mixin for widgets with a boolean on/off state.
9622 *
9623 * @abstract
9624 * @class
9625 *
9626 * @constructor
9627 * @param {Object} [config] Configuration options
9628 * @cfg {boolean} [value=false] Initial value
9629 */
9630 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
9631 // Configuration initialization
9632 config = config || {};
9633
9634 // Properties
9635 this.value = null;
9636
9637 // Initialization
9638 this.$element.addClass( 'oo-ui-toggleWidget' );
9639 this.setValue( !!config.value );
9640 };
9641
9642 /* Events */
9643
9644 /**
9645 * @event change
9646 * @param {boolean} value Changed value
9647 */
9648
9649 /* Methods */
9650
9651 /**
9652 * Get the value of the toggle.
9653 *
9654 * @return {boolean}
9655 */
9656 OO.ui.ToggleWidget.prototype.getValue = function () {
9657 return this.value;
9658 };
9659
9660 /**
9661 * Set the value of the toggle.
9662 *
9663 * @param {boolean} value New value
9664 * @fires change
9665 * @chainable
9666 */
9667 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
9668 value = !!value;
9669 if ( this.value !== value ) {
9670 this.value = value;
9671 this.emit( 'change', value );
9672 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
9673 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
9674 this.$element.attr( 'aria-checked', value.toString() );
9675 }
9676 return this;
9677 };
9678
9679 /**
9680 * Group widget for multiple related buttons.
9681 *
9682 * Use together with OO.ui.ButtonWidget.
9683 *
9684 * @class
9685 * @extends OO.ui.Widget
9686 * @mixins OO.ui.GroupElement
9687 *
9688 * @constructor
9689 * @param {Object} [config] Configuration options
9690 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
9691 */
9692 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
9693 // Configuration initialization
9694 config = config || {};
9695
9696 // Parent constructor
9697 OO.ui.ButtonGroupWidget.super.call( this, config );
9698
9699 // Mixin constructors
9700 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9701
9702 // Initialization
9703 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
9704 if ( $.isArray( config.items ) ) {
9705 this.addItems( config.items );
9706 }
9707 };
9708
9709 /* Setup */
9710
9711 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
9712 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
9713
9714 /**
9715 * Generic widget for buttons.
9716 *
9717 * @class
9718 * @extends OO.ui.Widget
9719 * @mixins OO.ui.ButtonElement
9720 * @mixins OO.ui.IconElement
9721 * @mixins OO.ui.IndicatorElement
9722 * @mixins OO.ui.LabelElement
9723 * @mixins OO.ui.TitledElement
9724 * @mixins OO.ui.FlaggedElement
9725 * @mixins OO.ui.TabIndexedElement
9726 *
9727 * @constructor
9728 * @param {Object} [config] Configuration options
9729 * @cfg {string} [href] Hyperlink to visit when clicked
9730 * @cfg {string} [target] Target to open hyperlink in
9731 */
9732 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
9733 // Configuration initialization
9734 config = config || {};
9735
9736 // Parent constructor
9737 OO.ui.ButtonWidget.super.call( this, config );
9738
9739 // Mixin constructors
9740 OO.ui.ButtonElement.call( this, config );
9741 OO.ui.IconElement.call( this, config );
9742 OO.ui.IndicatorElement.call( this, config );
9743 OO.ui.LabelElement.call( this, config );
9744 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
9745 OO.ui.FlaggedElement.call( this, config );
9746 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
9747
9748 // Properties
9749 this.href = null;
9750 this.target = null;
9751 this.isHyperlink = false;
9752
9753 // Events
9754 this.$button.on( {
9755 click: this.onClick.bind( this ),
9756 keypress: this.onKeyPress.bind( this )
9757 } );
9758
9759 // Initialization
9760 this.$button.append( this.$icon, this.$label, this.$indicator );
9761 this.$element
9762 .addClass( 'oo-ui-buttonWidget' )
9763 .append( this.$button );
9764 this.setHref( config.href );
9765 this.setTarget( config.target );
9766 };
9767
9768 /* Setup */
9769
9770 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
9771 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
9772 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
9773 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
9774 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
9775 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
9776 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
9777 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
9778
9779 /* Events */
9780
9781 /**
9782 * @event click
9783 */
9784
9785 /* Methods */
9786
9787 /**
9788 * Handles mouse click events.
9789 *
9790 * @param {jQuery.Event} e Mouse click event
9791 * @fires click
9792 */
9793 OO.ui.ButtonWidget.prototype.onClick = function () {
9794 if ( !this.isDisabled() ) {
9795 this.emit( 'click' );
9796 if ( this.isHyperlink ) {
9797 return true;
9798 }
9799 }
9800 return false;
9801 };
9802
9803 /**
9804 * @inheritdoc
9805 */
9806 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
9807 // Remove the tab-index while the button is down to prevent the button from stealing focus
9808 this.$button.removeAttr( 'tabindex' );
9809 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
9810 // reliably reapply the tabindex and remove the pressed class
9811 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
9812
9813 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
9814 };
9815
9816 /**
9817 * @inheritdoc
9818 */
9819 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
9820 // Restore the tab-index after the button is up to restore the button's accessibility
9821 this.$button.attr( 'tabindex', this.tabIndex );
9822 // Stop listening for mouseup, since we only needed this once
9823 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
9824
9825 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
9826 };
9827
9828 /**
9829 * Handles keypress events.
9830 *
9831 * @param {jQuery.Event} e Keypress event
9832 * @fires click
9833 */
9834 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
9835 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
9836 this.emit( 'click' );
9837 if ( this.isHyperlink ) {
9838 return true;
9839 }
9840 }
9841 return false;
9842 };
9843
9844 /**
9845 * Get hyperlink location.
9846 *
9847 * @return {string} Hyperlink location
9848 */
9849 OO.ui.ButtonWidget.prototype.getHref = function () {
9850 return this.href;
9851 };
9852
9853 /**
9854 * Get hyperlink target.
9855 *
9856 * @return {string} Hyperlink target
9857 */
9858 OO.ui.ButtonWidget.prototype.getTarget = function () {
9859 return this.target;
9860 };
9861
9862 /**
9863 * Set hyperlink location.
9864 *
9865 * @param {string|null} href Hyperlink location, null to remove
9866 */
9867 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
9868 href = typeof href === 'string' ? href : null;
9869
9870 if ( href !== this.href ) {
9871 this.href = href;
9872 if ( href !== null ) {
9873 this.$button.attr( 'href', href );
9874 this.isHyperlink = true;
9875 } else {
9876 this.$button.removeAttr( 'href' );
9877 this.isHyperlink = false;
9878 }
9879 }
9880
9881 return this;
9882 };
9883
9884 /**
9885 * Set hyperlink target.
9886 *
9887 * @param {string|null} target Hyperlink target, null to remove
9888 */
9889 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
9890 target = typeof target === 'string' ? target : null;
9891
9892 if ( target !== this.target ) {
9893 this.target = target;
9894 if ( target !== null ) {
9895 this.$button.attr( 'target', target );
9896 } else {
9897 this.$button.removeAttr( 'target' );
9898 }
9899 }
9900
9901 return this;
9902 };
9903
9904 /**
9905 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
9906 *
9907 * @class
9908 * @extends OO.ui.ButtonWidget
9909 * @mixins OO.ui.PendingElement
9910 *
9911 * @constructor
9912 * @param {Object} [config] Configuration options
9913 * @cfg {string} [action] Symbolic action name
9914 * @cfg {string[]} [modes] Symbolic mode names
9915 * @cfg {boolean} [framed=false] Render button with a frame
9916 */
9917 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
9918 // Configuration initialization
9919 config = $.extend( { framed: false }, config );
9920
9921 // Parent constructor
9922 OO.ui.ActionWidget.super.call( this, config );
9923
9924 // Mixin constructors
9925 OO.ui.PendingElement.call( this, config );
9926
9927 // Properties
9928 this.action = config.action || '';
9929 this.modes = config.modes || [];
9930 this.width = 0;
9931 this.height = 0;
9932
9933 // Initialization
9934 this.$element.addClass( 'oo-ui-actionWidget' );
9935 };
9936
9937 /* Setup */
9938
9939 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
9940 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
9941
9942 /* Events */
9943
9944 /**
9945 * @event resize
9946 */
9947
9948 /* Methods */
9949
9950 /**
9951 * Check if action is available in a certain mode.
9952 *
9953 * @param {string} mode Name of mode
9954 * @return {boolean} Has mode
9955 */
9956 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
9957 return this.modes.indexOf( mode ) !== -1;
9958 };
9959
9960 /**
9961 * Get symbolic action name.
9962 *
9963 * @return {string}
9964 */
9965 OO.ui.ActionWidget.prototype.getAction = function () {
9966 return this.action;
9967 };
9968
9969 /**
9970 * Get symbolic action name.
9971 *
9972 * @return {string}
9973 */
9974 OO.ui.ActionWidget.prototype.getModes = function () {
9975 return this.modes.slice();
9976 };
9977
9978 /**
9979 * Emit a resize event if the size has changed.
9980 *
9981 * @chainable
9982 */
9983 OO.ui.ActionWidget.prototype.propagateResize = function () {
9984 var width, height;
9985
9986 if ( this.isElementAttached() ) {
9987 width = this.$element.width();
9988 height = this.$element.height();
9989
9990 if ( width !== this.width || height !== this.height ) {
9991 this.width = width;
9992 this.height = height;
9993 this.emit( 'resize' );
9994 }
9995 }
9996
9997 return this;
9998 };
9999
10000 /**
10001 * @inheritdoc
10002 */
10003 OO.ui.ActionWidget.prototype.setIcon = function () {
10004 // Mixin method
10005 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10006 this.propagateResize();
10007
10008 return this;
10009 };
10010
10011 /**
10012 * @inheritdoc
10013 */
10014 OO.ui.ActionWidget.prototype.setLabel = function () {
10015 // Mixin method
10016 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10017 this.propagateResize();
10018
10019 return this;
10020 };
10021
10022 /**
10023 * @inheritdoc
10024 */
10025 OO.ui.ActionWidget.prototype.setFlags = function () {
10026 // Mixin method
10027 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10028 this.propagateResize();
10029
10030 return this;
10031 };
10032
10033 /**
10034 * @inheritdoc
10035 */
10036 OO.ui.ActionWidget.prototype.clearFlags = function () {
10037 // Mixin method
10038 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10039 this.propagateResize();
10040
10041 return this;
10042 };
10043
10044 /**
10045 * Toggle visibility of button.
10046 *
10047 * @param {boolean} [show] Show button, omit to toggle visibility
10048 * @chainable
10049 */
10050 OO.ui.ActionWidget.prototype.toggle = function () {
10051 // Parent method
10052 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10053 this.propagateResize();
10054
10055 return this;
10056 };
10057
10058 /**
10059 * Button that shows and hides a popup.
10060 *
10061 * @class
10062 * @extends OO.ui.ButtonWidget
10063 * @mixins OO.ui.PopupElement
10064 *
10065 * @constructor
10066 * @param {Object} [config] Configuration options
10067 */
10068 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10069 // Parent constructor
10070 OO.ui.PopupButtonWidget.super.call( this, config );
10071
10072 // Mixin constructors
10073 OO.ui.PopupElement.call( this, config );
10074
10075 // Initialization
10076 this.$element
10077 .addClass( 'oo-ui-popupButtonWidget' )
10078 .attr( 'aria-haspopup', 'true' )
10079 .append( this.popup.$element );
10080 };
10081
10082 /* Setup */
10083
10084 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10085 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10086
10087 /* Methods */
10088
10089 /**
10090 * Handles mouse click events.
10091 *
10092 * @param {jQuery.Event} e Mouse click event
10093 */
10094 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
10095 // Skip clicks within the popup
10096 if ( $.contains( this.popup.$element[ 0 ], e.target ) ) {
10097 return;
10098 }
10099
10100 if ( !this.isDisabled() ) {
10101 this.popup.toggle();
10102 // Parent method
10103 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
10104 }
10105 return false;
10106 };
10107
10108 /**
10109 * Button that toggles on and off.
10110 *
10111 * @class
10112 * @extends OO.ui.ButtonWidget
10113 * @mixins OO.ui.ToggleWidget
10114 *
10115 * @constructor
10116 * @param {Object} [config] Configuration options
10117 * @cfg {boolean} [value=false] Initial value
10118 */
10119 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10120 // Configuration initialization
10121 config = config || {};
10122
10123 // Parent constructor
10124 OO.ui.ToggleButtonWidget.super.call( this, config );
10125
10126 // Mixin constructors
10127 OO.ui.ToggleWidget.call( this, config );
10128
10129 // Initialization
10130 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10131 };
10132
10133 /* Setup */
10134
10135 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10136 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10137
10138 /* Methods */
10139
10140 /**
10141 * @inheritdoc
10142 */
10143 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
10144 if ( !this.isDisabled() ) {
10145 this.setValue( !this.value );
10146 }
10147
10148 // Parent method
10149 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
10150 };
10151
10152 /**
10153 * @inheritdoc
10154 */
10155 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10156 value = !!value;
10157 if ( value !== this.value ) {
10158 this.$button.attr( 'aria-pressed', value.toString() );
10159 this.setActive( value );
10160 }
10161
10162 // Parent method (from mixin)
10163 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10164
10165 return this;
10166 };
10167
10168 /**
10169 * Dropdown menu of options.
10170 *
10171 * Dropdown menus provide a control for accessing a menu and compose a menu within the widget, which
10172 * can be accessed using the #getMenu method.
10173 *
10174 * Use with OO.ui.MenuOptionWidget.
10175 *
10176 * @class
10177 * @extends OO.ui.Widget
10178 * @mixins OO.ui.IconElement
10179 * @mixins OO.ui.IndicatorElement
10180 * @mixins OO.ui.LabelElement
10181 * @mixins OO.ui.TitledElement
10182 *
10183 * @constructor
10184 * @param {Object} [config] Configuration options
10185 * @cfg {Object} [menu] Configuration options to pass to menu widget
10186 */
10187 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10188 // Configuration initialization
10189 config = $.extend( { indicator: 'down' }, config );
10190
10191 // Parent constructor
10192 OO.ui.DropdownWidget.super.call( this, config );
10193
10194 // Mixin constructors
10195 OO.ui.IconElement.call( this, config );
10196 OO.ui.IndicatorElement.call( this, config );
10197 OO.ui.LabelElement.call( this, config );
10198 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10199
10200 // Properties
10201 this.menu = new OO.ui.MenuSelectWidget( $.extend( { $: this.$, widget: this }, config.menu ) );
10202 this.$handle = this.$( '<span>' );
10203
10204 // Events
10205 this.$element.on( { click: this.onClick.bind( this ) } );
10206 this.menu.connect( this, { select: 'onMenuSelect' } );
10207
10208 // Initialization
10209 this.$handle
10210 .addClass( 'oo-ui-dropdownWidget-handle' )
10211 .append( this.$icon, this.$label, this.$indicator );
10212 this.$element
10213 .addClass( 'oo-ui-dropdownWidget' )
10214 .append( this.$handle, this.menu.$element );
10215 };
10216
10217 /* Setup */
10218
10219 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10220 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10221 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10222 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10223 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10224
10225 /* Methods */
10226
10227 /**
10228 * Get the menu.
10229 *
10230 * @return {OO.ui.MenuSelectWidget} Menu of widget
10231 */
10232 OO.ui.DropdownWidget.prototype.getMenu = function () {
10233 return this.menu;
10234 };
10235
10236 /**
10237 * Handles menu select events.
10238 *
10239 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10240 */
10241 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10242 var selectedLabel;
10243
10244 if ( !item ) {
10245 return;
10246 }
10247
10248 selectedLabel = item.getLabel();
10249
10250 // If the label is a DOM element, clone it, because setLabel will append() it
10251 if ( selectedLabel instanceof jQuery ) {
10252 selectedLabel = selectedLabel.clone();
10253 }
10254
10255 this.setLabel( selectedLabel );
10256 };
10257
10258 /**
10259 * Handles mouse click events.
10260 *
10261 * @param {jQuery.Event} e Mouse click event
10262 */
10263 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10264 // Skip clicks within the menu
10265 if ( $.contains( this.menu.$element[ 0 ], e.target ) ) {
10266 return;
10267 }
10268
10269 if ( !this.isDisabled() ) {
10270 if ( this.menu.isVisible() ) {
10271 this.menu.toggle( false );
10272 } else {
10273 this.menu.toggle( true );
10274 }
10275 }
10276 return false;
10277 };
10278
10279 /**
10280 * Icon widget.
10281 *
10282 * See OO.ui.IconElement for more information.
10283 *
10284 * @class
10285 * @extends OO.ui.Widget
10286 * @mixins OO.ui.IconElement
10287 * @mixins OO.ui.TitledElement
10288 *
10289 * @constructor
10290 * @param {Object} [config] Configuration options
10291 */
10292 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10293 // Configuration initialization
10294 config = config || {};
10295
10296 // Parent constructor
10297 OO.ui.IconWidget.super.call( this, config );
10298
10299 // Mixin constructors
10300 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10301 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10302
10303 // Initialization
10304 this.$element.addClass( 'oo-ui-iconWidget' );
10305 };
10306
10307 /* Setup */
10308
10309 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10310 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
10311 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
10312
10313 /* Static Properties */
10314
10315 OO.ui.IconWidget.static.tagName = 'span';
10316
10317 /**
10318 * Indicator widget.
10319 *
10320 * See OO.ui.IndicatorElement for more information.
10321 *
10322 * @class
10323 * @extends OO.ui.Widget
10324 * @mixins OO.ui.IndicatorElement
10325 * @mixins OO.ui.TitledElement
10326 *
10327 * @constructor
10328 * @param {Object} [config] Configuration options
10329 */
10330 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
10331 // Configuration initialization
10332 config = config || {};
10333
10334 // Parent constructor
10335 OO.ui.IndicatorWidget.super.call( this, config );
10336
10337 // Mixin constructors
10338 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
10339 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10340
10341 // Initialization
10342 this.$element.addClass( 'oo-ui-indicatorWidget' );
10343 };
10344
10345 /* Setup */
10346
10347 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
10348 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
10349 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
10350
10351 /* Static Properties */
10352
10353 OO.ui.IndicatorWidget.static.tagName = 'span';
10354
10355 /**
10356 * Base class for input widgets.
10357 *
10358 * @abstract
10359 * @class
10360 * @extends OO.ui.Widget
10361 * @mixins OO.ui.FlaggedElement
10362 * @mixins OO.ui.TabIndexedElement
10363 *
10364 * @constructor
10365 * @param {Object} [config] Configuration options
10366 * @cfg {string} [name=''] HTML input name
10367 * @cfg {string} [value=''] Input value
10368 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
10369 */
10370 OO.ui.InputWidget = function OoUiInputWidget( config ) {
10371 // Configuration initialization
10372 config = config || {};
10373
10374 // Parent constructor
10375 OO.ui.InputWidget.super.call( this, config );
10376
10377 // Properties
10378 this.$input = this.getInputElement( config );
10379 this.value = '';
10380 this.inputFilter = config.inputFilter;
10381
10382 // Mixin constructors
10383 OO.ui.FlaggedElement.call( this, config );
10384 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
10385
10386 // Events
10387 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
10388
10389 // Initialization
10390 this.$input
10391 .attr( 'name', config.name )
10392 .prop( 'disabled', this.isDisabled() );
10393 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
10394 this.setValue( config.value );
10395 };
10396
10397 /* Setup */
10398
10399 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
10400 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
10401 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
10402
10403 /* Events */
10404
10405 /**
10406 * @event change
10407 * @param {string} value
10408 */
10409
10410 /* Methods */
10411
10412 /**
10413 * Get input element.
10414 *
10415 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10416 * different circumstances. The element must have a `value` property (like form elements).
10417 *
10418 * @private
10419 * @param {Object} config Configuration options
10420 * @return {jQuery} Input element
10421 */
10422 OO.ui.InputWidget.prototype.getInputElement = function () {
10423 return this.$( '<input>' );
10424 };
10425
10426 /**
10427 * Handle potentially value-changing events.
10428 *
10429 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10430 */
10431 OO.ui.InputWidget.prototype.onEdit = function () {
10432 var widget = this;
10433 if ( !this.isDisabled() ) {
10434 // Allow the stack to clear so the value will be updated
10435 setTimeout( function () {
10436 widget.setValue( widget.$input.val() );
10437 } );
10438 }
10439 };
10440
10441 /**
10442 * Get the value of the input.
10443 *
10444 * @return {string} Input value
10445 */
10446 OO.ui.InputWidget.prototype.getValue = function () {
10447 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10448 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10449 var value = this.$input.val();
10450 if ( this.value !== value ) {
10451 this.setValue( value );
10452 }
10453 return this.value;
10454 };
10455
10456 /**
10457 * Sets the direction of the current input, either RTL or LTR
10458 *
10459 * @param {boolean} isRTL
10460 */
10461 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
10462 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
10463 };
10464
10465 /**
10466 * Set the value of the input.
10467 *
10468 * @param {string} value New value
10469 * @fires change
10470 * @chainable
10471 */
10472 OO.ui.InputWidget.prototype.setValue = function ( value ) {
10473 value = this.cleanUpValue( value );
10474 // Update the DOM if it has changed. Note that with cleanUpValue, it
10475 // is possible for the DOM value to change without this.value changing.
10476 if ( this.$input.val() !== value ) {
10477 this.$input.val( value );
10478 }
10479 if ( this.value !== value ) {
10480 this.value = value;
10481 this.emit( 'change', this.value );
10482 }
10483 return this;
10484 };
10485
10486 /**
10487 * Clean up incoming value.
10488 *
10489 * Ensures value is a string, and converts undefined and null to empty string.
10490 *
10491 * @private
10492 * @param {string} value Original value
10493 * @return {string} Cleaned up value
10494 */
10495 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
10496 if ( value === undefined || value === null ) {
10497 return '';
10498 } else if ( this.inputFilter ) {
10499 return this.inputFilter( String( value ) );
10500 } else {
10501 return String( value );
10502 }
10503 };
10504
10505 /**
10506 * Simulate the behavior of clicking on a label bound to this input.
10507 */
10508 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
10509 if ( !this.isDisabled() ) {
10510 if ( this.$input.is( ':checkbox,:radio' ) ) {
10511 this.$input.click();
10512 } else if ( this.$input.is( ':input' ) ) {
10513 this.$input[ 0 ].focus();
10514 }
10515 }
10516 };
10517
10518 /**
10519 * @inheritdoc
10520 */
10521 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
10522 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
10523 if ( this.$input ) {
10524 this.$input.prop( 'disabled', this.isDisabled() );
10525 }
10526 return this;
10527 };
10528
10529 /**
10530 * Focus the input.
10531 *
10532 * @chainable
10533 */
10534 OO.ui.InputWidget.prototype.focus = function () {
10535 this.$input[ 0 ].focus();
10536 return this;
10537 };
10538
10539 /**
10540 * Blur the input.
10541 *
10542 * @chainable
10543 */
10544 OO.ui.InputWidget.prototype.blur = function () {
10545 this.$input[ 0 ].blur();
10546 return this;
10547 };
10548
10549 /**
10550 * A button that is an input widget. Intended to be used within a OO.ui.FormLayout.
10551 *
10552 * @class
10553 * @extends OO.ui.InputWidget
10554 * @mixins OO.ui.ButtonElement
10555 * @mixins OO.ui.IconElement
10556 * @mixins OO.ui.IndicatorElement
10557 * @mixins OO.ui.LabelElement
10558 * @mixins OO.ui.TitledElement
10559 * @mixins OO.ui.FlaggedElement
10560 *
10561 * @constructor
10562 * @param {Object} [config] Configuration options
10563 * @cfg {string} [type='button'] HTML tag `type` attribute, may be 'button', 'submit' or 'reset'
10564 * @cfg {boolean} [useInputTag=false] Whether to use `<input/>` rather than `<button/>`. Only useful
10565 * if you need IE 6 support in a form with multiple buttons. If you use this option, icons and
10566 * indicators will not be displayed, it won't be possible to have a non-plaintext label, and it
10567 * won't be possible to set a value (which will internally become identical to the label).
10568 */
10569 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
10570 // Configuration initialization
10571 config = $.extend( { type: 'button', useInputTag: false }, config );
10572
10573 // Properties (must be set before parent constructor, which calls #setValue)
10574 this.useInputTag = config.useInputTag;
10575
10576 // Parent constructor
10577 OO.ui.ButtonInputWidget.super.call( this, config );
10578
10579 // Mixin constructors
10580 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
10581 OO.ui.IconElement.call( this, config );
10582 OO.ui.IndicatorElement.call( this, config );
10583 OO.ui.LabelElement.call( this, config );
10584 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
10585 OO.ui.FlaggedElement.call( this, config );
10586
10587 // Events
10588 this.$input.on( {
10589 click: this.onClick.bind( this ),
10590 keypress: this.onKeyPress.bind( this )
10591 } );
10592
10593 // Initialization
10594 if ( !config.useInputTag ) {
10595 this.$input.append( this.$icon, this.$label, this.$indicator );
10596 }
10597 this.$element.addClass( 'oo-ui-buttonInputWidget' );
10598 };
10599
10600 /* Setup */
10601
10602 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
10603 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
10604 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
10605 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
10606 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
10607 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
10608 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
10609
10610 /* Events */
10611
10612 /**
10613 * @event click
10614 */
10615
10616 /* Methods */
10617
10618 /**
10619 * @inheritdoc
10620 * @private
10621 */
10622 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
10623 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
10624 return this.$( html );
10625 };
10626
10627 /**
10628 * Set label value.
10629 *
10630 * Overridden to support setting the 'value' of `<input/>` elements.
10631 *
10632 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
10633 * text; or null for no label
10634 * @chainable
10635 */
10636 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
10637 OO.ui.LabelElement.prototype.setLabel.call( this, label );
10638
10639 if ( this.useInputTag ) {
10640 if ( typeof label === 'function' ) {
10641 label = OO.ui.resolveMsg( label );
10642 }
10643 if ( label instanceof jQuery ) {
10644 label = label.text();
10645 }
10646 if ( !label ) {
10647 label = '';
10648 }
10649 this.$input.val( label );
10650 }
10651
10652 return this;
10653 };
10654
10655 /**
10656 * Set the value of the input.
10657 *
10658 * Overridden to disable for `<input/>` elements, which have value identical to the label.
10659 *
10660 * @param {string} value New value
10661 * @chainable
10662 */
10663 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
10664 if ( !this.useInputTag ) {
10665 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
10666 }
10667 return this;
10668 };
10669
10670 /**
10671 * Handles mouse click events.
10672 *
10673 * @param {jQuery.Event} e Mouse click event
10674 * @fires click
10675 */
10676 OO.ui.ButtonInputWidget.prototype.onClick = function () {
10677 if ( !this.isDisabled() ) {
10678 this.emit( 'click' );
10679 }
10680 return false;
10681 };
10682
10683 /**
10684 * Handles keypress events.
10685 *
10686 * @param {jQuery.Event} e Keypress event
10687 * @fires click
10688 */
10689 OO.ui.ButtonInputWidget.prototype.onKeyPress = function ( e ) {
10690 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10691 this.emit( 'click' );
10692 }
10693 return false;
10694 };
10695
10696 /**
10697 * Checkbox input widget.
10698 *
10699 * @class
10700 * @extends OO.ui.InputWidget
10701 *
10702 * @constructor
10703 * @param {Object} [config] Configuration options
10704 * @cfg {boolean} [selected=false] Whether the checkbox is initially selected
10705 */
10706 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
10707 // Parent constructor
10708 OO.ui.CheckboxInputWidget.super.call( this, config );
10709
10710 // Initialization
10711 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
10712 this.setSelected( config.selected !== undefined ? config.selected : false );
10713 };
10714
10715 /* Setup */
10716
10717 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
10718
10719 /* Methods */
10720
10721 /**
10722 * @inheritdoc
10723 * @private
10724 */
10725 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
10726 return this.$( '<input type="checkbox" />' );
10727 };
10728
10729 /**
10730 * @inheritdoc
10731 */
10732 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
10733 var widget = this;
10734 if ( !this.isDisabled() ) {
10735 // Allow the stack to clear so the value will be updated
10736 setTimeout( function () {
10737 widget.setSelected( widget.$input.prop( 'checked' ) );
10738 } );
10739 }
10740 };
10741
10742 /**
10743 * Set selection state of this checkbox.
10744 *
10745 * @param {boolean} state Whether the checkbox is selected
10746 * @chainable
10747 */
10748 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
10749 state = !!state;
10750 if ( this.selected !== state ) {
10751 this.selected = state;
10752 this.$input.prop( 'checked', this.selected );
10753 this.emit( 'change', this.selected );
10754 }
10755 return this;
10756 };
10757
10758 /**
10759 * Check if this checkbox is selected.
10760 *
10761 * @return {boolean} Checkbox is selected
10762 */
10763 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
10764 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10765 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10766 var selected = this.$input.prop( 'checked' );
10767 if ( this.selected !== selected ) {
10768 this.setSelected( selected );
10769 }
10770 return this.selected;
10771 };
10772
10773 /**
10774 * A OO.ui.DropdownWidget synchronized with a `<input type=hidden>` for form submission. Intended to
10775 * be used within a OO.ui.FormLayout.
10776 *
10777 * @class
10778 * @extends OO.ui.InputWidget
10779 *
10780 * @constructor
10781 * @param {Object} [config] Configuration options
10782 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10783 */
10784 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
10785 // Configuration initialization
10786 config = config || {};
10787
10788 // Properties (must be done before parent constructor which calls #setDisabled)
10789 this.dropdownWidget = new OO.ui.DropdownWidget( {
10790 $: this.$
10791 } );
10792
10793 // Parent constructor
10794 OO.ui.DropdownInputWidget.super.call( this, config );
10795
10796 // Events
10797 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
10798
10799 // Initialization
10800 this.setOptions( config.options || [] );
10801 this.$element
10802 .addClass( 'oo-ui-dropdownInputWidget' )
10803 .append( this.dropdownWidget.$element );
10804 };
10805
10806 /* Setup */
10807
10808 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
10809
10810 /* Methods */
10811
10812 /**
10813 * @inheritdoc
10814 * @private
10815 */
10816 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
10817 return this.$( '<input type="hidden">' );
10818 };
10819
10820 /**
10821 * Handles menu select events.
10822 *
10823 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10824 */
10825 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
10826 this.setValue( item.getData() );
10827 };
10828
10829 /**
10830 * @inheritdoc
10831 */
10832 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
10833 var item = this.dropdownWidget.getMenu().getItemFromData( value );
10834 if ( item ) {
10835 this.dropdownWidget.getMenu().selectItem( item );
10836 }
10837 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
10838 return this;
10839 };
10840
10841 /**
10842 * @inheritdoc
10843 */
10844 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
10845 this.dropdownWidget.setDisabled( state );
10846 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
10847 return this;
10848 };
10849
10850 /**
10851 * Set the options available for this input.
10852 *
10853 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10854 * @chainable
10855 */
10856 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
10857 var value = this.getValue();
10858
10859 // Rebuild the dropdown menu
10860 this.dropdownWidget.getMenu()
10861 .clearItems()
10862 .addItems( options.map( function ( opt ) {
10863 return new OO.ui.MenuOptionWidget( {
10864 data: opt.data,
10865 label: opt.label !== undefined ? opt.label : opt.data
10866 } );
10867 } ) );
10868
10869 // Restore the previous value, or reset to something sensible
10870 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
10871 // Previous value is still available, ensure consistency with the dropdown
10872 this.setValue( value );
10873 } else {
10874 // No longer valid, reset
10875 if ( options.length ) {
10876 this.setValue( options[ 0 ].data );
10877 }
10878 }
10879
10880 return this;
10881 };
10882
10883 /**
10884 * @inheritdoc
10885 */
10886 OO.ui.DropdownInputWidget.prototype.focus = function () {
10887 this.dropdownWidget.getMenu().toggle( true );
10888 return this;
10889 };
10890
10891 /**
10892 * @inheritdoc
10893 */
10894 OO.ui.DropdownInputWidget.prototype.blur = function () {
10895 this.dropdownWidget.getMenu().toggle( false );
10896 return this;
10897 };
10898
10899 /**
10900 * Radio input widget.
10901 *
10902 * Radio buttons only make sense as a set, and you probably want to use the OO.ui.RadioSelectWidget
10903 * class instead of using this class directly.
10904 *
10905 * @class
10906 * @extends OO.ui.InputWidget
10907 *
10908 * @constructor
10909 * @param {Object} [config] Configuration options
10910 * @cfg {boolean} [selected=false] Whether the radio button is initially selected
10911 */
10912 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
10913 // Parent constructor
10914 OO.ui.RadioInputWidget.super.call( this, config );
10915
10916 // Initialization
10917 this.$element.addClass( 'oo-ui-radioInputWidget' );
10918 this.setSelected( config.selected !== undefined ? config.selected : false );
10919 };
10920
10921 /* Setup */
10922
10923 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
10924
10925 /* Methods */
10926
10927 /**
10928 * @inheritdoc
10929 * @private
10930 */
10931 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
10932 return this.$( '<input type="radio" />' );
10933 };
10934
10935 /**
10936 * @inheritdoc
10937 */
10938 OO.ui.RadioInputWidget.prototype.onEdit = function () {
10939 // RadioInputWidget doesn't track its state.
10940 };
10941
10942 /**
10943 * Set selection state of this radio button.
10944 *
10945 * @param {boolean} state Whether the button is selected
10946 * @chainable
10947 */
10948 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
10949 // RadioInputWidget doesn't track its state.
10950 this.$input.prop( 'checked', state );
10951 return this;
10952 };
10953
10954 /**
10955 * Check if this radio button is selected.
10956 *
10957 * @return {boolean} Radio is selected
10958 */
10959 OO.ui.RadioInputWidget.prototype.isSelected = function () {
10960 return this.$input.prop( 'checked' );
10961 };
10962
10963 /**
10964 * Input widget with a text field.
10965 *
10966 * @class
10967 * @extends OO.ui.InputWidget
10968 * @mixins OO.ui.IconElement
10969 * @mixins OO.ui.IndicatorElement
10970 * @mixins OO.ui.PendingElement
10971 *
10972 * @constructor
10973 * @param {Object} [config] Configuration options
10974 * @cfg {string} [type='text'] HTML tag `type` attribute
10975 * @cfg {string} [placeholder] Placeholder text
10976 * @cfg {boolean} [autofocus=false] Ask the browser to focus this widget, using the 'autofocus' HTML
10977 * attribute
10978 * @cfg {boolean} [readOnly=false] Prevent changes
10979 * @cfg {number} [maxLength] Maximum allowed number of characters to input
10980 * @cfg {boolean} [multiline=false] Allow multiple lines of text
10981 * @cfg {boolean} [autosize=false] Automatically resize to fit content
10982 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
10983 * @cfg {string} [labelPosition='after'] Label position, 'before' or 'after'
10984 * @cfg {RegExp|string} [validate] Regular expression to validate against (or symbolic name referencing
10985 * one, see #static-validationPatterns)
10986 */
10987 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10988 // Configuration initialization
10989 config = $.extend( {
10990 type: 'text',
10991 labelPosition: 'after',
10992 maxRows: 10
10993 }, config );
10994
10995 // Parent constructor
10996 OO.ui.TextInputWidget.super.call( this, config );
10997
10998 // Mixin constructors
10999 OO.ui.IconElement.call( this, config );
11000 OO.ui.IndicatorElement.call( this, config );
11001 OO.ui.PendingElement.call( this, config );
11002 OO.ui.LabelElement.call( this, config );
11003
11004 // Properties
11005 this.readOnly = false;
11006 this.multiline = !!config.multiline;
11007 this.autosize = !!config.autosize;
11008 this.maxRows = config.maxRows;
11009 this.validate = null;
11010 this.attached = false;
11011
11012 // Clone for resizing
11013 if ( this.autosize ) {
11014 this.$clone = this.$input
11015 .clone()
11016 .insertAfter( this.$input )
11017 .hide();
11018 }
11019
11020 this.setValidation( config.validate );
11021 this.setPosition( config.labelPosition );
11022
11023 // Events
11024 this.$input.on( {
11025 keypress: this.onKeyPress.bind( this ),
11026 blur: this.setValidityFlag.bind( this )
11027 } );
11028 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
11029 this.$element.on( 'DOMNodeRemovedFromDocument', this.onElementDetach.bind( this ) );
11030 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11031 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11032 this.on( 'labelChange', this.updatePosition.bind( this ) );
11033
11034 // Initialization
11035 this.$element
11036 .addClass( 'oo-ui-textInputWidget' )
11037 .append( this.$icon, this.$indicator, this.$label );
11038 this.setReadOnly( !!config.readOnly );
11039 if ( config.placeholder ) {
11040 this.$input.attr( 'placeholder', config.placeholder );
11041 }
11042 if ( config.maxLength ) {
11043 this.$input.attr( 'maxlength', config.maxLength );
11044 }
11045 if ( config.autofocus ) {
11046 this.$input.attr( 'autofocus', 'autofocus' );
11047 }
11048 };
11049
11050 /* Setup */
11051
11052 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11053 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11054 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11055 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11056 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11057
11058 /* Static properties */
11059
11060 OO.ui.TextInputWidget.static.validationPatterns = {
11061 'non-empty': /.+/,
11062 integer: /^\d+$/
11063 };
11064
11065 /* Events */
11066
11067 /**
11068 * User presses enter inside the text box.
11069 *
11070 * Not called if input is multiline.
11071 *
11072 * @event enter
11073 */
11074
11075 /**
11076 * User clicks the icon.
11077 *
11078 * @event icon
11079 */
11080
11081 /**
11082 * User clicks the indicator.
11083 *
11084 * @event indicator
11085 */
11086
11087 /* Methods */
11088
11089 /**
11090 * Handle icon mouse down events.
11091 *
11092 * @param {jQuery.Event} e Mouse down event
11093 * @fires icon
11094 */
11095 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11096 if ( e.which === 1 ) {
11097 this.$input[ 0 ].focus();
11098 this.emit( 'icon' );
11099 return false;
11100 }
11101 };
11102
11103 /**
11104 * Handle indicator mouse down events.
11105 *
11106 * @param {jQuery.Event} e Mouse down event
11107 * @fires indicator
11108 */
11109 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11110 if ( e.which === 1 ) {
11111 this.$input[ 0 ].focus();
11112 this.emit( 'indicator' );
11113 return false;
11114 }
11115 };
11116
11117 /**
11118 * Handle key press events.
11119 *
11120 * @param {jQuery.Event} e Key press event
11121 * @fires enter If enter key is pressed and input is not multiline
11122 */
11123 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11124 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11125 this.emit( 'enter', e );
11126 }
11127 };
11128
11129 /**
11130 * Handle element attach events.
11131 *
11132 * @param {jQuery.Event} e Element attach event
11133 */
11134 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11135 this.attached = true;
11136 // If we reattached elsewhere, the valCache is now invalid
11137 this.valCache = null;
11138 this.adjustSize();
11139 this.positionLabel();
11140 };
11141
11142 /**
11143 * Handle element detach events.
11144 *
11145 * @param {jQuery.Event} e Element detach event
11146 */
11147 OO.ui.TextInputWidget.prototype.onElementDetach = function () {
11148 this.attached = false;
11149 };
11150
11151 /**
11152 * @inheritdoc
11153 */
11154 OO.ui.TextInputWidget.prototype.onEdit = function () {
11155 this.adjustSize();
11156
11157 // Parent method
11158 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11159 };
11160
11161 /**
11162 * @inheritdoc
11163 */
11164 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11165 // Parent method
11166 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11167
11168 this.setValidityFlag();
11169 this.adjustSize();
11170 return this;
11171 };
11172
11173 /**
11174 * Check if the widget is read-only.
11175 *
11176 * @return {boolean}
11177 */
11178 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11179 return this.readOnly;
11180 };
11181
11182 /**
11183 * Set the read-only state of the widget.
11184 *
11185 * This should probably change the widget's appearance and prevent it from being used.
11186 *
11187 * @param {boolean} state Make input read-only
11188 * @chainable
11189 */
11190 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11191 this.readOnly = !!state;
11192 this.$input.prop( 'readOnly', this.readOnly );
11193 return this;
11194 };
11195
11196 /**
11197 * Automatically adjust the size of the text input.
11198 *
11199 * This only affects multi-line inputs that are auto-sized.
11200 *
11201 * @chainable
11202 */
11203 OO.ui.TextInputWidget.prototype.adjustSize = function () {
11204 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
11205
11206 if ( this.multiline && this.autosize && this.attached && this.$input.val() !== this.valCache ) {
11207 this.$clone
11208 .val( this.$input.val() )
11209 .attr( 'rows', '' )
11210 // Set inline height property to 0 to measure scroll height
11211 .css( 'height', 0 );
11212
11213 this.$clone[ 0 ].style.display = 'block';
11214
11215 this.valCache = this.$input.val();
11216
11217 scrollHeight = this.$clone[ 0 ].scrollHeight;
11218
11219 // Remove inline height property to measure natural heights
11220 this.$clone.css( 'height', '' );
11221 innerHeight = this.$clone.innerHeight();
11222 outerHeight = this.$clone.outerHeight();
11223
11224 // Measure max rows height
11225 this.$clone
11226 .attr( 'rows', this.maxRows )
11227 .css( 'height', 'auto' )
11228 .val( '' );
11229 maxInnerHeight = this.$clone.innerHeight();
11230
11231 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11232 // Equals 1 on Blink-based browsers and 0 everywhere else
11233 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11234 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11235
11236 this.$clone[ 0 ].style.display = 'none';
11237
11238 // Only apply inline height when expansion beyond natural height is needed
11239 if ( idealHeight > innerHeight ) {
11240 // Use the difference between the inner and outer height as a buffer
11241 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
11242 } else {
11243 this.$input.css( 'height', '' );
11244 }
11245 }
11246 return this;
11247 };
11248
11249 /**
11250 * @inheritdoc
11251 * @private
11252 */
11253 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
11254 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="' + config.type + '" />' );
11255 };
11256
11257 /**
11258 * Check if input supports multiple lines.
11259 *
11260 * @return {boolean}
11261 */
11262 OO.ui.TextInputWidget.prototype.isMultiline = function () {
11263 return !!this.multiline;
11264 };
11265
11266 /**
11267 * Check if input automatically adjusts its size.
11268 *
11269 * @return {boolean}
11270 */
11271 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
11272 return !!this.autosize;
11273 };
11274
11275 /**
11276 * Select the contents of the input.
11277 *
11278 * @chainable
11279 */
11280 OO.ui.TextInputWidget.prototype.select = function () {
11281 this.$input.select();
11282 return this;
11283 };
11284
11285 /**
11286 * Sets the validation pattern to use.
11287 * @param {RegExp|string|null} validate Regular expression (or symbolic name referencing
11288 * one, see #static-validationPatterns)
11289 */
11290 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
11291 if ( validate instanceof RegExp ) {
11292 this.validate = validate;
11293 } else {
11294 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
11295 }
11296 };
11297
11298 /**
11299 * Sets the 'invalid' flag appropriately.
11300 */
11301 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
11302 var widget = this;
11303 this.isValid().done( function ( valid ) {
11304 widget.setFlags( { invalid: !valid } );
11305 } );
11306 };
11307
11308 /**
11309 * Returns whether or not the current value is considered valid, according to the
11310 * supplied validation pattern.
11311 *
11312 * @return {jQuery.Deferred}
11313 */
11314 OO.ui.TextInputWidget.prototype.isValid = function () {
11315 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
11316 };
11317
11318 /**
11319 * Set the position of the inline label.
11320 *
11321 * @param {string} labelPosition Label position, 'before' or 'after'
11322 * @chainable
11323 */
11324 OO.ui.TextInputWidget.prototype.setPosition = function ( labelPosition ) {
11325 this.labelPosition = labelPosition;
11326 this.updatePosition();
11327 return this;
11328 };
11329
11330 /**
11331 * Update the position of the inline label.
11332 *
11333 * @chainable
11334 */
11335 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11336 var after = this.labelPosition === 'after';
11337
11338 this.$element
11339 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', this.label && after )
11340 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', this.label && !after );
11341
11342 if ( this.label ) {
11343 this.positionLabel();
11344 }
11345
11346 return this;
11347 };
11348
11349 /**
11350 * Position the label by setting the correct padding on the input.
11351 *
11352 * @chainable
11353 */
11354 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11355 // Clear old values
11356 this.$input
11357 // Clear old values if present
11358 .css( {
11359 'padding-right': '',
11360 'padding-left': ''
11361 } );
11362
11363 if ( !this.$label.text() ) {
11364 return;
11365 }
11366
11367 var after = this.labelPosition === 'after',
11368 rtl = this.$element.css( 'direction' ) === 'rtl',
11369 property = after === rtl ? 'padding-left' : 'padding-right';
11370
11371 this.$input.css( property, this.$label.outerWidth() );
11372
11373 return this;
11374 };
11375
11376 /**
11377 * Text input with a menu of optional values.
11378 *
11379 * @class
11380 * @extends OO.ui.Widget
11381 *
11382 * @constructor
11383 * @param {Object} [config] Configuration options
11384 * @cfg {Object} [menu] Configuration options to pass to menu widget
11385 * @cfg {Object} [input] Configuration options to pass to input widget
11386 * @cfg {jQuery} [$overlay] Overlay layer; defaults to relative positioning
11387 */
11388 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
11389 // Configuration initialization
11390 config = config || {};
11391
11392 // Parent constructor
11393 OO.ui.ComboBoxWidget.super.call( this, config );
11394
11395 // Properties
11396 this.$overlay = config.$overlay || this.$element;
11397 this.input = new OO.ui.TextInputWidget( $.extend(
11398 { $: this.$, indicator: 'down', disabled: this.isDisabled() },
11399 config.input
11400 ) );
11401 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
11402 {
11403 $: OO.ui.Element.static.getJQuery( this.$overlay ),
11404 widget: this,
11405 input: this.input,
11406 disabled: this.isDisabled()
11407 },
11408 config.menu
11409 ) );
11410
11411 // Events
11412 this.input.connect( this, {
11413 change: 'onInputChange',
11414 indicator: 'onInputIndicator',
11415 enter: 'onInputEnter'
11416 } );
11417 this.menu.connect( this, {
11418 choose: 'onMenuChoose',
11419 add: 'onMenuItemsChange',
11420 remove: 'onMenuItemsChange'
11421 } );
11422
11423 // Initialization
11424 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
11425 this.$overlay.append( this.menu.$element );
11426 this.onMenuItemsChange();
11427 };
11428
11429 /* Setup */
11430
11431 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
11432
11433 /* Methods */
11434
11435 /**
11436 * Get the combobox's menu.
11437 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
11438 */
11439 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
11440 return this.menu;
11441 };
11442
11443 /**
11444 * Handle input change events.
11445 *
11446 * @param {string} value New value
11447 */
11448 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
11449 var match = this.menu.getItemFromData( value );
11450
11451 this.menu.selectItem( match );
11452
11453 if ( !this.isDisabled() ) {
11454 this.menu.toggle( true );
11455 }
11456 };
11457
11458 /**
11459 * Handle input indicator events.
11460 */
11461 OO.ui.ComboBoxWidget.prototype.onInputIndicator = function () {
11462 if ( !this.isDisabled() ) {
11463 this.menu.toggle();
11464 }
11465 };
11466
11467 /**
11468 * Handle input enter events.
11469 */
11470 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
11471 if ( !this.isDisabled() ) {
11472 this.menu.toggle( false );
11473 }
11474 };
11475
11476 /**
11477 * Handle menu choose events.
11478 *
11479 * @param {OO.ui.OptionWidget} item Chosen item
11480 */
11481 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
11482 if ( item ) {
11483 this.input.setValue( item.getData() );
11484 }
11485 };
11486
11487 /**
11488 * Handle menu item change events.
11489 */
11490 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
11491 var match = this.menu.getItemFromData( this.input.getValue() );
11492 this.menu.selectItem( match );
11493 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
11494 };
11495
11496 /**
11497 * @inheritdoc
11498 */
11499 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
11500 // Parent method
11501 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
11502
11503 if ( this.input ) {
11504 this.input.setDisabled( this.isDisabled() );
11505 }
11506 if ( this.menu ) {
11507 this.menu.setDisabled( this.isDisabled() );
11508 }
11509
11510 return this;
11511 };
11512
11513 /**
11514 * Label widget.
11515 *
11516 * @class
11517 * @extends OO.ui.Widget
11518 * @mixins OO.ui.LabelElement
11519 *
11520 * @constructor
11521 * @param {Object} [config] Configuration options
11522 * @cfg {OO.ui.InputWidget} [input] Input widget this label is for
11523 */
11524 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
11525 // Configuration initialization
11526 config = config || {};
11527
11528 // Parent constructor
11529 OO.ui.LabelWidget.super.call( this, config );
11530
11531 // Mixin constructors
11532 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
11533 OO.ui.TitledElement.call( this, config );
11534
11535 // Properties
11536 this.input = config.input;
11537
11538 // Events
11539 if ( this.input instanceof OO.ui.InputWidget ) {
11540 this.$element.on( 'click', this.onClick.bind( this ) );
11541 }
11542
11543 // Initialization
11544 this.$element.addClass( 'oo-ui-labelWidget' );
11545 };
11546
11547 /* Setup */
11548
11549 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
11550 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
11551 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
11552
11553 /* Static Properties */
11554
11555 OO.ui.LabelWidget.static.tagName = 'span';
11556
11557 /* Methods */
11558
11559 /**
11560 * Handles label mouse click events.
11561 *
11562 * @param {jQuery.Event} e Mouse click event
11563 */
11564 OO.ui.LabelWidget.prototype.onClick = function () {
11565 this.input.simulateLabelClick();
11566 return false;
11567 };
11568
11569 /**
11570 * Generic option widget for use with OO.ui.SelectWidget.
11571 *
11572 * @class
11573 * @extends OO.ui.Widget
11574 * @mixins OO.ui.LabelElement
11575 * @mixins OO.ui.FlaggedElement
11576 *
11577 * @constructor
11578 * @param {Object} [config] Configuration options
11579 */
11580 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
11581 // Configuration initialization
11582 config = config || {};
11583
11584 // Parent constructor
11585 OO.ui.OptionWidget.super.call( this, config );
11586
11587 // Mixin constructors
11588 OO.ui.ItemWidget.call( this );
11589 OO.ui.LabelElement.call( this, config );
11590 OO.ui.FlaggedElement.call( this, config );
11591
11592 // Properties
11593 this.selected = false;
11594 this.highlighted = false;
11595 this.pressed = false;
11596
11597 // Initialization
11598 this.$element
11599 .data( 'oo-ui-optionWidget', this )
11600 .attr( 'role', 'option' )
11601 .addClass( 'oo-ui-optionWidget' )
11602 .append( this.$label );
11603 };
11604
11605 /* Setup */
11606
11607 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
11608 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
11609 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
11610 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
11611
11612 /* Static Properties */
11613
11614 OO.ui.OptionWidget.static.selectable = true;
11615
11616 OO.ui.OptionWidget.static.highlightable = true;
11617
11618 OO.ui.OptionWidget.static.pressable = true;
11619
11620 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
11621
11622 /* Methods */
11623
11624 /**
11625 * Check if option can be selected.
11626 *
11627 * @return {boolean} Item is selectable
11628 */
11629 OO.ui.OptionWidget.prototype.isSelectable = function () {
11630 return this.constructor.static.selectable && !this.isDisabled();
11631 };
11632
11633 /**
11634 * Check if option can be highlighted.
11635 *
11636 * @return {boolean} Item is highlightable
11637 */
11638 OO.ui.OptionWidget.prototype.isHighlightable = function () {
11639 return this.constructor.static.highlightable && !this.isDisabled();
11640 };
11641
11642 /**
11643 * Check if option can be pressed.
11644 *
11645 * @return {boolean} Item is pressable
11646 */
11647 OO.ui.OptionWidget.prototype.isPressable = function () {
11648 return this.constructor.static.pressable && !this.isDisabled();
11649 };
11650
11651 /**
11652 * Check if option is selected.
11653 *
11654 * @return {boolean} Item is selected
11655 */
11656 OO.ui.OptionWidget.prototype.isSelected = function () {
11657 return this.selected;
11658 };
11659
11660 /**
11661 * Check if option is highlighted.
11662 *
11663 * @return {boolean} Item is highlighted
11664 */
11665 OO.ui.OptionWidget.prototype.isHighlighted = function () {
11666 return this.highlighted;
11667 };
11668
11669 /**
11670 * Check if option is pressed.
11671 *
11672 * @return {boolean} Item is pressed
11673 */
11674 OO.ui.OptionWidget.prototype.isPressed = function () {
11675 return this.pressed;
11676 };
11677
11678 /**
11679 * Set selected state.
11680 *
11681 * @param {boolean} [state=false] Select option
11682 * @chainable
11683 */
11684 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
11685 if ( this.constructor.static.selectable ) {
11686 this.selected = !!state;
11687 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
11688 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
11689 this.scrollElementIntoView();
11690 }
11691 this.updateThemeClasses();
11692 }
11693 return this;
11694 };
11695
11696 /**
11697 * Set highlighted state.
11698 *
11699 * @param {boolean} [state=false] Highlight option
11700 * @chainable
11701 */
11702 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
11703 if ( this.constructor.static.highlightable ) {
11704 this.highlighted = !!state;
11705 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
11706 this.updateThemeClasses();
11707 }
11708 return this;
11709 };
11710
11711 /**
11712 * Set pressed state.
11713 *
11714 * @param {boolean} [state=false] Press option
11715 * @chainable
11716 */
11717 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
11718 if ( this.constructor.static.pressable ) {
11719 this.pressed = !!state;
11720 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
11721 this.updateThemeClasses();
11722 }
11723 return this;
11724 };
11725
11726 /**
11727 * Option widget with an option icon and indicator.
11728 *
11729 * Use together with OO.ui.SelectWidget.
11730 *
11731 * @class
11732 * @extends OO.ui.OptionWidget
11733 * @mixins OO.ui.IconElement
11734 * @mixins OO.ui.IndicatorElement
11735 *
11736 * @constructor
11737 * @param {Object} [config] Configuration options
11738 */
11739 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
11740 // Parent constructor
11741 OO.ui.DecoratedOptionWidget.super.call( this, config );
11742
11743 // Mixin constructors
11744 OO.ui.IconElement.call( this, config );
11745 OO.ui.IndicatorElement.call( this, config );
11746
11747 // Initialization
11748 this.$element
11749 .addClass( 'oo-ui-decoratedOptionWidget' )
11750 .prepend( this.$icon )
11751 .append( this.$indicator );
11752 };
11753
11754 /* Setup */
11755
11756 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
11757 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
11758 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
11759
11760 /**
11761 * Option widget that looks like a button.
11762 *
11763 * Use together with OO.ui.ButtonSelectWidget.
11764 *
11765 * @class
11766 * @extends OO.ui.DecoratedOptionWidget
11767 * @mixins OO.ui.ButtonElement
11768 * @mixins OO.ui.TabIndexedElement
11769 *
11770 * @constructor
11771 * @param {Object} [config] Configuration options
11772 */
11773 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
11774 // Parent constructor
11775 OO.ui.ButtonOptionWidget.super.call( this, config );
11776
11777 // Mixin constructors
11778 OO.ui.ButtonElement.call( this, config );
11779 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
11780
11781 // Initialization
11782 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
11783 this.$button.append( this.$element.contents() );
11784 this.$element.append( this.$button );
11785 };
11786
11787 /* Setup */
11788
11789 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
11790 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
11791 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
11792
11793 /* Static Properties */
11794
11795 // Allow button mouse down events to pass through so they can be handled by the parent select widget
11796 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
11797
11798 /* Methods */
11799
11800 /**
11801 * @inheritdoc
11802 */
11803 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
11804 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
11805
11806 if ( this.constructor.static.selectable ) {
11807 this.setActive( state );
11808 }
11809
11810 return this;
11811 };
11812
11813 /**
11814 * Option widget that looks like a radio button.
11815 *
11816 * Use together with OO.ui.RadioSelectWidget.
11817 *
11818 * @class
11819 * @extends OO.ui.OptionWidget
11820 *
11821 * @constructor
11822 * @param {Object} [config] Configuration options
11823 */
11824 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
11825 // Parent constructor
11826 OO.ui.RadioOptionWidget.super.call( this, config );
11827
11828 // Properties
11829 this.radio = new OO.ui.RadioInputWidget( { value: config.data } );
11830
11831 // Initialization
11832 this.$element
11833 .addClass( 'oo-ui-radioOptionWidget' )
11834 .prepend( this.radio.$element );
11835 };
11836
11837 /* Setup */
11838
11839 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
11840
11841 /* Static Properties */
11842
11843 OO.ui.RadioOptionWidget.static.highlightable = false;
11844
11845 OO.ui.RadioOptionWidget.static.pressable = false;
11846
11847 /* Methods */
11848
11849 /**
11850 * @inheritdoc
11851 */
11852 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
11853 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
11854
11855 this.radio.setSelected( state );
11856
11857 return this;
11858 };
11859
11860 /**
11861 * Item of an OO.ui.MenuSelectWidget.
11862 *
11863 * @class
11864 * @extends OO.ui.DecoratedOptionWidget
11865 *
11866 * @constructor
11867 * @param {Object} [config] Configuration options
11868 */
11869 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
11870 // Configuration initialization
11871 config = $.extend( { icon: 'check' }, config );
11872
11873 // Parent constructor
11874 OO.ui.MenuOptionWidget.super.call( this, config );
11875
11876 // Initialization
11877 this.$element
11878 .attr( 'role', 'menuitem' )
11879 .addClass( 'oo-ui-menuOptionWidget' );
11880 };
11881
11882 /* Setup */
11883
11884 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
11885
11886 /**
11887 * Section to group one or more items in a OO.ui.MenuSelectWidget.
11888 *
11889 * @class
11890 * @extends OO.ui.DecoratedOptionWidget
11891 *
11892 * @constructor
11893 * @param {Object} [config] Configuration options
11894 */
11895 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
11896 // Parent constructor
11897 OO.ui.MenuSectionOptionWidget.super.call( this, config );
11898
11899 // Initialization
11900 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
11901 };
11902
11903 /* Setup */
11904
11905 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
11906
11907 /* Static Properties */
11908
11909 OO.ui.MenuSectionOptionWidget.static.selectable = false;
11910
11911 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
11912
11913 /**
11914 * Items for an OO.ui.OutlineSelectWidget.
11915 *
11916 * @class
11917 * @extends OO.ui.DecoratedOptionWidget
11918 *
11919 * @constructor
11920 * @param {Object} [config] Configuration options
11921 * @cfg {number} [level] Indentation level
11922 * @cfg {boolean} [movable] Allow modification from outline controls
11923 */
11924 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
11925 // Configuration initialization
11926 config = config || {};
11927
11928 // Parent constructor
11929 OO.ui.OutlineOptionWidget.super.call( this, config );
11930
11931 // Properties
11932 this.level = 0;
11933 this.movable = !!config.movable;
11934 this.removable = !!config.removable;
11935
11936 // Initialization
11937 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
11938 this.setLevel( config.level );
11939 };
11940
11941 /* Setup */
11942
11943 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
11944
11945 /* Static Properties */
11946
11947 OO.ui.OutlineOptionWidget.static.highlightable = false;
11948
11949 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
11950
11951 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
11952
11953 OO.ui.OutlineOptionWidget.static.levels = 3;
11954
11955 /* Methods */
11956
11957 /**
11958 * Check if item is movable.
11959 *
11960 * Movability is used by outline controls.
11961 *
11962 * @return {boolean} Item is movable
11963 */
11964 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
11965 return this.movable;
11966 };
11967
11968 /**
11969 * Check if item is removable.
11970 *
11971 * Removability is used by outline controls.
11972 *
11973 * @return {boolean} Item is removable
11974 */
11975 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
11976 return this.removable;
11977 };
11978
11979 /**
11980 * Get indentation level.
11981 *
11982 * @return {number} Indentation level
11983 */
11984 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
11985 return this.level;
11986 };
11987
11988 /**
11989 * Set movability.
11990 *
11991 * Movability is used by outline controls.
11992 *
11993 * @param {boolean} movable Item is movable
11994 * @chainable
11995 */
11996 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
11997 this.movable = !!movable;
11998 this.updateThemeClasses();
11999 return this;
12000 };
12001
12002 /**
12003 * Set removability.
12004 *
12005 * Removability is used by outline controls.
12006 *
12007 * @param {boolean} movable Item is removable
12008 * @chainable
12009 */
12010 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
12011 this.removable = !!removable;
12012 this.updateThemeClasses();
12013 return this;
12014 };
12015
12016 /**
12017 * Set indentation level.
12018 *
12019 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12020 * @chainable
12021 */
12022 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
12023 var levels = this.constructor.static.levels,
12024 levelClass = this.constructor.static.levelClass,
12025 i = levels;
12026
12027 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
12028 while ( i-- ) {
12029 if ( this.level === i ) {
12030 this.$element.addClass( levelClass + i );
12031 } else {
12032 this.$element.removeClass( levelClass + i );
12033 }
12034 }
12035 this.updateThemeClasses();
12036
12037 return this;
12038 };
12039
12040 /**
12041 * Container for content that is overlaid and positioned absolutely.
12042 *
12043 * @class
12044 * @extends OO.ui.Widget
12045 * @mixins OO.ui.LabelElement
12046 *
12047 * @constructor
12048 * @param {Object} [config] Configuration options
12049 * @cfg {number} [width=320] Width of popup in pixels
12050 * @cfg {number} [height] Height of popup, omit to use automatic height
12051 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12052 * @cfg {string} [align='center'] Alignment of popup to origin
12053 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
12054 * @cfg {number} [containerPadding=10] How much padding to keep between popup and container
12055 * @cfg {jQuery} [$content] Content to append to the popup's body
12056 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
12057 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
12058 * @cfg {boolean} [head] Show label and close button at the top
12059 * @cfg {boolean} [padded] Add padding to the body
12060 */
12061 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
12062 // Configuration initialization
12063 config = config || {};
12064
12065 // Parent constructor
12066 OO.ui.PopupWidget.super.call( this, config );
12067
12068 // Mixin constructors
12069 OO.ui.LabelElement.call( this, config );
12070 OO.ui.ClippableElement.call( this, config );
12071
12072 // Properties
12073 this.visible = false;
12074 this.$popup = this.$( '<div>' );
12075 this.$head = this.$( '<div>' );
12076 this.$body = this.$( '<div>' );
12077 this.$anchor = this.$( '<div>' );
12078 // If undefined, will be computed lazily in updateDimensions()
12079 this.$container = config.$container;
12080 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
12081 this.autoClose = !!config.autoClose;
12082 this.$autoCloseIgnore = config.$autoCloseIgnore;
12083 this.transitionTimeout = null;
12084 this.anchor = null;
12085 this.width = config.width !== undefined ? config.width : 320;
12086 this.height = config.height !== undefined ? config.height : null;
12087 this.align = config.align || 'center';
12088 this.closeButton = new OO.ui.ButtonWidget( { $: this.$, framed: false, icon: 'close' } );
12089 this.onMouseDownHandler = this.onMouseDown.bind( this );
12090
12091 // Events
12092 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
12093
12094 // Initialization
12095 this.toggleAnchor( config.anchor === undefined || config.anchor );
12096 this.$body.addClass( 'oo-ui-popupWidget-body' );
12097 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
12098 this.$head
12099 .addClass( 'oo-ui-popupWidget-head' )
12100 .append( this.$label, this.closeButton.$element );
12101 if ( !config.head ) {
12102 this.$head.hide();
12103 }
12104 this.$popup
12105 .addClass( 'oo-ui-popupWidget-popup' )
12106 .append( this.$head, this.$body );
12107 this.$element
12108 .hide()
12109 .addClass( 'oo-ui-popupWidget' )
12110 .append( this.$popup, this.$anchor );
12111 // Move content, which was added to #$element by OO.ui.Widget, to the body
12112 if ( config.$content instanceof jQuery ) {
12113 this.$body.append( config.$content );
12114 }
12115 if ( config.padded ) {
12116 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
12117 }
12118 this.setClippableElement( this.$body );
12119 };
12120
12121 /* Setup */
12122
12123 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
12124 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
12125 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
12126
12127 /* Methods */
12128
12129 /**
12130 * Handles mouse down events.
12131 *
12132 * @param {jQuery.Event} e Mouse down event
12133 */
12134 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
12135 if (
12136 this.isVisible() &&
12137 !$.contains( this.$element[ 0 ], e.target ) &&
12138 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
12139 ) {
12140 this.toggle( false );
12141 }
12142 };
12143
12144 /**
12145 * Bind mouse down listener.
12146 */
12147 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
12148 // Capture clicks outside popup
12149 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
12150 };
12151
12152 /**
12153 * Handles close button click events.
12154 */
12155 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
12156 if ( this.isVisible() ) {
12157 this.toggle( false );
12158 }
12159 };
12160
12161 /**
12162 * Unbind mouse down listener.
12163 */
12164 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
12165 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
12166 };
12167
12168 /**
12169 * Set whether to show a anchor.
12170 *
12171 * @param {boolean} [show] Show anchor, omit to toggle
12172 */
12173 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
12174 show = show === undefined ? !this.anchored : !!show;
12175
12176 if ( this.anchored !== show ) {
12177 if ( show ) {
12178 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
12179 } else {
12180 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
12181 }
12182 this.anchored = show;
12183 }
12184 };
12185
12186 /**
12187 * Check if showing a anchor.
12188 *
12189 * @return {boolean} anchor is visible
12190 */
12191 OO.ui.PopupWidget.prototype.hasAnchor = function () {
12192 return this.anchor;
12193 };
12194
12195 /**
12196 * @inheritdoc
12197 */
12198 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
12199 show = show === undefined ? !this.isVisible() : !!show;
12200
12201 var change = show !== this.isVisible();
12202
12203 // Parent method
12204 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
12205
12206 if ( change ) {
12207 if ( show ) {
12208 if ( this.autoClose ) {
12209 this.bindMouseDownListener();
12210 }
12211 this.updateDimensions();
12212 this.toggleClipping( true );
12213 } else {
12214 this.toggleClipping( false );
12215 if ( this.autoClose ) {
12216 this.unbindMouseDownListener();
12217 }
12218 }
12219 }
12220
12221 return this;
12222 };
12223
12224 /**
12225 * Set the size of the popup.
12226 *
12227 * Changing the size may also change the popup's position depending on the alignment.
12228 *
12229 * @param {number} width Width
12230 * @param {number} height Height
12231 * @param {boolean} [transition=false] Use a smooth transition
12232 * @chainable
12233 */
12234 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
12235 this.width = width;
12236 this.height = height !== undefined ? height : null;
12237 if ( this.isVisible() ) {
12238 this.updateDimensions( transition );
12239 }
12240 };
12241
12242 /**
12243 * Update the size and position.
12244 *
12245 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
12246 * be called automatically.
12247 *
12248 * @param {boolean} [transition=false] Use a smooth transition
12249 * @chainable
12250 */
12251 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
12252 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
12253 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
12254 widget = this;
12255
12256 if ( !this.$container ) {
12257 // Lazy-initialize $container if not specified in constructor
12258 this.$container = this.$( this.getClosestScrollableElementContainer() );
12259 }
12260
12261 // Set height and width before measuring things, since it might cause our measurements
12262 // to change (e.g. due to scrollbars appearing or disappearing)
12263 this.$popup.css( {
12264 width: this.width,
12265 height: this.height !== null ? this.height : 'auto'
12266 } );
12267
12268 // Compute initial popupOffset based on alignment
12269 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
12270
12271 // Figure out if this will cause the popup to go beyond the edge of the container
12272 originOffset = this.$element.offset().left;
12273 containerLeft = this.$container.offset().left;
12274 containerWidth = this.$container.innerWidth();
12275 containerRight = containerLeft + containerWidth;
12276 popupLeft = popupOffset - this.containerPadding;
12277 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
12278 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
12279 overlapRight = containerRight - ( originOffset + popupRight );
12280
12281 // Adjust offset to make the popup not go beyond the edge, if needed
12282 if ( overlapRight < 0 ) {
12283 popupOffset += overlapRight;
12284 } else if ( overlapLeft < 0 ) {
12285 popupOffset -= overlapLeft;
12286 }
12287
12288 // Adjust offset to avoid anchor being rendered too close to the edge
12289 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
12290 // TODO: Find a measurement that works for CSS anchors and image anchors
12291 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
12292 if ( popupOffset + this.width < anchorWidth ) {
12293 popupOffset = anchorWidth - this.width;
12294 } else if ( -popupOffset < anchorWidth ) {
12295 popupOffset = -anchorWidth;
12296 }
12297
12298 // Prevent transition from being interrupted
12299 clearTimeout( this.transitionTimeout );
12300 if ( transition ) {
12301 // Enable transition
12302 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
12303 }
12304
12305 // Position body relative to anchor
12306 this.$popup.css( 'margin-left', popupOffset );
12307
12308 if ( transition ) {
12309 // Prevent transitioning after transition is complete
12310 this.transitionTimeout = setTimeout( function () {
12311 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
12312 }, 200 );
12313 } else {
12314 // Prevent transitioning immediately
12315 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
12316 }
12317
12318 // Reevaluate clipping state since we've relocated and resized the popup
12319 this.clip();
12320
12321 return this;
12322 };
12323
12324 /**
12325 * Progress bar widget.
12326 *
12327 * @class
12328 * @extends OO.ui.Widget
12329 *
12330 * @constructor
12331 * @param {Object} [config] Configuration options
12332 * @cfg {number|boolean} [progress=false] Initial progress percent or false for indeterminate
12333 */
12334 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
12335 // Configuration initialization
12336 config = config || {};
12337
12338 // Parent constructor
12339 OO.ui.ProgressBarWidget.super.call( this, config );
12340
12341 // Properties
12342 this.$bar = this.$( '<div>' );
12343 this.progress = null;
12344
12345 // Initialization
12346 this.setProgress( config.progress !== undefined ? config.progress : false );
12347 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
12348 this.$element
12349 .attr( {
12350 role: 'progressbar',
12351 'aria-valuemin': 0,
12352 'aria-valuemax': 100
12353 } )
12354 .addClass( 'oo-ui-progressBarWidget' )
12355 .append( this.$bar );
12356 };
12357
12358 /* Setup */
12359
12360 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
12361
12362 /* Static Properties */
12363
12364 OO.ui.ProgressBarWidget.static.tagName = 'div';
12365
12366 /* Methods */
12367
12368 /**
12369 * Get progress percent
12370 *
12371 * @return {number} Progress percent
12372 */
12373 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
12374 return this.progress;
12375 };
12376
12377 /**
12378 * Set progress percent
12379 *
12380 * @param {number|boolean} progress Progress percent or false for indeterminate
12381 */
12382 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
12383 this.progress = progress;
12384
12385 if ( progress !== false ) {
12386 this.$bar.css( 'width', this.progress + '%' );
12387 this.$element.attr( 'aria-valuenow', this.progress );
12388 } else {
12389 this.$bar.css( 'width', '' );
12390 this.$element.removeAttr( 'aria-valuenow' );
12391 }
12392 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
12393 };
12394
12395 /**
12396 * Search widget.
12397 *
12398 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
12399 * Results are cleared and populated each time the query is changed.
12400 *
12401 * @class
12402 * @extends OO.ui.Widget
12403 *
12404 * @constructor
12405 * @param {Object} [config] Configuration options
12406 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
12407 * @cfg {string} [value] Initial query value
12408 */
12409 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
12410 // Configuration initialization
12411 config = config || {};
12412
12413 // Parent constructor
12414 OO.ui.SearchWidget.super.call( this, config );
12415
12416 // Properties
12417 this.query = new OO.ui.TextInputWidget( {
12418 $: this.$,
12419 icon: 'search',
12420 placeholder: config.placeholder,
12421 value: config.value
12422 } );
12423 this.results = new OO.ui.SelectWidget( { $: this.$ } );
12424 this.$query = this.$( '<div>' );
12425 this.$results = this.$( '<div>' );
12426
12427 // Events
12428 this.query.connect( this, {
12429 change: 'onQueryChange',
12430 enter: 'onQueryEnter'
12431 } );
12432 this.results.connect( this, {
12433 highlight: 'onResultsHighlight',
12434 select: 'onResultsSelect'
12435 } );
12436 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
12437
12438 // Initialization
12439 this.$query
12440 .addClass( 'oo-ui-searchWidget-query' )
12441 .append( this.query.$element );
12442 this.$results
12443 .addClass( 'oo-ui-searchWidget-results' )
12444 .append( this.results.$element );
12445 this.$element
12446 .addClass( 'oo-ui-searchWidget' )
12447 .append( this.$results, this.$query );
12448 };
12449
12450 /* Setup */
12451
12452 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
12453
12454 /* Events */
12455
12456 /**
12457 * @event highlight
12458 * @param {Object|null} item Item data or null if no item is highlighted
12459 */
12460
12461 /**
12462 * @event select
12463 * @param {Object|null} item Item data or null if no item is selected
12464 */
12465
12466 /* Methods */
12467
12468 /**
12469 * Handle query key down events.
12470 *
12471 * @param {jQuery.Event} e Key down event
12472 */
12473 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
12474 var highlightedItem, nextItem,
12475 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
12476
12477 if ( dir ) {
12478 highlightedItem = this.results.getHighlightedItem();
12479 if ( !highlightedItem ) {
12480 highlightedItem = this.results.getSelectedItem();
12481 }
12482 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
12483 this.results.highlightItem( nextItem );
12484 nextItem.scrollElementIntoView();
12485 }
12486 };
12487
12488 /**
12489 * Handle select widget select events.
12490 *
12491 * Clears existing results. Subclasses should repopulate items according to new query.
12492 *
12493 * @param {string} value New value
12494 */
12495 OO.ui.SearchWidget.prototype.onQueryChange = function () {
12496 // Reset
12497 this.results.clearItems();
12498 };
12499
12500 /**
12501 * Handle select widget enter key events.
12502 *
12503 * Selects highlighted item.
12504 *
12505 * @param {string} value New value
12506 */
12507 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
12508 // Reset
12509 this.results.selectItem( this.results.getHighlightedItem() );
12510 };
12511
12512 /**
12513 * Handle select widget highlight events.
12514 *
12515 * @param {OO.ui.OptionWidget} item Highlighted item
12516 * @fires highlight
12517 */
12518 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
12519 this.emit( 'highlight', item ? item.getData() : null );
12520 };
12521
12522 /**
12523 * Handle select widget select events.
12524 *
12525 * @param {OO.ui.OptionWidget} item Selected item
12526 * @fires select
12527 */
12528 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
12529 this.emit( 'select', item ? item.getData() : null );
12530 };
12531
12532 /**
12533 * Get the query input.
12534 *
12535 * @return {OO.ui.TextInputWidget} Query input
12536 */
12537 OO.ui.SearchWidget.prototype.getQuery = function () {
12538 return this.query;
12539 };
12540
12541 /**
12542 * Get the results list.
12543 *
12544 * @return {OO.ui.SelectWidget} Select list
12545 */
12546 OO.ui.SearchWidget.prototype.getResults = function () {
12547 return this.results;
12548 };
12549
12550 /**
12551 * Generic selection of options.
12552 *
12553 * Items can contain any rendering. Any widget that provides options, from which the user must
12554 * choose one, should be built on this class.
12555 *
12556 * Use together with OO.ui.OptionWidget.
12557 *
12558 * @class
12559 * @extends OO.ui.Widget
12560 * @mixins OO.ui.GroupElement
12561 *
12562 * @constructor
12563 * @param {Object} [config] Configuration options
12564 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
12565 */
12566 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
12567 // Configuration initialization
12568 config = config || {};
12569
12570 // Parent constructor
12571 OO.ui.SelectWidget.super.call( this, config );
12572
12573 // Mixin constructors
12574 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
12575
12576 // Properties
12577 this.pressed = false;
12578 this.selecting = null;
12579 this.onMouseUpHandler = this.onMouseUp.bind( this );
12580 this.onMouseMoveHandler = this.onMouseMove.bind( this );
12581
12582 // Events
12583 this.$element.on( {
12584 mousedown: this.onMouseDown.bind( this ),
12585 mouseover: this.onMouseOver.bind( this ),
12586 mouseleave: this.onMouseLeave.bind( this )
12587 } );
12588
12589 // Initialization
12590 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
12591 if ( $.isArray( config.items ) ) {
12592 this.addItems( config.items );
12593 }
12594 };
12595
12596 /* Setup */
12597
12598 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
12599
12600 // Need to mixin base class as well
12601 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
12602 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
12603
12604 /* Events */
12605
12606 /**
12607 * @event highlight
12608 * @param {OO.ui.OptionWidget|null} item Highlighted item
12609 */
12610
12611 /**
12612 * @event press
12613 * @param {OO.ui.OptionWidget|null} item Pressed item
12614 */
12615
12616 /**
12617 * @event select
12618 * @param {OO.ui.OptionWidget|null} item Selected item
12619 */
12620
12621 /**
12622 * @event choose
12623 * @param {OO.ui.OptionWidget|null} item Chosen item
12624 */
12625
12626 /**
12627 * @event add
12628 * @param {OO.ui.OptionWidget[]} items Added items
12629 * @param {number} index Index items were added at
12630 */
12631
12632 /**
12633 * @event remove
12634 * @param {OO.ui.OptionWidget[]} items Removed items
12635 */
12636
12637 /* Methods */
12638
12639 /**
12640 * Handle mouse down events.
12641 *
12642 * @private
12643 * @param {jQuery.Event} e Mouse down event
12644 */
12645 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
12646 var item;
12647
12648 if ( !this.isDisabled() && e.which === 1 ) {
12649 this.togglePressed( true );
12650 item = this.getTargetItem( e );
12651 if ( item && item.isSelectable() ) {
12652 this.pressItem( item );
12653 this.selecting = item;
12654 this.getElementDocument().addEventListener(
12655 'mouseup',
12656 this.onMouseUpHandler,
12657 true
12658 );
12659 this.getElementDocument().addEventListener(
12660 'mousemove',
12661 this.onMouseMoveHandler,
12662 true
12663 );
12664 }
12665 }
12666 return false;
12667 };
12668
12669 /**
12670 * Handle mouse up events.
12671 *
12672 * @private
12673 * @param {jQuery.Event} e Mouse up event
12674 */
12675 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
12676 var item;
12677
12678 this.togglePressed( false );
12679 if ( !this.selecting ) {
12680 item = this.getTargetItem( e );
12681 if ( item && item.isSelectable() ) {
12682 this.selecting = item;
12683 }
12684 }
12685 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
12686 this.pressItem( null );
12687 this.chooseItem( this.selecting );
12688 this.selecting = null;
12689 }
12690
12691 this.getElementDocument().removeEventListener(
12692 'mouseup',
12693 this.onMouseUpHandler,
12694 true
12695 );
12696 this.getElementDocument().removeEventListener(
12697 'mousemove',
12698 this.onMouseMoveHandler,
12699 true
12700 );
12701
12702 return false;
12703 };
12704
12705 /**
12706 * Handle mouse move events.
12707 *
12708 * @private
12709 * @param {jQuery.Event} e Mouse move event
12710 */
12711 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
12712 var item;
12713
12714 if ( !this.isDisabled() && this.pressed ) {
12715 item = this.getTargetItem( e );
12716 if ( item && item !== this.selecting && item.isSelectable() ) {
12717 this.pressItem( item );
12718 this.selecting = item;
12719 }
12720 }
12721 return false;
12722 };
12723
12724 /**
12725 * Handle mouse over events.
12726 *
12727 * @private
12728 * @param {jQuery.Event} e Mouse over event
12729 */
12730 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
12731 var item;
12732
12733 if ( !this.isDisabled() ) {
12734 item = this.getTargetItem( e );
12735 this.highlightItem( item && item.isHighlightable() ? item : null );
12736 }
12737 return false;
12738 };
12739
12740 /**
12741 * Handle mouse leave events.
12742 *
12743 * @private
12744 * @param {jQuery.Event} e Mouse over event
12745 */
12746 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
12747 if ( !this.isDisabled() ) {
12748 this.highlightItem( null );
12749 }
12750 return false;
12751 };
12752
12753 /**
12754 * Get the closest item to a jQuery.Event.
12755 *
12756 * @private
12757 * @param {jQuery.Event} e
12758 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
12759 */
12760 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
12761 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
12762 if ( $item.length ) {
12763 return $item.data( 'oo-ui-optionWidget' );
12764 }
12765 return null;
12766 };
12767
12768 /**
12769 * Get selected item.
12770 *
12771 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
12772 */
12773 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
12774 var i, len;
12775
12776 for ( i = 0, len = this.items.length; i < len; i++ ) {
12777 if ( this.items[ i ].isSelected() ) {
12778 return this.items[ i ];
12779 }
12780 }
12781 return null;
12782 };
12783
12784 /**
12785 * Get highlighted item.
12786 *
12787 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
12788 */
12789 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
12790 var i, len;
12791
12792 for ( i = 0, len = this.items.length; i < len; i++ ) {
12793 if ( this.items[ i ].isHighlighted() ) {
12794 return this.items[ i ];
12795 }
12796 }
12797 return null;
12798 };
12799
12800 /**
12801 * Toggle pressed state.
12802 *
12803 * @param {boolean} pressed An option is being pressed
12804 */
12805 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
12806 if ( pressed === undefined ) {
12807 pressed = !this.pressed;
12808 }
12809 if ( pressed !== this.pressed ) {
12810 this.$element
12811 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
12812 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
12813 this.pressed = pressed;
12814 }
12815 };
12816
12817 /**
12818 * Highlight an item.
12819 *
12820 * Highlighting is mutually exclusive.
12821 *
12822 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
12823 * @fires highlight
12824 * @chainable
12825 */
12826 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
12827 var i, len, highlighted,
12828 changed = false;
12829
12830 for ( i = 0, len = this.items.length; i < len; i++ ) {
12831 highlighted = this.items[ i ] === item;
12832 if ( this.items[ i ].isHighlighted() !== highlighted ) {
12833 this.items[ i ].setHighlighted( highlighted );
12834 changed = true;
12835 }
12836 }
12837 if ( changed ) {
12838 this.emit( 'highlight', item );
12839 }
12840
12841 return this;
12842 };
12843
12844 /**
12845 * Select an item.
12846 *
12847 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
12848 * @fires select
12849 * @chainable
12850 */
12851 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
12852 var i, len, selected,
12853 changed = false;
12854
12855 for ( i = 0, len = this.items.length; i < len; i++ ) {
12856 selected = this.items[ i ] === item;
12857 if ( this.items[ i ].isSelected() !== selected ) {
12858 this.items[ i ].setSelected( selected );
12859 changed = true;
12860 }
12861 }
12862 if ( changed ) {
12863 this.emit( 'select', item );
12864 }
12865
12866 return this;
12867 };
12868
12869 /**
12870 * Press an item.
12871 *
12872 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
12873 * @fires press
12874 * @chainable
12875 */
12876 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
12877 var i, len, pressed,
12878 changed = false;
12879
12880 for ( i = 0, len = this.items.length; i < len; i++ ) {
12881 pressed = this.items[ i ] === item;
12882 if ( this.items[ i ].isPressed() !== pressed ) {
12883 this.items[ i ].setPressed( pressed );
12884 changed = true;
12885 }
12886 }
12887 if ( changed ) {
12888 this.emit( 'press', item );
12889 }
12890
12891 return this;
12892 };
12893
12894 /**
12895 * Choose an item.
12896 *
12897 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
12898 * an item is selected using the keyboard or mouse.
12899 *
12900 * @param {OO.ui.OptionWidget} item Item to choose
12901 * @fires choose
12902 * @chainable
12903 */
12904 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
12905 this.selectItem( item );
12906 this.emit( 'choose', item );
12907
12908 return this;
12909 };
12910
12911 /**
12912 * Get an item relative to another one.
12913 *
12914 * @param {OO.ui.OptionWidget|null} item Item to start at, null to get relative to list start
12915 * @param {number} direction Direction to move in, -1 to move backward, 1 to move forward
12916 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
12917 */
12918 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
12919 var currentIndex, nextIndex, i,
12920 increase = direction > 0 ? 1 : -1,
12921 len = this.items.length;
12922
12923 if ( item instanceof OO.ui.OptionWidget ) {
12924 currentIndex = $.inArray( item, this.items );
12925 nextIndex = ( currentIndex + increase + len ) % len;
12926 } else {
12927 // If no item is selected and moving forward, start at the beginning.
12928 // If moving backward, start at the end.
12929 nextIndex = direction > 0 ? 0 : len - 1;
12930 }
12931
12932 for ( i = 0; i < len; i++ ) {
12933 item = this.items[ nextIndex ];
12934 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
12935 return item;
12936 }
12937 nextIndex = ( nextIndex + increase + len ) % len;
12938 }
12939 return null;
12940 };
12941
12942 /**
12943 * Get the next selectable item.
12944 *
12945 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
12946 */
12947 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
12948 var i, len, item;
12949
12950 for ( i = 0, len = this.items.length; i < len; i++ ) {
12951 item = this.items[ i ];
12952 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
12953 return item;
12954 }
12955 }
12956
12957 return null;
12958 };
12959
12960 /**
12961 * Add items.
12962 *
12963 * @param {OO.ui.OptionWidget[]} items Items to add
12964 * @param {number} [index] Index to insert items after
12965 * @fires add
12966 * @chainable
12967 */
12968 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
12969 // Mixin method
12970 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
12971
12972 // Always provide an index, even if it was omitted
12973 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
12974
12975 return this;
12976 };
12977
12978 /**
12979 * Remove items.
12980 *
12981 * Items will be detached, not removed, so they can be used later.
12982 *
12983 * @param {OO.ui.OptionWidget[]} items Items to remove
12984 * @fires remove
12985 * @chainable
12986 */
12987 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
12988 var i, len, item;
12989
12990 // Deselect items being removed
12991 for ( i = 0, len = items.length; i < len; i++ ) {
12992 item = items[ i ];
12993 if ( item.isSelected() ) {
12994 this.selectItem( null );
12995 }
12996 }
12997
12998 // Mixin method
12999 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
13000
13001 this.emit( 'remove', items );
13002
13003 return this;
13004 };
13005
13006 /**
13007 * Clear all items.
13008 *
13009 * Items will be detached, not removed, so they can be used later.
13010 *
13011 * @fires remove
13012 * @chainable
13013 */
13014 OO.ui.SelectWidget.prototype.clearItems = function () {
13015 var items = this.items.slice();
13016
13017 // Mixin method
13018 OO.ui.GroupWidget.prototype.clearItems.call( this );
13019
13020 // Clear selection
13021 this.selectItem( null );
13022
13023 this.emit( 'remove', items );
13024
13025 return this;
13026 };
13027
13028 /**
13029 * Select widget containing button options.
13030 *
13031 * Use together with OO.ui.ButtonOptionWidget.
13032 *
13033 * @class
13034 * @extends OO.ui.SelectWidget
13035 *
13036 * @constructor
13037 * @param {Object} [config] Configuration options
13038 */
13039 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
13040 // Parent constructor
13041 OO.ui.ButtonSelectWidget.super.call( this, config );
13042
13043 // Initialization
13044 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
13045 };
13046
13047 /* Setup */
13048
13049 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
13050
13051 /**
13052 * Select widget containing radio button options.
13053 *
13054 * Use together with OO.ui.RadioOptionWidget.
13055 *
13056 * @class
13057 * @extends OO.ui.SelectWidget
13058 *
13059 * @constructor
13060 * @param {Object} [config] Configuration options
13061 */
13062 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
13063 // Parent constructor
13064 OO.ui.RadioSelectWidget.super.call( this, config );
13065
13066 // Initialization
13067 this.$element.addClass( 'oo-ui-radioSelectWidget' );
13068 };
13069
13070 /* Setup */
13071
13072 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
13073
13074 /**
13075 * Overlaid menu of options.
13076 *
13077 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
13078 * the menu.
13079 *
13080 * Use together with OO.ui.MenuOptionWidget.
13081 *
13082 * @class
13083 * @extends OO.ui.SelectWidget
13084 * @mixins OO.ui.ClippableElement
13085 *
13086 * @constructor
13087 * @param {Object} [config] Configuration options
13088 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
13089 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
13090 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
13091 */
13092 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
13093 // Configuration initialization
13094 config = config || {};
13095
13096 // Parent constructor
13097 OO.ui.MenuSelectWidget.super.call( this, config );
13098
13099 // Mixin constructors
13100 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
13101
13102 // Properties
13103 this.visible = false;
13104 this.newItems = null;
13105 this.autoHide = config.autoHide === undefined || !!config.autoHide;
13106 this.$input = config.input ? config.input.$input : null;
13107 this.$widget = config.widget ? config.widget.$element : null;
13108 this.$previousFocus = null;
13109 this.isolated = !config.input;
13110 this.onKeyDownHandler = this.onKeyDown.bind( this );
13111 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
13112
13113 // Initialization
13114 this.$element
13115 .hide()
13116 .attr( 'role', 'menu' )
13117 .addClass( 'oo-ui-menuSelectWidget' );
13118 };
13119
13120 /* Setup */
13121
13122 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
13123 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
13124
13125 /* Methods */
13126
13127 /**
13128 * Handles document mouse down events.
13129 *
13130 * @param {jQuery.Event} e Key down event
13131 */
13132 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
13133 if (
13134 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
13135 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
13136 ) {
13137 this.toggle( false );
13138 }
13139 };
13140
13141 /**
13142 * Handles key down events.
13143 *
13144 * @param {jQuery.Event} e Key down event
13145 */
13146 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
13147 var nextItem,
13148 handled = false,
13149 highlightItem = this.getHighlightedItem();
13150
13151 if ( !this.isDisabled() && this.isVisible() ) {
13152 if ( !highlightItem ) {
13153 highlightItem = this.getSelectedItem();
13154 }
13155 switch ( e.keyCode ) {
13156 case OO.ui.Keys.ENTER:
13157 this.chooseItem( highlightItem );
13158 handled = true;
13159 break;
13160 case OO.ui.Keys.UP:
13161 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
13162 handled = true;
13163 break;
13164 case OO.ui.Keys.DOWN:
13165 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
13166 handled = true;
13167 break;
13168 case OO.ui.Keys.ESCAPE:
13169 if ( highlightItem ) {
13170 highlightItem.setHighlighted( false );
13171 }
13172 this.toggle( false );
13173 handled = true;
13174 break;
13175 }
13176
13177 if ( nextItem ) {
13178 this.highlightItem( nextItem );
13179 nextItem.scrollElementIntoView();
13180 }
13181
13182 if ( handled ) {
13183 e.preventDefault();
13184 e.stopPropagation();
13185 return false;
13186 }
13187 }
13188 };
13189
13190 /**
13191 * Bind key down listener.
13192 */
13193 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
13194 if ( this.$input ) {
13195 this.$input.on( 'keydown', this.onKeyDownHandler );
13196 } else {
13197 // Capture menu navigation keys
13198 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
13199 }
13200 };
13201
13202 /**
13203 * Unbind key down listener.
13204 */
13205 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
13206 if ( this.$input ) {
13207 this.$input.off( 'keydown' );
13208 } else {
13209 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
13210 }
13211 };
13212
13213 /**
13214 * Choose an item.
13215 *
13216 * This will close the menu, unlike #selectItem which only changes selection.
13217 *
13218 * @param {OO.ui.OptionWidget} item Item to choose
13219 * @chainable
13220 */
13221 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
13222 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
13223 this.toggle( false );
13224 return this;
13225 };
13226
13227 /**
13228 * @inheritdoc
13229 */
13230 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
13231 var i, len, item;
13232
13233 // Parent method
13234 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
13235
13236 // Auto-initialize
13237 if ( !this.newItems ) {
13238 this.newItems = [];
13239 }
13240
13241 for ( i = 0, len = items.length; i < len; i++ ) {
13242 item = items[ i ];
13243 if ( this.isVisible() ) {
13244 // Defer fitting label until item has been attached
13245 item.fitLabel();
13246 } else {
13247 this.newItems.push( item );
13248 }
13249 }
13250
13251 // Reevaluate clipping
13252 this.clip();
13253
13254 return this;
13255 };
13256
13257 /**
13258 * @inheritdoc
13259 */
13260 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
13261 // Parent method
13262 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
13263
13264 // Reevaluate clipping
13265 this.clip();
13266
13267 return this;
13268 };
13269
13270 /**
13271 * @inheritdoc
13272 */
13273 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
13274 // Parent method
13275 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
13276
13277 // Reevaluate clipping
13278 this.clip();
13279
13280 return this;
13281 };
13282
13283 /**
13284 * @inheritdoc
13285 */
13286 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
13287 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
13288
13289 var i, len,
13290 change = visible !== this.isVisible(),
13291 elementDoc = this.getElementDocument(),
13292 widgetDoc = this.$widget ? this.$widget[ 0 ].ownerDocument : null;
13293
13294 // Parent method
13295 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
13296
13297 if ( change ) {
13298 if ( visible ) {
13299 this.bindKeyDownListener();
13300
13301 // Change focus to enable keyboard navigation
13302 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
13303 this.$previousFocus = this.$( ':focus' );
13304 this.$input[ 0 ].focus();
13305 }
13306 if ( this.newItems && this.newItems.length ) {
13307 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
13308 this.newItems[ i ].fitLabel();
13309 }
13310 this.newItems = null;
13311 }
13312 this.toggleClipping( true );
13313
13314 // Auto-hide
13315 if ( this.autoHide ) {
13316 elementDoc.addEventListener(
13317 'mousedown', this.onDocumentMouseDownHandler, true
13318 );
13319 // Support $widget being in a different document
13320 if ( widgetDoc && widgetDoc !== elementDoc ) {
13321 widgetDoc.addEventListener(
13322 'mousedown', this.onDocumentMouseDownHandler, true
13323 );
13324 }
13325 }
13326 } else {
13327 this.unbindKeyDownListener();
13328 if ( this.isolated && this.$previousFocus ) {
13329 this.$previousFocus[ 0 ].focus();
13330 this.$previousFocus = null;
13331 }
13332 elementDoc.removeEventListener(
13333 'mousedown', this.onDocumentMouseDownHandler, true
13334 );
13335 // Support $widget being in a different document
13336 if ( widgetDoc && widgetDoc !== elementDoc ) {
13337 widgetDoc.removeEventListener(
13338 'mousedown', this.onDocumentMouseDownHandler, true
13339 );
13340 }
13341 this.toggleClipping( false );
13342 }
13343 }
13344
13345 return this;
13346 };
13347
13348 /**
13349 * Menu for a text input widget.
13350 *
13351 * This menu is specially designed to be positioned beneath the text input widget. Even if the input
13352 * is in a different frame, the menu's position is automatically calculated and maintained when the
13353 * menu is toggled or the window is resized.
13354 *
13355 * @class
13356 * @extends OO.ui.MenuSelectWidget
13357 *
13358 * @constructor
13359 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
13360 * @param {Object} [config] Configuration options
13361 * @cfg {jQuery} [$container=input.$element] Element to render menu under
13362 */
13363 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( input, config ) {
13364 // Configuration initialization
13365 config = config || {};
13366
13367 // Parent constructor
13368 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
13369
13370 // Properties
13371 this.input = input;
13372 this.$container = config.$container || this.input.$element;
13373 this.onWindowResizeHandler = this.onWindowResize.bind( this );
13374
13375 // Initialization
13376 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
13377 };
13378
13379 /* Setup */
13380
13381 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
13382
13383 /* Methods */
13384
13385 /**
13386 * Handle window resize event.
13387 *
13388 * @param {jQuery.Event} e Window resize event
13389 */
13390 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
13391 this.position();
13392 };
13393
13394 /**
13395 * @inheritdoc
13396 */
13397 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
13398 visible = visible === undefined ? !this.isVisible() : !!visible;
13399
13400 var change = visible !== this.isVisible();
13401
13402 if ( change && visible ) {
13403 // Make sure the width is set before the parent method runs.
13404 // After this we have to call this.position(); again to actually
13405 // position ourselves correctly.
13406 this.position();
13407 }
13408
13409 // Parent method
13410 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
13411
13412 if ( change ) {
13413 if ( this.isVisible() ) {
13414 this.position();
13415 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
13416 } else {
13417 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
13418 }
13419 }
13420
13421 return this;
13422 };
13423
13424 /**
13425 * Position the menu.
13426 *
13427 * @chainable
13428 */
13429 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
13430 var $container = this.$container,
13431 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
13432
13433 // Position under input
13434 pos.top += $container.height();
13435 this.$element.css( pos );
13436
13437 // Set width
13438 this.setIdealSize( $container.width() );
13439 // We updated the position, so re-evaluate the clipping state
13440 this.clip();
13441
13442 return this;
13443 };
13444
13445 /**
13446 * Structured list of items.
13447 *
13448 * Use with OO.ui.OutlineOptionWidget.
13449 *
13450 * @class
13451 * @extends OO.ui.SelectWidget
13452 *
13453 * @constructor
13454 * @param {Object} [config] Configuration options
13455 */
13456 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
13457 // Configuration initialization
13458 config = config || {};
13459
13460 // Parent constructor
13461 OO.ui.OutlineSelectWidget.super.call( this, config );
13462
13463 // Initialization
13464 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
13465 };
13466
13467 /* Setup */
13468
13469 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
13470
13471 /**
13472 * Switch that slides on and off.
13473 *
13474 * @class
13475 * @extends OO.ui.Widget
13476 * @mixins OO.ui.ToggleWidget
13477 *
13478 * @constructor
13479 * @param {Object} [config] Configuration options
13480 * @cfg {boolean} [value=false] Initial value
13481 */
13482 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
13483 // Parent constructor
13484 OO.ui.ToggleSwitchWidget.super.call( this, config );
13485
13486 // Mixin constructors
13487 OO.ui.ToggleWidget.call( this, config );
13488
13489 // Properties
13490 this.dragging = false;
13491 this.dragStart = null;
13492 this.sliding = false;
13493 this.$glow = this.$( '<span>' );
13494 this.$grip = this.$( '<span>' );
13495
13496 // Events
13497 this.$element.on( 'click', this.onClick.bind( this ) );
13498
13499 // Initialization
13500 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
13501 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
13502 this.$element
13503 .addClass( 'oo-ui-toggleSwitchWidget' )
13504 .append( this.$glow, this.$grip );
13505 };
13506
13507 /* Setup */
13508
13509 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
13510 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
13511
13512 /* Methods */
13513
13514 /**
13515 * Handle mouse down events.
13516 *
13517 * @param {jQuery.Event} e Mouse down event
13518 */
13519 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
13520 if ( !this.isDisabled() && e.which === 1 ) {
13521 this.setValue( !this.value );
13522 }
13523 };
13524
13525 }( OO ) );